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.
Below is the screenshot of our application in action.
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.
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
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.
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!
Was this article worth reading? Share it with fellow developers too. Thanks!
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