Total Pageviews

Tuesday, March 01, 2011

Gmail / Facebook Style AJAX Instant Messenger

Introduction

We've developed a simple chat web application for LPHPP intranet http://191.254.186.1 that deals with sql express 2008 to store information about online users, using ASP.NET, VB, SQL Server, Ajax on .NET Framework. 
It is one of the most innovative and easy-to-use chat web service designed for web sites and intranets. It provides an easy and inexpensive way for you to start your own chat community provide your customers with "live support" and real-time consulting  chat events. Everyone loves the gmail and facebook inline chat modules. This ajax based chat module enables you to seamlessly integrate Gmail/Facebook style chat into your existing website.


Features
1. Gmail style modal pop up  display of chat boxes.
2. Auto login through users ipaddress



































3. Displays IP address when name is not in database.
4. Displays “X says…” & start sound(currently disabled) when chat boxes open.
5. close chat boxes
6. Keeps chat boxes open on any  pages of intranet.
7. Auto-scrolling of chat text
8. Auto-back-off polling policy (hits the server less-often when chat activity is low)
9. Extremely simple to integrate into existing site
Demo
Please open the following url  http://191.254.186.1
( the ipaddress is actually not supposed to be used by multiple users at the same time)
Database: You must first create few SQL Express table as below 

1.       IMChats : It contain temporary chat data between sender and recipient and deleted during closing / initiating chat session.
2.       Iplist : contains username with ipaddress. Have more  then 5000 address of allover ntpc.
3.       Onlineusers : it contains list of online users. Updates every 10 seconds and sort them according to lastlogon.
4.       Projects : contains initial 3 octets of ipaddress to get ntpc project name. This database has been disabled cause to decrease load on sqlserver instead a javascript has been used to complete that task since database was small.
Browser Compatibility
1. Firefox 2+
2. Internet Explorer 6+
3. Safari 2+
5.       Opera 9+
6.       Google chrome

How to code (short):
The script does manage rosters (i.e. which users are online etc.), it enables users to chat with each other. I assume your current application may provide that functionality. You must also make sure that SESSION['myIP'] is being set with client ip address when your website session begins. You will understand the logic better after you try the sample files that I have provided at http://191.254.186.1/source.html

(A)    Get a placeholder for onlineusers in ur aspx page. (We have done only in home page)
(b)     Set variables in page load event and create a listener event using javascript for incoming chat request. (It has been done in all web pages)
(c)     using Ajax timer control we will refresh online users.
(d)     A web service is created named chatservice.asmx using chatservice.vb  in App_code folder
'ENQ = chr(5)                            # Request to send
    'EOT = chr(4)                            # Ready to receive
    'ACK = chr(6)                            # Correct reception
    'NAK = chr(21)                           # Incorrect reception
    '////////////////////////////////
    '// Sender init chat
    '////////////////////////////////
    '// Sender ENQ     Wait 4 ACK
    '// Recip  ACK ENQ Wait 4 ACK ACK
    '// Sender ACK ACK Wait 4 EOT
    '// Recip  EOT
    '////////////////////////////////
    '// Recip wait 4 chat
    '////////////////////////////////
    '// Recip  ACK ENQ Wait 4 ACK
    '// Sender ACK ACK Wait 4 EOT
    '// Recip  EOT
(e)    Getting Project list



How to code (Detail):

A.      Get a placeholder for onlineusers in ur aspx page.
A javascript inside head tag

1.     <script type="text/javascript" runat="server">
2.         Function getProject(ByVal ipaddress As String) As String
3.             Dim oct3 As String = Strings.Left(ipaddress, Strings.InStrRev(ipaddress, ".") - 1)
4.             Select Case oct3
5.                 Case "191.254.186", "127.0.0"
6.                     oct3 = ""
7.                 Case "191.254.20"
8.                     oct3 = " - ANTA"
9.                 Case "191.254.16"
10.                   oct3 = " - AURAIYA"
11.               Case "191.254.178"
12.                   oct3 = " - BADARPUR"
13.               Case "191.254.100"
14.                   oct3 = " - BARH"
15.               Case "10.1.249"
16.                   oct3 = " - BONGAIGAON"
17.               Case "10.0.9"
18.                   oct3 = " - CC"
19.               Case "191.254.157"
20.                   oct3 = " - DADRI"
21.               Case "190.190.25"
22.                   oct3 = " - EOC"
23.               Case "191.254.171"
24.                   oct3 = " - ERHQ I"
25.               Case "191.254.186"
26.                   oct3 = " – Loharinag pala"
27.     Case Else
28.                   oct3 = "- ntpc limited "
29.           End Select
30.           Return oct3.ToLower()
31.       End Function
32.   script>


33.   <asp:UpdatePanel ID="UpdatePanel2" runat="server">
34.               <ContentTemplate>
35.                 <div style="width: 139px; height: 197px;  overflow-x: hidden; overflow-y: auto;  white-space:nowrap;" >
36.               <asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="False"
37.               CellPadding="2" ForeColor="#333333"
38.               GridLines="None" Style="position: static"
39.                EmptyDataText="No Users Online" Font-Size="9px" Width="137px" BorderColor="#3399FF"
40.                         BorderStyle="Dotted" BorderWidth="1px"  >
41.               <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
42.                   <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
43.               <Columns>
44.    
45.             <asp:TemplateField  ShowHeader="False">
46.             <ItemTemplate>
47.             <asp:Image ID="Image1" ImageUrl='<%# "images/greendot.gif" %>' runat="server" width="8px" height="8px" />
48.             ItemTemplate>
49.                 <HeaderStyle HorizontalAlign="Center" />
50.                 <ItemStyle HorizontalAlign="Left" Width="8px" />
51.             asp:TemplateField>
52.    
53.             <asp:TemplateField HeaderText="Real Time Chat"  >
54.             <ItemTemplate>
55.                   <a href="javascript:vinModal('<%# Eval("ipaddress") %>');" ><%# Eval("name")%> <font color="maroon"><i> <%# getProject(Eval("ipaddress"))%>i> font>  a>
56.                ItemTemplate>
57.                 <HeaderStyle HorizontalAlign="Left" />
58.                 <ItemStyle HorizontalAlign="Left" />
59.               asp:TemplateField> 
60.               Columns>
61.                   <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
62.               <EmptyDataTemplate>
63.                   No users are online now.
64.               EmptyDataTemplate>
65.                   <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
66.                   <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
67.                   <EditRowStyle BackColor="#999999" />
68.                   <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
69.               asp:GridView>
70.               div>
71.           <asp:Timer ID="Timer1" runat="server" ontick="Timer1_Tick" Interval="10000">
72.    
73.                   asp:Timer>
74.    
75.                ContentTemplate>
76.           asp:UpdatePanel>
77.     
78.    <asp:ModalPopupExtender ID="ModalPopupExtender2" runat="server" TargetControlID="net" PopupControlID="upNet" BackgroundCssClass="modalBackground" dropshadow="true" OkControlID="btnok2"  >asp:ModalPopupExtender>
79.         
80.    
81.    
82.         <div id="chatsection" >
83.           <asp:Panel ID="PanelChatRequest" runat="server" Style="display: none" CssClass="modalheader" scrolling="no" BorderWidth="2px" BorderStyle="Outset" BorderColor="Black">
84.                <center class="modalcontent">    <div id="ChatRequest">
85.                   div>
86.                    <asp:Label ID="Label1" runat="server" Text="Real Time Chat !!" ForeColor="White">asp:Label>
87.                   <asp:ImageButton ID="CancelButton" runat="server" ImageAlign="Right"  CssClass="closemodal"/>
88.                   <p style="text-align: center;">
89.                          <iframe id="chatframe"  width="188" height="200" scrolling="no">iframe>
90.                   p>
91.                   center>
92.               asp:Panel>
93.               <asp:Button runat="server" ID="hiddenTargetControlForModalPopup" style="display:none"/>
94.               <asp:TextBox ID="hiddenSenderUserID" runat="server" style="display:none">asp:TextBox>
95.               <asp:TextBox ID="hiddenMyUserID" runat="server" style="display:none">asp:TextBox>
96.               <asp:TextBox ID="hiddenAppPath" runat="server" style="display:none">asp:TextBox>
97.               <asp:ModalPopupExtender runat="server" ID="programmaticModalPopup"
98.                   BehaviorID="programmaticModalPopupBehaviorChatReq"
99.                   TargetControlID="hiddenTargetControlForModalPopup"
100.                 PopupControlID="PanelChatRequest"
101.                              RepositionMode="RepositionOnWindowResizeAndScroll"
102.                 CancelControlID="CancelButton"
103.                 OnCancelScript="OnCancel()"
104.                 PopupDragHandleControlID = "PanelChatRequest"   >
105.             asp:ModalPopupExtender>
106. div>


A.      Set variables in page load event and create a listener event for incoming chat request
1.  Dim ChatService As New ChatService
2.          Session("myIP") = Request.UserHostAddress   ' for LAN/WAN   or
3.          'Session("myIP") = Request.UserHostAddress + Request.Browser.Browser  'for single PC
4.          'Session("myIP") = Request.UserHostAddress + Str(Now.TimeOfDay.Seconds * Rnd(30))
5.          If Not Page.IsPostBack Then
6.              'this will be executed only first time any event happen on web page
7.   
8.              ChatService.trackOnlineVisitor(Session("myIP"))
9.   
10.             ' Clear user paging/sort
11.            
12.  
13.             Session("CurrentPage") = 0
14.             Session("SortExpression") = Nothing
15.             GridViewSortDirection = "ASC"
16.             ' Set current query
17.             Session("CurrentQuery") = "SELECT LEFT(sub, 35) + '...' AS sub,filename, convert(varchar, cdate, 104) as cdate1, cdate from circulars ORDER BY cdate DESC"
18.             Session("CurrentQuery1") = "SELECT LEFT(topic, 35) + '..  'as topic, filename from articles ORDER BY cdate DESC"
19.             '' setting to show popup should be made in web.config file : inside  
20.             If System.Configuration.ConfigurationManager.AppSettings("showPopup") = "1" Then
21.                 ModalPopupExtender1.Show()
22.             End If
23.  
24.             If Not String.IsNullOrEmpty(Session("eid")) Then
25.                 lblName.Text = "Welcome " + Session("name") + "
Your Visits : "
+ (trackVisitor(Request.UserHostAddress))
26.             Else
27.                 lblName.Text = "Welcome Guest: " + Request.UserHostAddress + "
Your Visits : "
+ (trackVisitor(Request.UserHostAddress)) ' HttpContext.Current.User.Identity.Name +
28.             End If
29.             lblQuotes.Text = getQuotes()
30.  
31.            
32.  
33.  
34.         End If
35.         Dim oQuery = " SELECT        o.ipaddress as ipaddress, o.lastlogon, ISNULL(i.name, o.ipaddress) AS name " & _
36. "FROM            onlineusers AS o LEFT OUTER JOIN " & _
37.                      "iplist AS i ON o.ipaddress = i.ipaddress " & _
38. "ORDER BY o.lastlogon DESC"
39.         ChatService.rebindGridView2(oQuery, gvUsers)
40.  
41.         'this will be executed every time any event happen on web page
42.  
43.         ' Bind GridView to current query & always store ur queery into session("currentquery") before calling
44.         ' reason is whenever page indexed changed or sort.. then it will show data from currentquery
45.         'Response.Write(loadwishes())
46.        
47.         If (Not ClientScript.IsStartupScriptRegistered(Me.GetType(), "vinscript")) Then
48.             ClientScript.RegisterClientScriptBlock(Me.GetType(), "vinscript", loadwishes())
49.         End If
50.        
51.  
52.         ' Request.Browser.Browser
53.         ' Session("myIP") = Request.UserHostAddress '+ Str(Now.TimeOfDay.Seconds * Rnd(30))
54.  
55.         ' End If
56.         If Not String.IsNullOrEmpty(Session("myIP")) Then '  If Not String.IsNullOrEmpty(Page.User.Identity.Name) Then
57.             hiddenAppPath.Text = Request.ServerVariables("SERVER_NAME") & ":" & Request.ServerVariables("SERVER_PORT") & Request.ApplicationPath()
58.  
59.             Dim csname As String = "CheckChatReq"
60.             Dim cstype As Type = Me.GetType()
61.             Dim cs As ClientScriptManager = Page.ClientScript
62.             If (Not cs.IsClientScriptBlockRegistered(cstype, csname)) Then
63.                 Dim cstext As New StringBuilder()
64.                 cstext.Append("var DelayInSeconds = 12;" & vbCrLf)
65.                 cstext.Append("function InitCheckChatReq(strMyUserID) {" & vbCrLf)
66.                 cstext.Append("    setTimeout(""CheckChatReq('"" + strMyUserID + ""')"", DelayInSeconds * 1000);" & vbCrLf)
67.                 cstext.Append("}" & vbCrLf)
68.                 cstext.Append("function CheckChatReq(strMyUserID) {" & vbCrLf)
69.                 cstext.Append("    ret = ChatService.CheckChatReq(strMyUserID, CheckChatReqOnComplete, CheckChatReqOnTimeout);" & vbCrLf)
70.                 cstext.Append("    document.getElementById('" & hiddenMyUserID.ClientID & "').value = strMyUserID;" & vbCrLf)
71.                 cstext.Append("}" & vbCrLf)
72.                 cstext.Append("function CheckChatReqOnComplete(strSenderUserID) {" & vbCrLf)  'this will listen for request so init =0 and open a popup
73.                 cstext.Append("    if (strSenderUserID != """")" & vbCrLf)
74.                 cstext.Append("    {" & vbCrLf)
75.                 cstext.Append("        var popupWindow = null;" & vbCrLf)
76.                 cstext.Append("        document.getElementById('" & hiddenSenderUserID.ClientID & "').value = strSenderUserID;" & vbCrLf)
77.                 cstext.Append("   //     document.getElementById('ChatRequest').innerHTML = ""
""" & vbCrLf)
78.                 cstext.Append("  //          + ""You have an incoming chat request from: '"" + strSenderUserID + ""'

"""
& vbCrLf)
79.                 cstext.Append("  //          + ""Would you like to accept?
"";" & vbCrLf)
80.                 cstext.Append("    var strSenderUserID = document.getElementById('" & hiddenSenderUserID.ClientID & "').value;" & vbCrLf)
81.                 cstext.Append("    var strMyUserID = document.getElementById('" & hiddenMyUserID.ClientID & "').value;" & vbCrLf)
82.                 cstext.Append("    var strAppPath = document.getElementById('" & hiddenAppPath.ClientID & "').value;" & vbCrLf)
83.                 cstext.Append("     $get('chatframe').src='http://' + strAppPath + '/chat.aspx?Usr=' + strSenderUserID + '&Init=0';" & vbCrLf)
84.                 cstext.Append("      var modalPopupBehavior = $find('programmaticModalPopupBehaviorChatReq');" & vbCrLf)
85.                 cstext.Append("      modalPopupBehavior.show();" & vbCrLf)
86.                 cstext.Append(" //  redirect('http://' + strAppPath + '/chat.aspx?Usr=' + strSenderUserID + '&Init=0');" & vbCrLf)
87.                 cstext.Append("  // window.location = 'http://' + strAppPath + '/chat.aspx?Usr=' + strSenderUserID + '&Init=0';" & vbCrLf)
88.                 cstext.Append("  // popupWindow = window.open('http://' + strAppPath + '/chat.aspx?Usr=' + strSenderUserID + '&Init=0');" & vbCrLf)
89.                 cstext.Append("   setTimeout(""CheckChatReq('"" + strMyUserID + ""')"", 1000);" & vbCrLf)
90.                 cstext.Append("   }" & vbCrLf)
91.                 cstext.Append("     else" & vbCrLf)
92.                 cstext.Append("    {" & vbCrLf)
93.                 cstext.Append("        var strMyUserID = document.getElementById('" & hiddenMyUserID.ClientID & "').value;" & vbCrLf)
94.                 cstext.Append("        setTimeout(""CheckChatReq('"" + strMyUserID + ""')"", DelayInSeconds * 1000);" & vbCrLf)
95.                 cstext.Append("    }" & vbCrLf)
96.                 cstext.Append("}" & vbCrLf)
97.                 cstext.Append("function vinModal( strOther) {" & vbCrLf)  'this will call other person window so init =1
98.                 cstext.Append("        var popupWindow = null;" & vbCrLf)
99.                 cstext.Append("        document.getElementById('" & hiddenSenderUserID.ClientID & "').value = strOther;" & vbCrLf)
100.                    cstext.Append("    var strSenderUserID = document.getElementById('" & hiddenSenderUserID.ClientID & "').value;" & vbCrLf)
101.                    cstext.Append("    var strMyUserID = document.getElementById('" & hiddenMyUserID.ClientID & "').value;" & vbCrLf)
102.                    cstext.Append("    var strAppPath = document.getElementById('" & hiddenAppPath.ClientID & "').value;" & vbCrLf)
103.                    cstext.Append("     $get('chatframe').src= 'chat.aspx?Usr=' +  strSenderUserID+ '&Init=1';" & vbCrLf)
104.                    cstext.Append("      var modalPopupBehavior = $find('programmaticModalPopupBehaviorChatReq');" & vbCrLf)
105.                    cstext.Append("      modalPopupBehavior.show();" & vbCrLf)
106.                    cstext.Append(" //movePanel();" & vbCrLf)
107.                    cstext.Append("  }" & vbCrLf)
108.                    cstext.Append("var id = null; " & vbCrLf)
109.                    cstext.Append("function movePanel() { " & vbCrLf)
110.                    cstext.Append("  var pnl = $get('PanelChatRequest'); " & vbCrLf)
111.                    cstext.Append(" if (pnl != null) { " & vbCrLf)
112.                    cstext.Append("  pnl.style.top = '200'; " & vbCrLf)
113.                    cstext.Append("  pnl.style.left =  '200'; } " & vbCrLf)
114.                    cstext.Append(" id = setTimeout('movePanel();', 100);" & vbCrLf)
115.                    cstext.Append("}" & vbCrLf)
116.                    cstext.Append(" function stopMoving() { " & vbCrLf)
117.                    cstext.Append(" clearTimeout(id);" & vbCrLf)
118.                    cstext.Append("}" & vbCrLf)
119.                    cstext.Append("function CheckChatReqOnTimeout(strSenderUserID) {" & vbCrLf)
120.                    cstext.Append("    var strMyUserID = document.getElementById('" & hiddenMyUserID.ClientID & "').value;" & vbCrLf)
121.                    cstext.Append("    setTimeout(""CheckChatReq('"" + strMyUserID + ""')"", DelayInSeconds * 1000);" & vbCrLf)
122.                    cstext.Append("}" & vbCrLf)
123.                    cstext.Append("function OnOk() {" & vbCrLf)
124.                    cstext.Append("    var strSenderUserID = document.getElementById('" & hiddenSenderUserID.ClientID & "').value;" & vbCrLf)
125.                    cstext.Append("    var strMyUserID = document.getElementById('" & hiddenMyUserID.ClientID & "').value;" & vbCrLf)
126.                    cstext.Append("    var strAppPath = document.getElementById('" & hiddenAppPath.ClientID & "').value;" & vbCrLf)
127.                    cstext.Append("  // var w = window.open();" & vbCrLf)
128.                    cstext.Append("  // w.opener = null;" & vbCrLf)
129.                    cstext.Append("  // w.document.location = 'http://' + strAppPath + '/chat.aspx?Usr=' + strSenderUserID + '&Init=0';" & vbCrLf)
130.                    cstext.Append("  // window.location = 'http://' + strAppPath + '/chat.aspx?Usr=' + strSenderUserID + '&Init=0';" & vbCrLf)
131.                    cstext.Append(" //   popupWindow = window.open('http://' + strAppPath + '/chat.aspx?Usr=' + strSenderUserID + '&Init=0');" & vbCrLf)
132.                    cstext.Append("    setTimeout(""CheckChatReq('"" + strMyUserID + ""')"", 1000);" & vbCrLf)
133.                    cstext.Append("}" & vbCrLf)
134.                    cstext.Append("function OnCancel() {" & vbCrLf)
135.                    cstext.Append("    var strSenderUserID = document.getElementById('" & hiddenSenderUserID.ClientID & "').value;" & vbCrLf)
136.                    cstext.Append("    var strMyUserID = document.getElementById('" & hiddenMyUserID.ClientID & "').value;" & vbCrLf)
137.                    cstext.Append("    ret = ChatService.SendNak(strMyUserID, strSenderUserID);" & vbCrLf)
138.                    cstext.Append("    setTimeout(""CheckChatReq('"" + strMyUserID + ""')"", 1000);" & vbCrLf)
139.                    cstext.Append("//stopMoving();" & vbCrLf)
140.                    cstext.Append("  }" & vbCrLf)
141.     
142.                    cs.RegisterClientScriptBlock(cstype, csname, cstext.ToString, True)
143.                End If
144.     
145.                ' Dim strScript As String = "InitCheckChatReq('" & HttpUtility.UrlEncode(Page.User.Identity.Name) & "');"
146.                Dim strScript As String = "InitCheckChatReq('" & Session("myIP") & "');"
147.                csname = "InitCheckChatReq"
148.                cs = Page.ClientScript
149.                If (Not cs.IsStartupScriptRegistered(cstype, csname)) Then
150.                    cs.RegisterStartupScript(cstype, csname, strScript, True)
151.                End If
152.     
153.            End If
154.          
155.     
156.            'rebindGridView(Session("CurrentQuery"), gvCirculars)
157.            'rebindGridView(Session("CurrentQuery1"), gvArticles)
158.            rebindCachedGridView(Session("CurrentQuery"), gvCirculars, "gvCirculars")
159.            rebindCachedGridView(Session("CurrentQuery1"), gvArticles, "gvArticles")
160.     


A.      using Ajax timer control we will refresh online users.
1.  Protected Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick
2.          Dim ChatService As New ChatService
3.          ChatService.trackOnlineVisitor(Session("myIP"))
4.          ' rebindGridView2("select * from onlineusers", gvUsers)
5.          Dim oQuery = " SELECT        o.ipaddress as ipaddress, o.lastlogon, ISNULL(i.name, o.ipaddress) AS name " & _
6.  "FROM            onlineusers AS o LEFT OUTER JOIN " & _
7.                         "iplist AS i ON o.ipaddress = i.ipaddress " & _
8.  "ORDER BY o.lastlogon DESC"
9.          ChatService.rebindGridView2(oQuery, gvUsers)
10.     End Sub


A.    . A web service is created named chatservice.asmx using chatservice.vb  in App_code folder

1.        ' ASPDOTNETAJAXIM - Copyright 2010 Vinod Kotiya
2.       Imports System.Web
3.       Imports System.Web.Services
4.       Imports System.Web.Services.Protocols
5.        Imports System.Data.SqlClient
6.       Imports System.Data




No comments: