65.9K
CodeProject is changing. Read more.
Home

Live Chat - Template Code

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.83/5 (11 votes)

Oct 15, 2010

CPOL

1 min read

viewsIcon

76547

downloadIcon

5825

How to create a web Live Chat via C# ASP.NET + jQuery/AJAX

Introduction

I was looking around for some code for a Live Chat feature for a .NET application. (The kind where you can talk with a technician at a company, not an instant messenger). I didn't see anything, so I wrote some base code to do it here.

Background

This uses jQuery & Ajax calls. Also uses the http://json.org/json2.js for encoding strings into json.
Performance hit: It just polls the server for messages (because it's not a client-app).
Also: There's a bunch of dummy code in there that would be replaced with connections to a database. I'm currently using the Session.ClientLCID to uniquely identify a session. If you had users logging in, you'd replace that with user Ids.

(Not enough commenting in code. I will try to improve this, but since I'm not sure anybody will look at this....... I may just let you figure it out yourself.)

What does the Code Look Like?

So, the HTML is pretty simple.

<input type="hidden" id="LastUpdateId" value="0" />
<input type="hidden" id="ConversationId" value="0" />
<div id="result"></div>
<textarea id="message"></textarea>
<input type="button" id="send" value="send" />

The C# isn't too bad either:

 [WebMethod]
public static IEnumerable<IMailUpdate> 
	GetUpdates(int ConversationId, int LastUpdateId) {
    Conversation c = DAC.GetConversation(ConversationId);
    CheckConversationAccess(c);
    return c.GetUpdatesAfter(LastUpdateId);
}

[WebMethod]
public static string SendUpdate(int ConversationId, string update) {
    Conversation c = DAC.GetConversation(ConversationId);
    CheckConversationAccess(c);

    MailUpdate item = new MailUpdate();
    item.Author = SessionStateSink.IsTechnician ? 
	"Technician" : "Client";//you should populate this from user information.
    item.CssClass = SessionStateSink.IsTechnician ? 
	"tech" : "client";//you can leave this or find a different way of handling it.
    item.TimeStamp = DateTime.Now;
    item.Message = update;
    item.Save();

    return "";
}

The jQuery / AJAX is where it gets a little fun:

//Sending the data!

$.ajax({ 
    timeout: 15000, 
    type: "POST",
    cache: false, 
    contentType: "application/json; charset=utf-8", dataType: 'json',
    url: 'chat.aspx/SendUpdate',
    data: '{ConversationId:' + $("#ConversationId")[0].value + 
	',update:' + JSON.stringify(message) + '}'
}); 
//Receiving the Data! 
$.ajax({
    timeout: 15000, 
    type: "POST",
    cache: false, 
    contentType: "application/json; charset=utf-8", 
    dataType: 'json',  
    url: 'chat.aspx/GetUpdates',
    data: '{ConversationId:' + $("#ConversationId")[0].value + 
	',LastUpdateId:' + $("#LastUpdateId")[0].value + '}',
    success: chat_populateItems
});
//Populating the Data! (Data displayed here is 
//reflective of the custom IMailMessage interface)
function chat_populateItems(data) {
    for (var index = 0; index < data.d.length; index++) {
        var item = data.d[index];
        if ($('#update' + item.UpdateId).length == 0) {
            var text = "(" + item.DateString + ") " + 
			item.Author + ": " + item.Message;
            $('#result').append("<div id='update" + item.Id + 
		"' class='" + item.CssClass + "' />").children(":last").text(text);
        }
    }
    if (data.d.length > 0) {
        $("#LastUpdateId")[0].value = data.d[data.d.length - 1].Id;
    }
} 

Note: I dropped error functions (etc.) out of the code above, to make it simpler to read here.

If you have questions or comments, please post!