<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Dot Net Thoughts &#187; Javascript</title>
	<atom:link href="http://www.dotnetthoughts.net/tag/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.dotnetthoughts.net</link>
	<description>thoughts about .Net, WPF, Sharepoint, Javascript and more.</description>
	<lastBuildDate>Wed, 28 Jul 2010 09:59:26 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Pass your own arguments to the ClientValidationFunction in a CustomValidator</title>
		<link>http://www.dotnetthoughts.net/2010/05/30/pass-your-own-arguments-to-the-clientvalidationfunction-in-a-customvalidator/</link>
		<comments>http://www.dotnetthoughts.net/2010/05/30/pass-your-own-arguments-to-the-clientvalidationfunction-in-a-customvalidator/#comments</comments>
		<pubDate>Sun, 30 May 2010 09:41:04 +0000</pubDate>
		<dc:creator>Anuraj P</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[.Net 3.0 / 3.5]]></category>
		<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[C#.Net]]></category>

		<guid isPermaLink="false">http://www.dotnetthoughts.net/?p=896</guid>
		<description><![CDATA[Last few days I am working on an ASP.Net, where I can create Grids, Dropdown lists with Post back , and the best part is browser compatibility, client only requires compatible with IE. Yes it was a refresher course for me, I revisited GridView templates, Page.IsPostback checking etc. Today I got a requirement like I [...]]]></description>
			<content:encoded><![CDATA[<p>Last few days I am working on an ASP.Net, where I can create Grids, Dropdown lists with Post back <img src='http://www.dotnetthoughts.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> , and the best part is browser compatibility, client only requires compatible with IE. Yes it was a refresher course for me, I revisited GridView templates, Page.IsPostback checking etc. Today I got a requirement like I need to validate few radio buttons. I searched for an implementation, I found we can use required field validator for RadioButtonList, but in my case it was Radio buttons (Initially it was RadioButtonList, but due to some customization issues, I changed it to Radio Buttons). Then I implemented a custom validator, and in the client validation function I hardcoded the Radio Button ids, because for the client validation function we can&#8217;t pass the parameters to the function. Same problem again I faced in a GridView, where the problem I found was I won&#8217;t get the client id of the radio button in the Item template. <img src='http://www.dotnetthoughts.net/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' />  After doing some research I found we can extend the custom validator control using Validation Framework. And here is the implementation. Using this we can add properties to the source / sender parameter in the client side validation function.</p>
<pre class="brush: jscript;">
function ValidateRadioButtons(source, arguments) {
    var radio1 = document.getElementById(source.Radio1);
    var radio2 = document.getElementById(source.Radio2);
    var radio4 = document.getElementById(source.Radio4);
    var radio3 = document.getElementById(source.Radio3);
    var result = radio1.checked || radio2.checked || radio3.checked || radio4.checked;
    arguments.IsValid = result;
}
</pre>
<p>This is the JavaScript function which implements the validation logic. You can get the controls as part of the Source object. To get the Source.Radio1, you need to register the Radio1 as ClientValidator attribute. You can do some C# code like this.</p>
<pre class="brush: csharp;">
protected void Page_Load(object sender, EventArgs e)
{
    this.Page.ClientScript.RegisterExpandoAttribute(customCheck.ClientID, &quot;Radio1&quot;, this.radio1.ClientID, false);
    this.Page.ClientScript.RegisterExpandoAttribute(customCheck.ClientID, &quot;Radio2&quot;, this.radio2.ClientID, false);
    this.Page.ClientScript.RegisterExpandoAttribute(customCheck.ClientID, &quot;Radio3&quot;, this.radio3.ClientID, false);
    this.Page.ClientScript.RegisterExpandoAttribute(customCheck.ClientID, &quot;Radio4&quot;, this.radio4.ClientID, false);
}
</pre>
<p>And the ASPX Code is like this</p>
<pre class="brush: xml;">
&lt;asp:CustomValidator runat=&quot;server&quot; ID=&quot;customCheck&quot; ClientValidationFunction=&quot;ValidateRadioButtons&quot;
        ErrorMessage=&quot;Choose any option&quot; /&gt;
</pre>
<p>And here is the Output code generated for the custom validator.</p>
<div id="attachment_899" class="wp-caption aligncenter" style="width: 304px"><a href="http://www.dotnetthoughts.net/wp-content/uploads/2010/05/custom_validator_rendering.png"><img src="http://www.dotnetthoughts.net/wp-content/uploads/2010/05/custom_validator_rendering.png" alt="Custom validator output rendering" title="Custom validator output rendering" width="294" height="68" class="size-full wp-image-899" /></a><p class="wp-caption-text">Custom validator output rendering</p></div>
<p>Happy Coding.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2010/05/30/pass-your-own-arguments-to-the-clientvalidationfunction-in-a-customvalidator/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>System.InvalidOperationException &#8211; The length of the string exceeds the value set on the maxJsonLength property.</title>
		<link>http://www.dotnetthoughts.net/2010/04/16/system-invalidoperationexception-the-length-of-the-string-exceeds-the-value-set-on-the-maxjsonlength-property/</link>
		<comments>http://www.dotnetthoughts.net/2010/04/16/system-invalidoperationexception-the-length-of-the-string-exceeds-the-value-set-on-the-maxjsonlength-property/#comments</comments>
		<pubDate>Fri, 16 Apr 2010 15:00:51 +0000</pubDate>
		<dc:creator>Anuraj P</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[.Net 3.0 / 3.5]]></category>
		<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Ajax]]></category>
		<category><![CDATA[JSON]]></category>

		<guid isPermaLink="false">http://www.dotnetthoughts.net/?p=854</guid>
		<description><![CDATA[Yesterday I got a problem from one of my friend; he is getting a Javascript exception from some Ajax Page methods. The exception occurred when he tried to return a very long string from web method. The exception was like this. Error: Sys.Net.WebServiceFailedException: The server method &#8216;WebServiceMethod&#8217; failed with the following error: System.InvalidOperationException&#8211; Error during [...]]]></description>
			<content:encoded><![CDATA[<p>Yesterday I got a problem from one of my friend; he is getting a Javascript exception from some Ajax Page methods. The exception occurred when he tried to return a very long string from web method. The exception was like this.</p>
<p>Error: Sys.Net.WebServiceFailedException: The server method &#8216;WebServiceMethod&#8217; failed with the following error: System.InvalidOperationException&#8211; Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.</p>
<p>After doing some searching we resolved it. You can resolve this error by modifying the web.config file, and add / modify the Configuring JSON Serialization.</p>
<pre class="brush: xml;">
&lt;configuration&gt;
  &lt;system.web.extensions&gt;
    &lt;scripting&gt;
      &lt;webServices&gt;
        &lt;jsonSerialization maxJsonLength=&quot;5000&quot;/&gt;
      &lt;/webServices&gt;
    &lt;/scripting&gt;
  &lt;/system.web.extensions&gt;
&lt;/configuration&gt;
</pre>
<p>The default length is 102400.<br />
You can get more information about this from MSDN : http://msdn.microsoft.com/en-us/library/bb763183.aspx</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2010/04/16/system-invalidoperationexception-the-length-of-the-string-exceeds-the-value-set-on-the-maxjsonlength-property/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Developing simple Windows 7 Gadget &#8211; Part 3</title>
		<link>http://www.dotnetthoughts.net/2010/03/09/developing-simple-windows-7-gadget-part-3/</link>
		<comments>http://www.dotnetthoughts.net/2010/03/09/developing-simple-windows-7-gadget-part-3/#comments</comments>
		<pubDate>Tue, 09 Mar 2010 18:50:11 +0000</pubDate>
		<dc:creator>Anuraj P</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Miscellaneous]]></category>
		<category><![CDATA[Windows 7]]></category>
		<category><![CDATA[Windows Vista]]></category>

		<guid isPermaLink="false">http://www.dotnetthoughts.net/?p=795</guid>
		<description><![CDATA[In this I am exploring another two features of Gadget API, one is Docking and other is Flyout. The Docking feature is helpful in Windows Vista, because the gadget lives only in Vista Sidebar, but in Windows 7 it can be anywhere in the desktop. The Docking feature helps to change the size of Gadget, [...]]]></description>
			<content:encoded><![CDATA[<p>In this I am exploring another two features of Gadget API, one is Docking and other is Flyout. The Docking feature is helpful in Windows Vista, because the gadget lives only in Vista Sidebar, but in Windows 7 it can be anywhere in the desktop. The Docking feature helps to change the size of Gadget, in Windows Vista, the docking / un-docking events will automatically fired, when we drag the gadget out of the sidebar, but in Windows 7 another button will displayed in the Gadget toolbox. You can query the current state of a gadget with System.Gadget.docked. It returns true if docked, false if undocked.</p>
<div id="attachment_798" class="wp-caption alignnone" style="width: 170px"><a href="http://www.dotnetthoughts.net/wp-content/uploads/2010/03/image.png"><img class="size-full wp-image-798" title="Docking / UnDocking button in Sidebar" src="http://www.dotnetthoughts.net/wp-content/uploads/2010/03/image.png" alt="Docking / UnDocking button in Sidebar" width="160" height="273" /></a><p class="wp-caption-text">Docking / UnDocking button in Sidebar</p></div>
<p>There are also two events that you can monitor, System.Gadget.onDock and System.Gadget.onUndock, to determine when the docking state changes.</p>
<p>You can change the Width of the gadget by calling <em>document.body.style.width = &#8220;130px&#8221;;</em>. And the Docking and Undocking events should be attached on the Page_load.</p>
<pre class="brush: jscript;">
System.Gadget.onDock = dockStateChanged;
System.Gadget.onUndock = dockStateChanged;
</pre>
<p>And the dockStateChanged function is</p>
<pre class="brush: jscript;">
function dockStateChanged() {
//Checks the current state of the Gadget, if Docked state, setting the width to 130px;
//Otherwise changing to 330px;
	if (System.Gadget.docked) {
		document.body.style.width = &quot;130px&quot;;
document.getElementById(&quot;RSSOutput&quot;).style.width = &quot;125px&quot;;
	} else {
		document.body.style.width = &quot;330px&quot;;
document.getElementById(&quot;RSSOutput&quot;).style.width = &quot;325px&quot;;
	}
}
</pre>
<p>Another feature is Flyout. Flyouts used to extend the Gadget UI. The flyouts are system modal—only one can be displayed at a time. And when a gadget loses focus, its flyout will close. API for Flyouts available under System.Gadget.Flyout. As the flyouts is completely a separate window, with its own DOM, helps to add / create controls dynamically in it. Also you need to specify the flyout file, like Settings file.</p>
<p>The System.Gadget.Flyout.document returns the Document object of the flyout window. To display a flyout you need to set Flyout.show to True and to hide, set it to false. This property also returns the current state of flyout. But we cannot control the location of side bar, it is managed by Sidebar or OS.</p>
<pre class="brush: jscript;">
System.Gadget.Flyout.file = &quot;flyout.html&quot;;
</pre>
<p>There are certain events also available for Flyouts</p>
<pre class="brush: jscript;">
System.Gadget.Flyout.onShow = function()
{
//Do something, when flyout is opening, may be a dynamic control creation
}
System.Gadget.Flyout.onHide = function()
{
//Do some code.
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2010/03/09/developing-simple-windows-7-gadget-part-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Developing simple Windows 7 Gadget &#8211; Part 2</title>
		<link>http://www.dotnetthoughts.net/2010/02/24/developing-simple-windows-7-gadget-part-2/</link>
		<comments>http://www.dotnetthoughts.net/2010/02/24/developing-simple-windows-7-gadget-part-2/#comments</comments>
		<pubDate>Wed, 24 Feb 2010 18:05:39 +0000</pubDate>
		<dc:creator>Anuraj P</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Miscellaneous]]></category>
		<category><![CDATA[Windows 7]]></category>
		<category><![CDATA[Gadget]]></category>
		<category><![CDATA[Gadget API]]></category>
		<category><![CDATA[Sidebar Gadget]]></category>
		<category><![CDATA[Windows Vista]]></category>

		<guid isPermaLink="false">http://www.dotnetthoughts.net/?p=787</guid>
		<description><![CDATA[In my last post I have created a simple Windows 7 Gadget for testing Regular expressions. In this post we look into the Gadget Options dialog and Gadget API, which helps to display the options dialog and save the preferences from the User. The options dialog is a nice feature used in Gadgets to manage [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://www.dotnetthoughts.net/2010/02/24/developing-simple-windows-7-gadget-part-1/">last post </a>I have created a simple Windows 7 Gadget for testing Regular expressions. In this post we look into the Gadget Options dialog and Gadget API, which helps to display the options dialog and save the preferences from the User. The options dialog is a nice feature used in Gadgets to manage the user preferences. It is also an HTML file. Unlike the main Gadget HTML file, which is specified in the XML Definition file, the Options HTML File is specified in the main gadget file or in the main Javascript file, generally in the gadget initialization area of your script. In the RegEx Tester example, I am using the RegEx function flags as customization options.</p>
<div id="attachment_790" class="wp-caption alignnone" style="width: 240px"><a href="http://www.dotnetthoughts.net/wp-content/uploads/2010/02/settings_clicked.png"><img class="size-full wp-image-790" title="RegEx Tester Settings " src="http://www.dotnetthoughts.net/wp-content/uploads/2010/02/settings_clicked.png" alt="RegEx Tester Settings " width="230" height="327" /></a><p class="wp-caption-text">RegEx Tester Settings</p></div>
<p>So I have created an HTML File with 3 checkboxes and wrote a javascript function to get the user selected options, create the flags variable, and when closing the Options dialog, save the user preferences. To create the settings or options dialog, set the SettingsUI property.  </p>
<pre class="brush: jscript;">
System.Gadget.settingsUI = &quot;settings.html&quot;;
</pre>
<p>After setting the SettingsUI property, the Gadget will display a Options button in the Gadget handle.</p>
<div id="attachment_789" class="wp-caption alignnone" style="width: 240px"><a href="http://www.dotnetthoughts.net/wp-content/uploads/2010/02/RegExTester_Settings.png"><img src="http://www.dotnetthoughts.net/wp-content/uploads/2010/02/RegExTester_Settings.png" alt="Settings Button" title="Settings Button " width="230" height="280" class="size-full wp-image-789" /></a><p class="wp-caption-text">Settings Button </p></div>
<p>The Gadget API also supports various events / callback functions for the Options dialog, like SettingsClosing, SettingsClosed etc, which helps to save the Preferences and Read the preferences in the Gadget.</p>
<pre class="brush: jscript;">
System.Gadget.onSettingsClosed = settingsClosed;
function settingsClosed(event) {
	//OK Button clicked.
if (event.closeAction == event.Action.commit) {
	//Load settings here.
}
}
</pre>
<p>Gadget API supports various methods to read and write settings. For writing setting we can use System.Gadget.Settings.write or System.Gadget.Settings.writeString. Both the functions will expects a key/value pair. And for reading can use System.Gadget.Settings.read or System.Gadget.Settings.readString, both of these functions take a key and return a value. If the key does not exist (for instance if it has never been written) both will return a value of undefined. Use System.Gadget.Settings.xxxxString method, if you are working with string values. All the settings are stored in Settings.ini file. And it is available in the &#8220;C:\Users\\AppData\Local\Microsoft\Windows Sidebar&#8221; location.<br />
Saving the preferences</p>
<pre class="brush: jscript;">
System.Gadget.Settings.write(&quot;RegExOptionsSaved&quot;, &quot;true&quot;);
System.Gadget.Settings.write(&quot;RegExOption&quot;, escape(result));
</pre>
<p>And reading the Preferences </p>
<pre class="brush: jscript;">
if (System.Gadget.Settings.read(&quot;RegExOptionsSaved&quot;)) {
regExOptions = unescape(System.Gadget.Settings.read(&quot;RegExOption&quot;));
}
</pre>
<p><strong>RegEx Object constructor</strong> </p>
<pre class="brush: jscript;">
var re = new RegEx(&quot;Pattern&quot;,&quot;Flags&quot;);
</pre>
<p>And the Flags are</p>
<ol>
<li>
Global Search &#8211; g &#8211; The global search flag makes the RegExp search for a pattern throughout the string, creating an array of all occurrences it can find matching the given pattern.</li>
<li>Ignore Case &#8211; i &#8211; The ignore case flag makes a regular expression case insensitive. For international coders, note that this might not work on extended characters such as å, ü, ñ, æ.</li>
<li>Multiline Input &#8211; m &#8211; This flag makes the beginning of input (^) and end of input ($) codes also catch beginning and end of line respectively.</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2010/02/24/developing-simple-windows-7-gadget-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Image cropping in ASP.Net with JQuery</title>
		<link>http://www.dotnetthoughts.net/2009/12/07/image-cropping-in-asp-net-with-jquery/</link>
		<comments>http://www.dotnetthoughts.net/2009/12/07/image-cropping-in-asp-net-with-jquery/#comments</comments>
		<pubDate>Tue, 08 Dec 2009 05:29:02 +0000</pubDate>
		<dc:creator>Anuraj P</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[.Net 3.0 / 3.5]]></category>
		<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[JQuery]]></category>

		<guid isPermaLink="false">http://www.dotnetthoughts.net/?p=655</guid>
		<description><![CDATA[Yesterday I got a chance to explore Jcrop &#8211; the jQuery Image Cropping Plugin. You can get more details about JCrop from here. It is nice JQuery plugin to Crop photos. Here is a simple implementation of JCrop with ASP.Net and C#, which will upload a File to webserver, allows the user to crop and [...]]]></description>
			<content:encoded><![CDATA[<p>Yesterday I got a chance to explore Jcrop &#8211; the jQuery Image Cropping Plugin. You can get more details about JCrop from <a href="http://deepliquid.com/content/Jcrop.html" target="_blank" >here</a>. It is nice JQuery plugin to Crop photos. Here is a simple implementation of JCrop with ASP.Net and C#, which will upload a File to webserver, allows the user to crop and save it back to the server. <em>This is POC code. Make sure you validate all the inputs from end users.</em></p>
<p>Implementation</p>
<p>For the implementation first download the JQuery plugin from the  <a href="http://deepliquid.com/content/Jcrop_Download.html" target="_blank">deepliquid download page</a>. Extact it. Open the JS folder, and add reference of the scripts (jquery.Jcrop.min.js and jquery.min.js) files to the web application. Also Open the CSS folder and link the style sheet (jquery.Jcrop.css) to the ASPX Page. I am using Hidden fields to get the width, height, X, and Y values from the JCrop. </p>
<pre class="brush: jscript;">
function crop() {
    jQuery(function() {
        jQuery('#&lt;%= PicCropImage.ClientID %&gt;').Jcrop({
            onSelect: updateValues, //this function will be invoked when the user completes his selection
            aspectRatio: 1  //Setting aspectRatio: 1 will allow user to draw rectangle with aspectratio.
        });
    });
    //Updating the values of the Hidden fields from the output of crop.
    function updateValues(img) {
        document.getElementById('&lt;%= positionx.ClientID %&gt;').value = img.x;
        document.getElementById('&lt;%= positiony.ClientID %&gt;').value = img.y;
        document.getElementById('&lt;%= positionx1.ClientID %&gt;').value = img.x2;
        document.getElementById('&lt;%= positiony1.ClientID %&gt;').value = img.y2;
        document.getElementById('&lt;%= sizew.ClientID %&gt;').value = img.w;
        document.getElementById('&lt;%= sizeh.ClientID %&gt;').value = img.h;
    }
}
</pre>
<p>And in the server side I am taking the values from the Hidden fields and drawing a new image using the values and saving it in the File System.</p>
<pre class="brush: csharp;">

//Getting the Filename of the Image displayed.
string fileName = Server.MapPath(this.PicCropImage.ImageUrl);
using (Bitmap sourceImage = new Bitmap(fileName, true))
{
    Rectangle destinationArea = new Rectangle(0, 0,
        int.Parse(this.sizew.Value), int.Parse(this.sizeh.Value));
    Rectangle sourceArea =
        new Rectangle(int.Parse(this.positionx.Value), int.Parse(this.positiony.Value),
        int.Parse(this.sizew.Value), int.Parse(this.sizeh.Value));
    using (Bitmap newBitmapImage = new Bitmap(destinationArea.Right, destinationArea.Bottom))
    {
        using (Graphics graphicsImage = Graphics.FromImage(newBitmapImage))
        {
            //Setting the Graphics properties
            graphicsImage.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphicsImage.CompositingQuality = CompositingQuality.HighQuality;
            graphicsImage.SmoothingMode = SmoothingMode.HighQuality;
            graphicsImage.DrawImage(sourceImage, destinationArea, sourceArea, GraphicsUnit.Pixel);
            IntPtr hbitMap = newBitmapImage.GetHbitmap();
            using (Image image = Image.FromHbitmap(hbitMap))
            {
                //Saving the Image to file system.
                image.Save(Path.Combine(Path.GetDirectoryName(fileName),
                    string.Concat(&quot;Cropped_&quot;, Path.GetFileName(fileName))), ImageFormat.Jpeg);
            }
        }
    }
}
</pre>
<p>Thats it. You are ready for cropping with JCrop and ASP.Net.<br />
Happy Cropping <img src='http://www.dotnetthoughts.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2009/12/07/image-cropping-in-asp-net-with-jquery/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A Simple Chat script using ASP.Net C#</title>
		<link>http://www.dotnetthoughts.net/2009/09/11/a-simple-chat-script-using-asp-net-c/</link>
		<comments>http://www.dotnetthoughts.net/2009/09/11/a-simple-chat-script-using-asp-net-c/#comments</comments>
		<pubDate>Fri, 11 Sep 2009 12:50:34 +0000</pubDate>
		<dc:creator>Anuraj P</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[.Net 3.0 / 3.5]]></category>
		<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[AJAX.Net]]></category>
		<category><![CDATA[ASP.Net Chat script]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C#.Net]]></category>
		<category><![CDATA[Chat]]></category>
		<category><![CDATA[IIS 7]]></category>
		<category><![CDATA[PageMethods]]></category>

		<guid isPermaLink="false">http://anuraj.wordpress.com/?p=373</guid>
		<description><![CDATA[Few days back one of my colleague was looking for a simple chat script in ASP.Net, but he can&#8217;t found one. Almost all of the chat scripts were in ASP and he want to do it for an internal site. So I thought about implementing one. And here is the simple script using ASP.Net&#8217;s Page [...]]]></description>
			<content:encoded><![CDATA[<p>Few days back one of my colleague was looking for a simple chat script in ASP.Net, but he can&#8217;t found one. Almost all of the chat scripts were in ASP and he want to do it for an internal site. So I thought about implementing one. And here is the simple script using ASP.Net&#8217;s Page method feature. For this I am using Windows Authentication, because it is for a intranet site, where users will be coming from one domain only.</p>
<p>Code behind &#8211; Global.asax</p>
<pre class="brush: csharp;">
private List&lt;string&gt; onlineUsers;
void Session_Start(object sender, EventArgs e)
{
	if (this.onlineUsers == null)
	{
            this.onlineUsers = new List&lt;/string&gt;&lt;string&gt;();
        }

        if (!this.onlineUsers.Contains(HttpContext.Current.User.Identity.Name))
        {
            this.onlineUsers.Add(HttpContext.Current.User.Identity.Name);
        }
        HttpContext.Current.Session[&quot;Users&quot;] = this.onlineUsers;
}

void Session_End(object sender, EventArgs e)
{
        if (this.onlineUsers != null)
        {
            this.onlineUsers.Remove(HttpContext.Current.User.Identity.Name);
        }
	HttpContext.Current.Session[&quot;Users&quot;] = this.onlineUsers;
}
</pre>
<p>Web.Config</p>
<pre class="brush: xml;">
&lt;authentication mode=&quot;Windows&quot;/&gt;
&lt;authorization&gt;
	&lt;deny users=&quot;?&quot;/&gt;
&lt;/authorization&gt;
</pre>
<p>Default.aspx.cs</p>
<pre class="brush: csharp;">
private static List&lt;/string&gt;&lt;string&gt; chatCollection;

[WebMethod(true)]
public static List&lt;/string&gt;&lt;string&gt; Add(string comment)
{
	string user = HttpContext.Current.User.Identity.Name;
        if (chatCollection == null)
        {
		chatCollection = new List&lt;/string&gt;&lt;string&gt;();
        }
        comment = comment.Replace(&quot;&lt; &quot;, &quot;[&quot;).Replace(&quot;&gt;&quot;, &quot;]&quot;);
        comment = GetSmileys(comment);
        chatCollection.Add(string.Format(&quot;&lt;tr&gt;&lt;td&gt;{0} :&lt;font color=\&quot;blue\&quot;&gt;{1}&lt;/font&gt;&lt;/td&gt;&lt;/tr&gt;&quot;, user, comment));
        return chatCollection;
}

private static string GetSmileys(string comment)
{
        if (comment.Contains(&quot;[:-)]&quot;))
        {
        	comment = comment.Replace(&quot;[:-)]&quot;, &quot;&lt;img src=\&quot;icons\\smile.gif\&quot;/&gt;&quot;);
        }
        else if (comment.Contains(&quot;[;-)]&quot;))
        {
        	comment = comment.Replace(&quot;[;-)]&quot;, &quot;&lt;img src=\&quot;icons\\wink.gif\&quot;/&gt;&quot;);
        }
        else if (comment.Contains(&quot;[:-(]&quot;))
        {
        	comment = comment.Replace(&quot;[:-(]&quot;, &quot;&lt;img src=\&quot;icons\\frown.gif\&quot;/&gt;&quot;);
        }
        else if (comment.Contains(&quot;[:-D]&quot;))
        {
        	comment = comment.Replace(&quot;[:-D]&quot;, &quot;&lt;img src=\&quot;icons\\biggrin.gif\&quot;/&gt;&quot;);
        }
        else if (comment.Contains(&quot;[:-|]&quot;))
        {
        	comment = comment.Replace(&quot;[:-|]&quot;, &quot;&lt;img src=\&quot;icons\\blankstare.gif\&quot;/&gt;&quot;);
        }
        else if (comment.Contains(&quot;[B-)]&quot;))
        {
        	comment = comment.Replace(&quot;[B-)]&quot;, &quot;&lt;img src=\&quot;icons\\cool.gif\&quot;/&gt;&quot;);
        }
        else if (comment.Contains(&quot;[}-)]&quot;))
        {
        	comment = comment.Replace(&quot;[}-)]&quot;, &quot;&lt;img src=\&quot;icons\\devilish.gif\&quot;/&gt;&quot;);
        }
        else if (comment.Contains(&quot;[:-P]&quot;))
        {
        	comment = comment.Replace(&quot;[:-P]&quot;, &quot;&lt;img src=\&quot;icons\\p.gif\&quot;/&gt;&quot;);
        }
	return comment;
}

[WebMethod(true)]
public static List&lt;/string&gt;&lt;string&gt; GetChat()
{
	if (chatCollection == null)
        {
        	chatCollection = new List&lt;/string&gt;&lt;string&gt;();
        }
        return chatCollection;
}

[WebMethod(true)]
public static List&lt;/string&gt;&lt;string&gt; GetUsers()
{
	if (HttpContext.Current.Session[&quot;Users&quot;] == null)
        {
        	HttpContext.Current.Session[&quot;Users&quot;] = new List&lt;/string&gt;&lt;string&gt;();
        }
        return HttpContext.Current.Session[&quot;Users&quot;] as List&lt;/string&gt;&lt;string&gt;;
}
</pre>
<p>And finally the HTML</p>
<p>Default.aspx</p>
<pre class="brush: xml;">

&lt; !DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;
&lt;head runat=&quot;server&quot;&gt;
    &lt;title&gt;:: TEAM CHAT ::&lt;/title&gt;

    &lt;script type=&quot;text/javascript&quot;&gt;
        function sendChat() {
            var chatText = $get(&quot;txtChatInput&quot;).value;
            if (chatText != &quot;&quot;) {
                PageMethods.Add(chatText, sendChat_Callback);
            }
            else {
                $get(&quot;txtChatInput&quot;).focus();
            }
            return false;
        }
        function sendChat_Callback(response) {
            displayChatText(response);
            $get(&quot;txtChatInput&quot;).value = &quot;&quot;;
            $get(&quot;txtChatInput&quot;).focus();
        }
        function GetChat() {
            PageMethods.GetChat(GetChat_Callback);
        }
        function GetChat_Callback(response) {
            displayChatText(response);
        }
        function displayChatText(response) {
            var result;
            result = &quot;&lt;table&gt;&quot;;
            for (var i = response.length - 1; i &gt;= 0; i--) {
                result = result + response[i];
            }
            result = result + &quot;&lt;/table&gt;&quot;;
            $get(&quot;chatOutputDiv&quot;).innerHTML = result;
        }
        function getUsers() {
            PageMethods.GetUsers(GetUsers_Callback);
        }
        function GetUsers_Callback(response) {
            $get(&quot;lstUsers&quot;).options.length = 0;
            for (var i = response.length - 1; i &gt;= 0; i--) {
                addUsers(response[i]);
            }
        }
        function addUsers(text) {
            var optn = document.createElement(&quot;OPTION&quot;);
            optn.text = text;
            optn.value = text;
            $get(&quot;lstUsers&quot;).options.add(optn);
        }
        function LoadUI() {
            getUsers();
            GetChat();
            $get(&quot;txtChatInput&quot;).focus();
        }
        function showAbout() {
            var msg = &quot;Copyright (c) 2009 Anuraj. All rights reserved.\nLicenced under GNU GPL v2.&quot;;
            msg += &quot;\n\nVersion 0.2 : Supports Smileys\n&quot;;
            msg += &quot;Smileys should be in square brackets, like below,\ncase-sensitive(Sorry I will fix it later)\n&quot;;
            msg += &quot;Supported :- [:-)], [;-)], [:-(], [:-D], [:-|], [B-)], [}-)],[:-P]\n&quot;;
            msg += &quot;\n\nHappy Chatting [:)]\n&quot;;
            alert(msg);
        }
        setInterval(&quot;LoadUI();&quot;, 5000);
    &lt;/script&gt;

    &lt;style type=&quot;text/css&quot;&gt;
        body
        {
            font-family: Calibri;
            font-size: 11pt;
        }
        input
        {
            font-family: Calibri;
            font-size: 11pt;
            color: Blue;
        }
        .txt
        {
            border: solid 1px #000;
            font-family: Calibri;
            font-size: 11pt;
            color: Black;
        }
        option
        {
            font-family: Calibri;
            font-size: 11pt;
            color: Blue;
        }
        h1
        {
            color: Blue;
            font-size: xx-large;
            text-decoration: underline;
            text-align: center;
        }
    &lt;/style&gt;
&lt;/head&gt;
&lt;body onload=&quot;javascript:LoadUI();&quot;&gt;
    &lt;form id=&quot;form1&quot; runat=&quot;server&quot; onsubmit=&quot;javascript:return sendChat();&quot;&gt;
    &lt;div&gt;
        &lt;asp :ScriptManager runat=&quot;server&quot; ID=&quot;scriptMgr&quot; EnablePageMethods=&quot;true&quot; ScriptMode=&quot;Release&quot;
            EnableViewState=&quot;false&quot; /&gt;
        &lt;table cellpadding=&quot;0&quot; cellspacing=&quot;0&quot; border=&quot;0&quot;&gt;
            &lt;tr&gt;
                &lt;td colspan=&quot;2&quot; style=&quot;text-align: center&quot;&gt;
                    &lt;h1&gt;
                        :: TEAM CHAT ::
                    &lt;/h1&gt;
                    &lt;span&gt;A simple chat script using ASP.Net and C#&lt;/span&gt;
                    &amp;nbsp;&lt;a href=&quot;javascript:void('About');&quot; title=&quot;About TeamChat&quot; onclick=&quot;javascript:return showAbout

();&quot;&gt;?&lt;/a&gt;&amp;nbsp;
                &lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
                &lt;td&gt;

                    &lt;input class=&quot;txt&quot; type=&quot;text&quot; maxlength=&quot;1500&quot; style=&quot;width: 340px;&quot; id=&quot;txtChatInput&quot; /&gt;
                &lt;/td&gt;
                &lt;td valign=&quot;middle&quot;&gt;
                    &amp;nbsp;&lt;input type=&quot;button&quot; id=&quot;cmdSubmit&quot; value=&quot;Send&quot; onclick=&quot;javascript:return sendChat();&quot; /&gt;
                &lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
                &lt;td colspan=&quot;2&quot;&gt;
                    &amp;nbsp;
                &lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
                &lt;td colspan=&quot;2&quot; valign=&quot;top&quot;&gt;
                    &lt;div id=&quot;chatOutput&quot; style=&quot;height: 300px; width: 400px; border: solid 1px #000;
                        overflow: scroll;&quot;&gt;
                        &lt;div id=&quot;chatOutputDiv&quot; style=&quot;height: 280px; width: 380px;&quot;&gt;
                        &lt;/div&gt;
                    &lt;/div&gt;
                &lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
                &lt;td colspan=&quot;2&quot;&gt;
                    &amp;nbsp;
                &lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
                &lt;td colspan=&quot;2&quot; valign=&quot;top&quot;&gt;
                    &lt;label&gt;
                        Online Users&lt;/label&gt;&lt;br /&gt;
                    &lt;select class=&quot;txt&quot; size=&quot;4&quot; id=&quot;lstUsers&quot; style=&quot;width: 400px; border: thin solid #000000;
                        font-family: Calibri; font-size: 11pt; color: #FFFFFF;&quot;&gt;
                        &lt;option&gt;No users available &lt;/option&gt;
                    &lt;/select&gt;
                &lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
                &lt;td colspan=&quot;2&quot; style=&quot;text-align: center; font-size: 11px;&quot;&gt;
                    Copyright &amp;copy; 2009 &lt;a href=&quot;mailto:anuraj.p@mymailserver.com&quot;&gt;Anuraj&lt;/a&gt;. All rights
                    reserved.&lt;br /&gt;
                    Licenced under GNU GPL v2.
                &lt;/td&gt;
            &lt;/tr&gt;
        &lt;/table&gt;
    &lt;/div&gt;
    &lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Here is the Image &#8220;Team Chat&#8221; running on my machine</p>
<div id="attachment_374" class="wp-caption alignnone" style="width: 435px"><a href="http://anuraj.files.wordpress.com/2009/09/team_chat_image.jpg"><img src="http://anuraj.files.wordpress.com/2009/09/team_chat_image.jpg" alt="Team chat - asp.net script screenshot" title="Team Chat - Screen shot" width="425" height="580" class="size-full wp-image-374" /></a><p class="wp-caption-text">Team chat - asp.net script screenshot</p></div>
<p>Code seems like pretty self explantory. As wordpress don&#8217;t support zip attachments, I will upload, and give the source later.</p>
<p>Happy Chating <img src='http://www.dotnetthoughts.net/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>I took the Emoticons from <a href="http://comments.deviantart.com/emoticons?order=popularity" target="_blank">deviantart.com</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.dotnetthoughts.net/2009/09/11/a-simple-chat-script-using-asp-net-c/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
