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

Live Chat - Template Code

By , 18 Oct 2010
 

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)

About the Author

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

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 4membershani_75930 Dec '12 - 20:04 
Questionfile damagedmemberAteşG3 Aug '12 - 4:07 
it seems like the file is damaged, is there any way you can check what is going on with the file?
AnswerRe: file damagedmemberColinBashBash3 Aug '12 - 4:12 
GeneralRe: file damagedmemberAteşG3 Aug '12 - 4:27 
GeneralRe: file damagedmemberAteşG3 Aug '12 - 5:11 
QuestionGood stuff!! will try to improve and send back any comments! some question at last..memberAndyHo21 May '12 - 4:19 
AnswerRe: Good stuff!! will try to improve and send back any comments! some question at last..memberColinBashBash21 May '12 - 4:31 
GeneralRe: Good stuff!! will try to improve and send back any comments! some question at last.. [modified]memberAndyHo21 May '12 - 8:11 
QuestionThank you thank you thank you!!!!memberMember 826925822 Nov '11 - 15:46 
AnswerRe: Thank you thank you thank you!!!!memberColinBashBash23 Nov '11 - 3:48 
GeneralJust what i need!member_dr1v3r_27 Oct '10 - 0:59 
GeneralRe: Just what i need!memberColinBashBash27 Oct '10 - 3:23 

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

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 18 Oct 2010
Article Copyright 2010 by ColinBashBash
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid