Google Talk (GTalk) Autoreply using .NET

Posted by: Shoban Kumar , on 7/4/2009, in Category WinForms & WinRT
Views: 184239
Abstract: In this article, we will see how you can develop a simple Gtalk client using .NET using which you can notify your users that you are away from your desk.
Google Talk (GTalk) Autoreply using .NET
 
In this article we will see how you can develop a simple GTalk client using .NET using which you can notify your users that you are away from your desk. This article will also discuss how to use the Extensible Messaging and Presence Protocol (XMPP) protocol libraries. GTalk services are built on the XMPP protocol. The article is primarily in VB.NET, but C# code has also been mentioned in the article. Below is the screenshot of how our application will look like.




 
Auto Reply
Below is the screenshot of our application in action. 
Auto Message
Before getting started with the application, it is important for you to learn a little about Extensible Messaging and Presence Protocol (XMPP). According to www.xmpp.org
The Extensible Messaging and Presence Protocol (XMPP) is an open technology for real-time communication, which powers a wide range of applications including instant messaging, presence, multi-party chat, voice and video calls, collaboration, lightweight middleware, content syndication, and generalized routing of XML data.
You can learn more about XMPP at www.xmpp.org. Google Talk services is built on XMPP protocol. This allows us to build clients which can connect to Google Talk.
There are lots of XMPP libraries available for .NET. I am going to use agsXMPP .NET library. You can download the free library from its home page. http://www.ag-software.de/index.php?page=agsxmpp-sdk
Let us get started.
Step 1:    Open Visual Studio and create a new Windows Forms Application.
 
Step 2:    Add the following controls to the form.
 
a.    TextBox : txtUserName, txtPassword, txtMessage
b.    CheckBox : chkStartAutomatic
c.    Button : btnSave
d.    Label : lblStatus
 
Step 3:    I have also added few ‘Application Settings Variables’ which are detailed below:
 
a.    UserName : String
b.    Password : String
c.    AutomaticStart : Boolean
d.    Message : String

Step 4:    Add the following code to import the required classes
 
C#
 
using agsXMPP;
using Microsoft.Win32;
 
 
VB.NET
 
Imports agsXMPP
Imports Microsoft.Win32
 
 
Step 5:    Add the following code to the class
 
C#
 
agsXMPP.XmppClientConnection objXmpp
 
 
VB.NET
 
Dim objXmpp As agsXMPP.XmppClientConnection
 
 
Step 6:    Double click the form and add the following code to Form’s Load event.
 
C#
 
Control.CheckForIllegalCrossThreadCalls = false;
//Load settings
txtUserName.Text = Gtalk_Autoreply_Cshap.Properties.Settings.Default.Username;
txtPassword.Text = Gtalk_Autoreply_Cshap.Properties.Settings.Default.Password;
txtMessage.Text = Gtalk_Autoreply_Cshap.Properties.Settings.Default.Message;
if(Gtalk_Autoreply_Cshap.Properties.Settings.Default.AutoLogin == true)
   chkStartAutomatic.Checked = true;
else
   chkStartAutomatic.Checked = false;
 
 
VB.NET
 
Control.CheckForIllegalCrossThreadCalls = False
    'Load settings
txtUserName.Text = My.Settings.UserName
txtPassword.Text = My.Settings.Password
txtMessage.Text = My.Settings.Message
If My.Settings.AutomaticStart = True Then
 chkStartAutomatic.Checked = True
Else
 chkStartAutomatic.Checked = False
End If 
         
 In a short while, you will see that we will be saving user details in the application variables. In the above code we are just loading them to the appropriate controls.
 
Note: It is not advisable to set ‘CheckForIllegalCrossThreadCalls’ to False. This is not a good solution to be used in a production application.
 
Step 7:    Add the following code to ChkStartAutomatic’s CheckedChanged Status. This code will add the required values to the registry there by allowing the user to start the application automatically on Windows Startup.
C#
 
if (chkStartAutomatic.Checked == true)
{
      Properties.Settings.Default.AutomaticStart = true;
      RegistryKey regKey = null;
      regKey = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run", true);
      regKey.SetValue(Application.ProductName, Application.ExecutablePath);
      regKey.Close();
}
else
{
      Properties.Settings.Default.AutomaticStart = false;
      RegistryKey regKey = null;
      regKey = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run", true);
      regKey.DeleteValue(Application.ProductName);
      regKey.Close();
}
 
VB.NET
 
 
If chkStartAutomatic.Checked = True Then
    My.Settings.AutomaticStart = True
    Dim regKey As RegistryKey
    regKey = Registry.CurrentUser.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", True)
    regKey.SetValue(Application.ProductName, Application.ExecutablePath)
    regKey.Close()
Else
    My.Settings.AutomaticStart = False
    Dim regKey As RegistryKey
    regKey = Registry.CurrentUser.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", True)
    regKey.DeleteValue(Application.ProductName)
    regKey.Close()
End If
 
Step 8:    The following code in btnSave’s Click Event will do the job of doing basic validation, Login to Gmail and wait for a message. You will see that we have added 3 handlers for onMessage, onAuthError and onLogin. These handlers will take care of Sending the Autoreply, handling Authentication error if the Username/Password is incorrect and the necessary settings when the login is successful.

C#
 
if (txtUserName.Text.Trim() == "")
{
lblStatus.Text = "Please enter Username.";
txtUserName.Focus();
return;
}
 
if (txtPassword.Text.Trim() == "")
{
lblStatus.Text = "Please enter Password.";
txtPassword.Focus();
return;
}
 
if (txtMessage.Text.Trim() == "")
{
lblStatus.Text = "Please enter Message.";
txtMessage.Focus();
return;
}
 
lblStatus.Text = "Logging in. Please wait...";
objXmpp = new agsXMPP.XmppClientConnection();
agsXMPP.Jid jid = null;
jid = new agsXMPP.Jid(txtUserName.Text.Trim() + "@gmail.com");
objXmpp.Password = txtPassword.Text.Trim();
objXmpp.Username = jid.User;
objXmpp.Server = jid.Server;
objXmpp.AutoResolveConnectServer = true;
 
try
{
objXmpp.OnMessage += messageReceived;
objXmpp.OnAuthError += loginFailed;
objXmpp.OnLogin += loggedIn;
objXmpp.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
} 
 
VB.NET
 
If txtUserName.Text.Trim = "" Then
    lblStatus.Text = "Please enter Username."
    txtUserName.Focus()
    Exit Sub
End If
 
If txtPassword.Text.Trim = "" Then
    lblStatus.Text = "Please enter Password."
    txtPassword.Focus()
    Exit Sub
End If
 
If txtMessage.Text.Trim = "" Then
    lblStatus.Text = "Please enter Message."
    txtMessage.Focus()
    Exit Sub
End If
 
lblStatus.Text = "Logging in. Please wait..."
objXmpp = New agsXMPP.XmppClientConnection
    Dim jid As agsXMPP.Jid
jid = New agsXMPP.Jid(txtUserName.Text.Trim + "@gmail.com")
objXmpp.Password = txtPassword.Text.Trim
objXmpp.Username = jid.User
objXmpp.Server = jid.Server
objXmpp.AutoResolveConnectServer = True
 
Try
    AddHandler objXmpp.OnMessage, AddressOf messageReceived
    AddHandler objXmpp.OnAuthError, AddressOf loginFailed
    AddHandler objXmpp.OnLogin, AddressOf loggedIn
    objXmpp.Open()
Catch ex As Exception
    MsgBox(ex.Message)
End Try
 
 
Step 9:    Below is the code for the three functions messageReceived, loginFailed and loggedIn

C#
 
private void messageReceived(object sender, protocol.client.Message msg)
{
        string[] chatMessage = null;
        chatMessage = msg.From.ToString().Split('/');
        agsXMPP.Jid jid = null;
        jid = new agsXMPP.Jid(chatMessage[0]);
        protocol.client.Message autoReply = null;
        autoReply = new protocol.client.Message(jid, protocol.client.MessageType.chat, txtMessage.Text);
        objXmpp.Send(autoReply);
}
 
VB.NET
 
Private Sub messageReceived(ByVal sender As Object, ByVal msg As protocol.client.Message)
Dim chatMessage() As String
chatMessage = msg.From.ToString.Split("/")
Dim jid As agsXMPP.Jid
jid = New agsXMPP.Jid(chatMessage(0))
Dim autoReply As protocol.client.Message
autoReply = New protocol.client.Message(jid, protocol.client.MessageType.chat, txtMessage.Text)
objXmpp.Send(autoReply)
End Sub
 
The above code gets executed whenever a new message is received.
C#
 
private void loginFailed( object o,agsXMPP.Xml.Dom.Element el)
{
         this.Show();
         lblStatus.Text = "Login failed. Please check your details.";
}
 
VB.NET
 
Private Sub loginFailed()
       Me.Show()
       lblStatus.Text = "Login failed. Please check your details."
End Sub
 
 The above code gets execute when login fails.
 
C#
 
private void loggedIn()
{
    this.Hide();
    NotifyIcon.Visible = true;
    lblStatus.Text = "Logged in and Active.";
    Properties.Settings.Default.UserName = txtUserName.Text.Trim();
    Properties.Settings.Default.Password = txtPassword.Text.Trim();
    Properties.Settings.Default.Message = txtMessage.Text;
}
 
 
VB.NET
           
Private Sub loggedIn()
        Me.Hide()
        NotifyIcon.Visible = True
        lblStatus.Text = "Logged in and Active."
        My.Settings.UserName = txtUserName.Text.Trim
        My.Settings.Password = txtPassword.Text.Trim
        My.Settings.Message = txtMessage.Text
End Sub
 
 
On Successful login, the above code saves user’s settings to application variables and hides the form.
 
Step 10: Save and Run the application. Now every time when you are away from your machine, you can run this application and notify anyone, who pings you, with an auto reply. Cool!
 
The source code of this article can be downloaded from here 
If you liked the article,  Subscribe to the RSS Feed or Subscribe Via Email
 
ShobanKumar, is a 23 year old Client App Dev MVP from Trivandrum mainly working on ASP, ASP.NET, VB, VB.NET and PHP. You can also find him blogging at www.crankup.net and www.codegeeks.net. Follow him on twitter @shobankr 
 

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
ShobanKumar is an ex-Microsoft MVP in SharePoint who currently works as a SharePoint Consultant. You can read more about his projects at http://shobankumar.com. You can also follow him on twitter @shobankr


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Bipin on Friday, July 17, 2009 2:45 AM
I'm getting this error message when i tried to implement this coding using C#.
No overload for 'loggedIn' matches delegate 'agsXMPP.ObjectHandler'.

private void btn_enable_Click(object sender, EventArgs e)
        {
            if (txt_username.Text.Trim() == "")
            {
                lbl_status.Text = "Please Enter The Username...";
                txt_username.Focus();
                return;
            }
            if (txt_password.Text.Trim() == "")
            {
                lbl_status.Text = "Please Enter The Password...";
                txt_password.Focus();
                return;
            }
            if (txt_message.Text.Trim() == "")
            {
                lbl_status.Text = "Please Enter The Message...";
                txt_message.Focus();
                return;
            }
            lbl_status.Text = "Logging in...";
            objXmpp = new agsXMPP.XmppClientConnection();
            agsXMPP.Jid jid = null;
            jid = new agsXMPP.Jid(txt_username.Text.Trim() + "@gmail.com");
            objXmpp.Username = jid.User;
            objXmpp.Server = jid.Server;
            objXmpp.AutoResolveConnectServer = true;
            try
            {
                objXmpp.OnMessage += messageReceived;
                objXmpp.OnAuthError += loginFailed;
                objXmpp.OnLogin += loggedIn;
                objXmpp.Open();
            }
Comment posted by Bipin on Friday, July 17, 2009 2:46 AM
Please somebody help me....
Comment posted by Shoban Kumar on Saturday, July 18, 2009 4:33 AM
Hi Bipin

Can you send me the source code? I will check it. Email : shobankr[at]gmail.com
Comment posted by Alexander Gnauck on Thursday, July 23, 2009 5:08 AM
you don't have to Split the From adress. agsXMPP does this for you. Look at the Bare property.
Comment posted by Guest on Sunday, August 2, 2009 10:17 AM
Awesome work buddy!
Comment posted by flai on Sunday, October 18, 2009 9:21 AM
May you show full c# code&&&
Comment posted by Sruthi on Tuesday, October 20, 2009 3:08 AM
Awesome work...
Comment posted by santosh kakani on Saturday, November 14, 2009 6:10 AM
What is Gtalk_Autoreply_Cshap in this code for which we are setting username and password
where is its source ?

in step6
i downloaded librarys and used reference to agsXMPP.dll

can you tell me what dlls i need to import before writing this code please
Comment posted by Soufiane Tahiri on Sunday, December 20, 2009 10:54 AM
nice work ,
@Kakani : add to tour references agsXMPP.dll and Imports agsXMPP everything said !
Comment posted by Amit on Wednesday, January 27, 2010 2:46 PM
it is not working.... it just diaplays the message logging in and then nothing happens
Comment posted by Shoban Kumar on Sunday, January 31, 2010 1:08 AM
@Amit
Dd you try running the attached source code download? Are you behind any firewall?
Comment posted by Luis on Friday, June 25, 2010 3:54 AM
Thanks for sharing this with us. Can post a simple code for sending a message? (not a reply just a message). I wanted to use this when I need to override the bot.

Keep up the good work!

Comment posted by Luis on Friday, June 25, 2010 6:05 AM
Thanks for sharing this with us. Can post a simple code for sending a message? (not a reply just a message). I wanted to use this when I need to override the bot.

Keep up the good work!

Comment posted by mohammed on Friday, September 10, 2010 7:16 PM
hi
Comment posted by gene on Friday, December 3, 2010 7:52 AM
thank you for the effort, but this is really sloppy job. in just a few lines of code there are so many errors, omissions... the download is not worth anything. if you're doing something for others, do it well, otherwise there's more grief than good.
Comment posted by kinaung5 on Wednesday, December 29, 2010 11:27 PM
hi i am soo busy now please wait for me please call me back................bay..............bay...........
Comment posted by habibie on Monday, March 21, 2011 3:11 AM
i'm using Windown 7, vb.net 2010, .NET firmwork 4.0, that source not work.. can you help me..?
Comment posted by Aung Win on Saturday, April 23, 2011 12:23 AM
Error Occur when I open Gtalk Autoreply.vbproj with vb.net 2005 from source code zip please help me..
Comment posted by ghada ben attia on Saturday, October 22, 2011 3:54 PM
اشهد ان لا الاه الا الله و اشهد ان محمد رسول الله
Comment posted by Samuel on Saturday, November 5, 2011 3:34 PM
can you help me?
im using visual c# 2010 and .net 4
the error is: using agsXMPP is wrong. i'm missing assemby reference. when i tried to add it in resouces folder, i did'n find it. what shoud i do?
Comment posted by natkhat on Saturday, December 24, 2011 3:23 AM
that post is very confuse difficult to understand diametrically not clear
Comment posted by Akbar on Tuesday, February 28, 2012 3:01 AM
This works with jid.server = @gmail   Only. it is not taking any other customized Gtalk servers like username@yourdomain.com while i am able to log in to Gtalk with the ID
Comment posted by km on Saturday, August 4, 2012 4:28 AM
http://np.codeplex.com has an alternate autoreply implementation which seems to work globally across the entire contact list as well as on a per contact basis..
Comment posted by Shane on Tuesday, August 21, 2012 4:46 PM
I found out, if you are logged in google mail, this doesn't catch the incoming messages...is this correct?
Comment posted by asd on Tuesday, January 28, 2014 7:26 AM
sadad
Comment posted by Zeind on Wednesday, February 5, 2014 9:46 AM
how to can receive incoming messages on this application ?
Comment posted by amrit on Tuesday, February 25, 2014 11:21 PM
Hi
Great Job. i m try after download the code. it sent every message 3 Time to G-Talk. kindly sent me to resolve it.
Thanks
Comment posted by ravikant on Thursday, June 19, 2014 2:02 AM
i try c# code
everithing is fine
but one error is showing
No overload for 'loggedIn' matches delegate 'agsXMPP.ObjectHandler'
Comment posted by ravikant on Thursday, June 19, 2014 2:12 AM
i try c# code
everithing is fine
but one error is showing
No overload for 'loggedIn' matches delegate 'agsXMPP.ObjectHandler'
Comment posted by ashokkumar on Monday, August 11, 2014 4:31 AM
hi friends can anyone help me how to integrate Gtalk and yahoo mesenger in my Dot Net application responsive web site. we are using share tips proving company so please any one send the code.
Comment posted by Amir Hirani on Wednesday, September 17, 2014 12:27 AM
HiShobanKumar,
            I am using your gtalk autoreply code its awesome working superb,i want to implement it in yahoo messenger i tried using many yaho messenger server name n port,can u help to solve this issue that how to connect yahoo through agsxmpp dll,Please mail me code if possible