Click here to Skip to main content
Click here to Skip to main content

Live Chat - Template Code

, 18 Oct 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
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!

License

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

Share

About the Author

ColinBashBash
Software Developer
United States United States
likes boardgames, computer games, and enjoys his .net programming job.

Comments and Discussions

 
GeneralMy vote of 4 Pinmembershani_75930-Dec-12 21:04 
Questionfile damaged PinmemberAteşG3-Aug-12 5:07 
AnswerRe: file damaged PinmemberColinBashBash3-Aug-12 5:12 
GeneralRe: file damaged PinmemberAteşG3-Aug-12 5:27 
GeneralRe: file damaged PinmemberAteşG3-Aug-12 6:11 
QuestionGood stuff!! will try to improve and send back any comments! some question at last.. PinmemberAndyHo21-May-12 5:19 
AnswerRe: Good stuff!! will try to improve and send back any comments! some question at last.. PinmemberColinBashBash21-May-12 5:31 
GeneralRe: Good stuff!! will try to improve and send back any comments! some question at last.. [modified] PinmemberAndyHo21-May-12 9:11 
QuestionThank you thank you thank you!!!! PinmemberMember 826925822-Nov-11 16:46 
AnswerRe: Thank you thank you thank you!!!! PinmemberColinBashBash23-Nov-11 4:48 
GeneralJust what i need! Pinmember_dr1v3r_27-Oct-10 1:59 
GeneralRe: Just what i need! PinmemberColinBashBash27-Oct-10 4:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.1411028.1 | Last Updated 18 Oct 2010
Article Copyright 2010 by ColinBashBash
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid