Click here to Skip to main content
15,887,240 members
Articles / Programming Languages / Javascript

Live Chat - Template Code

Rate me:
Please Sign up or sign in to vote.
4.83/5 (11 votes)
18 Oct 2010CPOL1 min read 75.2K   5.8K   56   14
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.

HTML
<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:

C#
 [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:

JavaScript
//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) + '}'
}); 
JavaScript
//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
});
JavaScript
//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)


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

Comments and Discussions

 
Questionnewbee Pin
Member 1373397819-Mar-18 0:08
Member 1373397819-Mar-18 0:08 
Questionsolution file Pin
Member 1295979020-Jan-17 6:49
Member 1295979020-Jan-17 6:49 
GeneralMy vote of 4 Pin
shani_75930-Dec-12 20:04
shani_75930-Dec-12 20:04 
Questionfile damaged Pin
AteşG3-Aug-12 4:07
AteşG3-Aug-12 4:07 
AnswerRe: file damaged Pin
ColinBashBash3-Aug-12 4:12
ColinBashBash3-Aug-12 4:12 
GeneralRe: file damaged Pin
AteşG3-Aug-12 4:27
AteşG3-Aug-12 4:27 
GeneralRe: file damaged Pin
AteşG3-Aug-12 5:11
AteşG3-Aug-12 5:11 
QuestionGood stuff!! will try to improve and send back any comments! some question at last.. Pin
AndyHo21-May-12 4:19
professionalAndyHo21-May-12 4:19 
AnswerRe: Good stuff!! will try to improve and send back any comments! some question at last.. Pin
ColinBashBash21-May-12 4:31
ColinBashBash21-May-12 4:31 
GeneralRe: Good stuff!! will try to improve and send back any comments! some question at last.. Pin
AndyHo21-May-12 8:11
professionalAndyHo21-May-12 8:11 
QuestionThank you thank you thank you!!!! Pin
davecenter200222-Nov-11 15:46
davecenter200222-Nov-11 15:46 
AnswerRe: Thank you thank you thank you!!!! Pin
ColinBashBash23-Nov-11 3:48
ColinBashBash23-Nov-11 3:48 
Your welcome. As you go along, let me know if you have any additional notes that would be helpful to include in the article.
GeneralJust what i need! Pin
godidier27-Oct-10 0:59
godidier27-Oct-10 0:59 
GeneralRe: Just what i need! Pin
ColinBashBash27-Oct-10 3:23
ColinBashBash27-Oct-10 3:23 

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

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