Click here to Skip to main content
15,897,371 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone,

I have an problem with events and delegates. Basically i have two projects under same solution. One project is the server and other is the client. The client form contains a textbox for login and login button, rich textbox and button for whisper. Now when the user clicks on whisper the RTB of the client to whom message is sent has to be updated with the message but in my case i am recieving an exception saying object not set to instance. The code for server and client are has follows

Client code

C#
namespace ChatClient
{
    [CallbackBehavior(UseSynchronizationContext = false)]
    public partial class Client : Form,IChatCallback
    {
        public delegate void ReceiveMsg(string sender, string message);
        public event ReceiveMsg Receivemessage;

        IChat chatter = null;
        DuplexChannelFactory<ichat> connect;
        InstanceContext instanceContext = null;

        
        public string CurrentUser;
        public Client()
        {
            InitializeComponent();
            
        }

        

        private void login_btn_Click(object sender, EventArgs e)
        {
            //CallBackHandler instance = new CallBackHandler();
            //instanceContext = new InstanceContext(new CallBackHandler());
            Client instance = new Client();
            instanceContext = new InstanceContext(new Client());
          
            connect = new DuplexChannelFactory<ichat>(instanceContext, "TcpBinding");
            chatter = connect.CreateChannel();
            
            if (!string.IsNullOrEmpty(login_txt.Text))
            {
                CurrentUser = login_txt.Text;
                chatter.JoinChat(CurrentUser);
               
            }
            else
            {
                MessageBox.Show("Please Enter Valid UserName", "WARNING", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void whispher_btn_Click(object sender, EventArgs e)
        {
            
            chatter.SendMessage(login_txt.Text, rtxt_message.Text);
            //Trigger event
            Receivemessage(login_txt.Text, rtxt_message.Text);
            //after execution of this statement it throws object reference not set
            //to the instance
                      
            
        }



        #region IChatCallback Members

        public void ReceiveMessage(string from, string message)
        {
            
             rtxt_message.AppendText("hellO");
            
        }
</ichat></ichat>


Server code

<pre lang="c#">namespace WCFChat
{
    [ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall,ConcurrencyMode=ConcurrencyMode.Reentrant)]
    class ChatServer:IChat
    {
        //public delegate void ReceiveMsg(string sender, string message);
        //public event ReceiveMsg Receivemessage;

        IChatCallback callback = null;
        Client cs = new Client();
        public static Dictionary<string,> ListofUsers = new Dictionary<string,>();
        public void JoinChat(string username)
        {
            callback = OperationContext.Current.GetCallbackChannel<ichatcallback>();
            if (CheckUserExists(username) == true)
            {
                ListofUsers.Add(username, callback);
                
            }
            else
            {
                MessageBox.Show("Username already exixts!: Please select different Name");
            }
            ListofUsers.ToArray();
            
        }

        public void SendMessage(string sender, string message)
        {
            foreach (string str in ListofUsers.Keys)
            {
                if (str == "abc")
                {
                    
                    IChatCallback icall = ListofUsers[str];
                    icall.ReceiveMessage(sender,message);
                    //registering for the event on client side
                    cs.Receivemessage+=new Client.ReceiveMsg(icall.ReceiveMessage);
                    
                    
                }
            }
        }

        public void LeaveChat(string name)
        {
        }

        //public string[] GetOnlineUsers()
        //{
        //    return ;
        //}

        public bool CheckUserExists(string username)
        {
            foreach (string name in ListofUsers.Keys)
            {
                if(username.Equals(name,StringComparison.OrdinalIgnoreCase))
                     return false;
            }
            return true;
        }
    }
}</ichatcallback>
Posted
Comments
BillWoodruff 23-Oct-11 3:31am    
Is this an ASP.NET project: is there an actual server (IIS ?) being used here ?
manu g m 23-Oct-11 3:32am    
no this is not ASP.net its windows project.

1 solution

It's difficult to tell from that code fragment, but if
rtxt_message.AppendText("hellO");
causes an event to be fired then there are two thing you need to check:
1) Is rtxt_message set to an instance of your class?
2) In AppendText, do you check for an event handler before triggering it?
My default format for an event trigger is:
C#
public event EventHandler Changed;

protected virtual void OnChanged(EventArgs e)
   {
   EventHandler eh = Changed;
   if (eh != null)
      {
      eh(this, e);
      }
   }
If you do not check for an handler before trying to trigger the event, you will get a null reference exception.

If this doesn't help, then you are going to have to either give us better information, or use a breakpoint and single step into each line until you find the null value.
 
Share this answer
 
Comments
manu g m 23-Oct-11 5:08am    
My scenario is like, i have two different classes one is for server and other is for client. Server class doesnot contain any contorls its just a seperate class. And in client form i have all the controls button and textboxes. So when i subscribe for event in server class as show in code and fire tat event on Whisper button click i get exception. I want this even to be fired at any cost on button click. How can i modify my code to make it work without exception

Thank you for the reply.
manu g m 23-Oct-11 5:11am    
On SendMessage method of server class ill be subscribing to the event. And in the Whisper_buttonCLick ill be firing this event. But ReceiveMessage(login_txt.text,rtxt_message.text) will throw an exception on button click. How to make this to fire the event.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900