Tuesday, April 28, 2009

Ajax jQuery Chat Demo

** Update **

Here is a simpler version with source code designed for Webmatrix/Razor/MVC3
[HERE]


I wanted to do a quick demo for a chat client similar to the one I see on gTalk and Facebook. Note in this demo I am polling, I use javascript to poll a server page for any new chat comments. This technique will work ok for small to mid sized trafficed web sites. For heavy trafficed sites, you probably need to do some sort of subscript/event model, maybe using a comet server (google). That technique is beyond me at this point, but here is a demo of the more basic polling technique that you can expand on.

The concept is pretty simple. You need three things.

1) The chat page (HTML and jQuery...or in my case an aspx and jQuery page).
2) A push page with which will accept your chat form post and save them to a database (for this example I'm using SQL Server 2008.
3) a pull page that will send new chat messages to the chat pages as they become available (actually not really sending, the chat script will continuously poll the page about every 2 seconds looking for new data to read).

Ok, our chat page will look like this- (remember to include a reference to your jQuery script somewhere, not shown).

<form id="form1" runat="server">
  <div>
    <div style="width: 200px; height: 400px; border: solid 1px blue; overflow: auto"
      id="Chat_window">
    </div>
    <br />
    ID:
<input type="text" style="width: 80px" id="ChatID" maxlength="10" /><br />
    <input type="text" id="ChatMsg" style="width: 200px" maxlength="200" />
    <a href="javascript:postit()">Post</a>
    <script type="text/javascript">
      function postit() {
clearInterval(ptime);
var zpost = { "ChatID": $("#ChatID").val(), "ChatMsg": $("#ChatMsg").val() };
$("#Chat_window").prepend("<span>" + zpost.ChatID + ": " + zpost.ChatMsg + "<br /></span>");
$.post("push.aspx"
       , zpost
, function(data) {
pullit();
ptime = setInterval(pullit, 1500);
});
}
function pullit() {
var url = "pull.aspx?t=" + eval(Math.floor(Math.random() * 90000));
$.post(url, function(data) {
if (data == "") return;
$("#Chat_window").prepend(data);
while ($("#Chat_window").children().size() > 29) {
$("#Chat_window").find("span:last-child").remove();
}
});
}
var ptime = setInterval(pullit, 1500);
</script>
  </div>
  </form>



Ok, I know setting the ptime inline is bad form, but heh, it is just a demo. Some highlights. You have a postit and pullit method. The postit sends the ChatID and ChatMsg to the server as a form request. I'm adding some random query string var to the end of the pull.aspx page call to help prevent caching, this worked for me but you might have to tweak things a little bit more in your environment. The pullit method polls the the pull page about every 1.5 seconds for changes.

Now for the push it page. I'm using Asp.net, but you can accomplish the same thing in PHP or whatever.

 public partial class push : System.Web.UI.Page
  {
protected void Page_Load(object sender, EventArgs e)
{
SaveChatPost();
}
void SaveChatPost()
{
using (SqlConnection oConn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["myconnectionstringname"].ToString()))
{
using (SqlCommand oCmd = new SqlCommand())
{
oCmd.CommandType = CommandType.Text;
oCmd.CommandText = "declare @ts as datetime;set @ts = current_timestamp;Insert into HonoviMarketing.dbo.tChat (ChatTime, ChatId, ChatMsg) values (@ts,@p_ChatID, @p_ChatMsg);Select @ts as CurrentChatTime";
oCmd.Parameters.Add(new SqlParameter("@p_ChatID", Server.UrlDecode(Request.Form["ChatID"])));
oCmd.Parameters.Add(new SqlParameter("@p_ChatMsg", Server.UrlDecode(Request.Form["ChatMsg"])));
oConn.Open();
oCmd.Connection = oConn;
using (SqlDataReader dr = oCmd.ExecuteReader())
{
if (dr != null && dr.HasRows)
{
dr.Read();
Session["CurrentChatTime"] = dr["CurrentChatTime"].ToString();
Session["ChatID"] = Request.Form["ChatID"];
}
}
oConn.Close();
}
}
}
}


No biggie here (and if the code runs off the page, just highlight and copy it, you'll get it all, stupid blogger :)). I save the post to the database, get a current_timestamp, and set that as well as the chosen ChatID into session variables that help with pulling the right data on the pull.aspx page, which is next. Note on both pages I put this logic in the code behind of the aspx page, and removed all the HTML from the front page except for the top asp.net directives line. And again, I'm just doing a simple example here, not worried to much about query security and the like, so don't get anal.

 public partial class server : System.Web.UI.Page
  {
protected void Page_Load(object sender, EventArgs e)
{
PullData();
}
string XMLSafe(string s)
{
return s.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;");
}
void PullData()
{
using (SqlConnection oConn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["myconnectionstringname"].ToString()))
{
using (SqlCommand oCmd = new SqlCommand())
{
oCmd.CommandType = CommandType.Text;
oCmd.Connection = oConn;
oConn.Open();
if (Session["CurrentChatTime"] == null)
{
oCmd.CommandText = "Select Current_Timestamp as CurrentChatTime";
using (SqlDataReader dr = oCmd.ExecuteReader())
{
if (dr != null && dr.HasRows)
{
dr.Read();
Session["CurrentChatTime"] = dr["CurrentChatTime"].ToString();
}
}
}
else
          {
string sDate = Session["CurrentChatTime"].ToString();
SqlParameter p = new SqlParameter();
p.Direction = ParameterDirection.Input;
p.Value = sDate;
p.SqlDbType = SqlDbType.DateTime;
p.ParameterName = "@p_CurrentTime";
oCmd.Parameters.Add(p);
oCmd.CommandText = "select chatTime, ChatID, ChatMsg from HonoviMarketing.dbo.tChat where ChatTime > @p_CurrentTime and ChatID <> '" + Session["ChatID"] + "' order by ChatTime; SELECT CONVERT(varchar, current_timestamp, 21) as CurrentChatTime";
using (SqlDataReader dr = oCmd.ExecuteReader())
{
if (dr.HasRows)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
while (dr.Read())
{
sb.Append("<span>" + XMLSafe(dr["ChatID"].ToString()) + ": " + XMLSafe(dr["ChatMsg"].ToString()) + "<br /></span>");
}
Response.Write(sb.ToString());
dr.NextResult();
if (dr.HasRows)
{
dr.Read();
Session["CurrentChatTime"] = dr["CurrentChatTime"].ToString();
}
}
}
}
oConn.Close();
}
}
}
}



Again of note is that I'm using session vars to help pull just the latest message that is needed. One gotcha that I encountered with SQL server to be aware of is that you need to format the current_timestamp else you loose the milliseconds, which was causing the chat page to sometime receive double messages. You need to format in your query like so - SELECT CONVERT(varchar, current_timestamp, 21) as CurrentChatTime for setting an accurate time for a session var.

Also remember to put a reference on both pages to the System.Data.SqlClient if you are copying my code. Here is a pic of the table layout I used.




Happy coding!

[Update]

I noticed I didn't do the SELECT CONVERT(varchar, current_timestamp, 21) as CurrentChatTime formating on the if session["CurrentTimeChat"] == null clause for the first time the pull page is hit, you can add that if you want, though things seem to work without it. Also the XMLSafe method isn't really necessary nor fully implimented, so you can ditch that method if you want or fully build it out if you are concerned about illegal HTML and XML chars. I'd fix this all in code but reposting in blogger is a pain when dealing with code, so I'll leave it as is, which works fine.

Tuesday, April 21, 2009

Google Makes Another Raid into Web 3.0

Ok, I track what is going on in the web world, though I need to spend much less time tracking and more time doing, I did find something very interesting.

We have a battle for next generation web apps that currently is between Silverlight and Flex/Flash, with Unity 3D and some other plugins on the fringes.

But now Google enters the fray…

Google's new Open GL Web API

Source: Ajaxian.com

Tuesday, April 14, 2009

Javascript Gotcha: substr <> substring

I love Javascript, but I don't client side code as much as I used too, so coming from recent use in C#, I tried to do a substring on a string and pulled my hair out for about 15 minutes wondering why the results I was getting back wasn't at all as expected. Well, then I remembered substr, which operates in javascript like c#'s substring. Grrrr...

For more-

substr vs substring

Sunday, April 12, 2009

Free C# E-Book

Download your free C# 2008 Illustrated e-book from A-Press!

Free E-Book

Source: DotNetShoutOut.com

Friday, April 03, 2009

Sunday, March 29, 2009

Pushbutton Flash Game Maker

This looks promising, a Flash game engine that supports isometric views, tile maps, and more.

Check it out here-

http://pushbuttonengine.com/

Update: Looks like IE doesn't like blogger, as the past in link doesn't work anymore. Oh well. Also, the pushbuttonengine is by the same guys who made torque.

Thursday, March 26, 2009

Distributed Open Source SVN: Git

Web Designer Depot has a nice into to a version control system called GIT that looks like it might be worth checking out.


http://www.webdesignerdepot.com/2009/03/intro-to-git-for-web-designers/

Wednesday, March 25, 2009

Unity 3D AI Package

Check out this Unity 3D AI Pack

http://drawlogic.com/2009/03/24/unity3d-path-and-behave-projects-from-angryant-waypoints-ai-paths-library-behavioral-trees-and-more/

Torque to Offer Unity3D Alternative

Torque looks to offer a web plugin with similar capacities as Unity 3D. The browser wars are heating up. Web 3.0, the game web, or the 3D web, is on the Horizon.


http://drawlogic.com/2009/03/24/torque3d-to-offer-web-based-export-similar-to-unity3d-improved-pipeline/

Future: Javascript 3D Capabilities On the Horizon

Looks like the Mozilla foundation is looking to bring Open GL capabilities to Javascript.

http://dusanwriter.com/index.php/2009/03/25/3d-in-a-browser-mozilla-and-open-gl-to-build-plug-in-free-virtual-world-access/

About time! Why mess with all these 3rd party plugins (Flash/Unity/Silverlight) when we can do things directly from the web browser? Especially when 3D will become more and more common.

VRML is dead...but its successor could finally be on the horizon.

Monday, March 23, 2009

Disappointment with Silverlight 3 Beta's 3D

OK, it is just a Beta, but I was hoping for a full on programmable 3D engine in Silverlight 3. I might have been naive, but I had high hopes. We do now have Unity 3D, but for business aps Unity 3D lacks many features, as it is targeted solely for Game Development. I was hoping I could have one app to do it all. There are some nice 3D features in Silverlight, don't get me wrong, but nothing that can't be duplicated with Flash/Flex/Papervision etc...

I guess I will have to wait...but beggers can't be choosers.

Friday, March 20, 2009

IE 8, Didn't Break As Many Things As I Worried About

Yes, IE8 is out. I've downloaded it at home and at work (at home it took two tries). So far I've only noticed some minor text overlay issues (a line being a few pixels up or down). Other than that most of the sites (including our work site...I was worried about that) appear to operate normally.

www.microsoft.com/ie

Thursday, March 19, 2009

Great SQL Server Maintenance Article

I know a lot of people are using SQL Server 2005/2008 Express for production (though they shouldn't). I also know folks are using the cheaper SQL Server 2008 Web version for web databases. Both of these databases lack some maintenance and backup features that their more expensive cousins have. If you find yourself needing those features but unable to afford them, this article might help.

http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ExpressMaintenance&referringTitle=Home

Wednesday, March 18, 2009

Kick @ss, Unity 3D for Windows Released!

Finally, the true progeny of Director, Unity 3D, is available for Windows! I can't wait to get my hands on a copy. Download the 30 day trial here-

http://unity3d.com/unity/download

Thanks Developmag.com for breaking the story-

http://www.developmag.com/news/31482/Unity-now-avaiable-for-Windows

Also announced today is the release of Silverlight 3 Beta...yawn.

Wednesday, February 18, 2009

Like to Chat? Check out Meebo

I stumbled across www.meebo.com today, and I like it. Web based "omni" chat client, to use my own words. Use MSN, Yahoo, Facebook, and more. Pretty cool.

Tuesday, February 17, 2009

Ahhh Vanity

Basically, as a writer and a blogger, I suck pretty hard. Broken English, misspelled words, incomplete sentences and thoughts, yadda yadda. This occures partially because I really do suck at times, but more often then not it is laziness on my part to not cross every t or dot every i.

But blogging is fun, and feeds a little personal vanity I suppose. I don't bring much to the table, but every once in a while someone will thank me for posting some code or quote a comment I left on a blog.

Here is one case...

http://dusanwriter.com/index.php/2009/02/17/identities-constructed-virtual-worlds-and-anonymity/

This post is about virtual identities, something I'm very interested in. And the author, Dusan, talked briefly about a comment I made about Oscar Wilde, though I can't seem to find the original comment on the other blog post. So, in a small way, I added to the discussion of things, and got people to think a little bit about a point I made, which is cool.

Does my heat good and feeds the vanity flame a little more.

Thursday, February 12, 2009

Think Science Isn't Cool? In the USSR It Is

Just so you believe me, say you were a nuclear engineer in Russia. Here are some of your comrads.

http://miss2009.nuclear.ru/participants.html

I doubt most engineering or scientific firms in the US could mount any sort of challenge to the miss atom contest in the CIS.

What does this tell us, besides the fact that I was checking out some Russian scientific hotties? That there is a big cultural difference between Russia and the US. In Russia, science is cool enough to attract some babe talent. In America, not so much (though there are exceptions to every rule...if you are female, in science, and reading this, you are the exception...of course:). This is a problem.

Source: Wired Defense Blog

Monday, February 09, 2009

Three PHP Frameworks Worth Checking Out

I think php is kind of in a crisis right now (and I'm sort of talking through my rear, as I'm working on my first PHP project now). It seems like PHP is really simple. But a lot of folks talked down to PHP because it wasn't "object oriented" enough. So now PHP is trying to become what maybe it shouldn't be, a first class object oriented language. Or let me put it this way, hopefully it won't become a first class object oriented language at the expense of loosing its easy to use/easy to understand roots.

Anyway, I digress...

For those of you who just can't stand the fact that you don't have all the OOP and other "modern" features of other languages in PHP, check out the following PHP frameworks that extend PHP to support things like MVC, better OOP, and Active Record, to name a few. Here they are.

CakePHP http://cakephp.org/
The Zend Framework http://framework.zend.com/
Code Igniter http://codeigniter.com/

If you have any opinions on which is better, I'd be interested. I will take one out for a spin on my second or third project.