Monthly Archives: September 2013

Simple Browser Based SignalR Chat Application in ASP.NET

In this article, let’s discuss how to build a simple browser-based SignalR chat application.

ASP.NET SignalR is a new library for ASP.NET developers that makes developing real-time web functionality easy. SignalR allows bi-directional communication between server and side. Servers can now push content to connected cliently instantly as it becomes available. SignalR supports Web Sockets, and falls back to other compatible techniques for older browsers. SignalR includes APIs for connection management (for instance, connect and disconnect events), grouping connections, and authorization.

SignalR simplifies the process of building real-time applications. It includes an ASP.NET server library and a JavaScript client library to make it easier to manage client-server connections and push content updates to clients. You can add the SignalR library to an existing ASP.NET application to gain real-time functionality.


1. Create an ASP.NET empty web application project. Call it as “SignalRChat”.

2. Add a new “SignalR Hub Class”, call it as e.g ChatHub.cs

3. Once you added SignalR Hub Class, Script libraries for jQuery and SignalR are automatically added in the project by visual studio. Since it uses old jQuery, you can remove it and add latest jQuery file (1.10 version) which is optional.

4. Add following method in the ChatHub class.

public void Send(string name, string message)
// Call the broadcastMessage method to update clients.
Clients.All.broadcastMessage(name, message);

5. Add a “Gloabal Application Class” file to project.

6. Include following namespaces.

using System.Web.Routing;
using Microsoft.AspNet.SignalR;

7. Add the following line of code in the Application_Start method of the Global class to register the default route for SignalR hubs.


8. Add a ASPX page in the project, call it as “Default.aspx”, include following css and code.

<style type="text/css">
.container {
background-color: #99CCFF;
border: thick solid #808080;
padding: 20px;
margin: 20px;

<input type="text" id="message" />
<input type="button" id="sendmessage" value="Send" />
<input type="hidden" id="displayname" />
<ul id="discussion">
<!--Script references. -->
<!--Reference the jQuery library. -->
<script src="Scripts/jquery-1.10.2.min.js"></script>
<!--Reference the SignalR library. -->
<script src="/Scripts/jquery.signalR-1.0.0.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="/signalr/hubs"></script>
<!--Add script to update the page and send messages.-->
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var chat = $.connection.chatHub;
// Create a function that the hub can call to broadcast messages.
chat.client.broadcastMessage = function (name, message) {
// Html encode display name and message.
var encodedName = $('<div />').text(name).html();
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#discussion').append('<li><strong>' + encodedName
+ '</strong>:&nbsp;&nbsp;' + encodedMsg + '</li>');
// Get the user name and store it to prepend to messages.
$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.

9. Save the project and rebuild the solution. Run the project.

10. First you will be asked to enter your name.

11. Enter your name, click “ok” button to continue. Open another instance of browser, just copy paste the URL from first browser to another. Enter your name on another instance of browser, hit “ok” button.

12. Now enter a message and and click “Send” button. You will see messages you sent will be appeared on all instances of browser.

Hope this help you.

Source Code Download:

Github [Repository Link]


Fill a Dropdownlist using jQuery in ASP.NET

In this article, let’s discuss how to fill a dropdownlist using jQuery in ASP.NET

1. Let’s start by adding a dropdownlist on page.

<asp:DropDownList ID="ddlRecords" runat="server" ClientIDMode="Static"></asp:DropDownList>

Notice that we have set ClientIDMode property to “Static” which means The ClientID value is set to the value of the ID property. So that we can directly refering this control using ID.

2. To fill a dropdownlist, using  jQuery, let’s write a webmethod, which we will call through jQuery Ajax method.

 public static string GetResultset()
 DataTable dataTable = new System.Data.DataTable("Employees");
 using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString))
 SqlDataAdapter sqlDataAdapter = new SqlDataAdapter("SELECT EmployeeID, FirstName + ' ' + LastName AS Name FROM Employees", sqlConnection);
 return JsonConvert.SerializeObject(dataTable);
 catch (Exception ex)
 throw ex;

Notice that we have applied “WebMethod” attribute to this method which is defined in the namespace “using System.Web.Services;”, so we need to include it in the code.

using System.Web.Services;

Set the connection string in the config file.

 <add name="MyConnectionString" connectionString="Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI;User ID=sa;Password=123456" providerName="System.Data.SqlClient"/>

Webmethod Explained:

In the webmethod, we have taken a sql connection and sql adapter to fill a datatable. And the datatable object is serialized using

3. To call this webmethod, let’s write a jQuery code. Before using jQuery, we need to include the reference to it.

<script src=""></script>

4. On document.ready, we will call our webmethod to fill dropdownlist.

<script type="text/javascript">
 $(document).ready(function () {

//fill dropdownlist
 type: "POST",
 url: "Default.aspx/GetResultset",
 data: "{}",
 contentType: "application/json; charset=utf-8",
 dataType: "json",
 success: function (data) {
 $.each(jQuery.parseJSON(data.d), function () {
 error: function (msg) {


Here data will have number of records, so we have iterated through each record using .each() and appended a record to our dropdownlist. Since we are getting serialized data, we have parsed data using jQuery.parseJSON()

Source Code Download:

Github [Repository Link]

ASP.NET MVC Overview

The Model-View-Controller (MVC) architectural pattern separates an application into three main components namely the model, the view and the controller. The ASP.NET MVC framework is a very lightweight framework and it is also integrated with existing ASP.NET features such as master pages.

The MVC framework is defined in the System.Web.Mvc assembly.

MVC Components:

1. Model

They are part of application’s data domain. Often, model objects retrieve and store model state in a database.

2. View

They are the components that display the application’s user interface (UI). This UI is created from the model data.

3. Controller

They are the components that handle user interaction, work with the model, and ultimately select a view to render that displays UI.

In an MVC application, the view only displays information; the controller handles and responds to user input and interaction. For example, the controller handles query-string values, and passes these values to the model, which in turn might use these values to query the database.


1. Since application components are divided into 3 i.e the model, the view, and the controller, It makes it easier to manage complexity.

2. It does not use view state or server-based forms.

3. It enables you to design an application that supports a rich routing infrastructure.

4. It provides better support for test-driven development (TDD).

5. It is ideal for large teams of developers and for Web designers who need a high degree of control over the application behaviour.


1. Separation of application tasks (input logic, business logic, and UI logic), testability, and test-driven development (TDD). All core contracts in the MVC framework are interface-based and can be tested by using mock objects

2. An extensible and pluggable framework.

3. Extensive support for ASP.NET routing.

4. You can use existing ASP.NET features with the ASP.NET MVC framework, such as nested master pages, in-line expressions (<%= %>), declarative server controls, templates, data-binding, localization, and so on.

5. Support for existing ASP.NET features such as forms authentication and Windows authentication, membership and roles, output and data caching, session management etc.

What is the future of ASP.NET and MVC?

There are lots of articles on the internet that will put some thoughts on “What is the future of ASP.NET?”

Some thoughts:

As a developer, do you know Silverlight? Yes/No ?

Few years back, Microsoft marketing team promoted it. They promoted it in such a way that developers thought Silverlight will be the next Adobe Flash. A very popular companies such as Netflix, Renault Megane, NBC etc developed their websites using Silverlight.

But Where is Silverlight today? What is the share of Silverlight today in the market? What is the trend?

Now what about upcoming things like HTML 5TypeScriptMVC etc.. etc..?

Back to the main point, what is the future of ASP.NET and MVC?

It is true that, there is a shift to MVC from ASP.NET web forms. ASP.Net MVC is on the rise and growing more popular everyday. Another reason, ASP.Net MVC is becoming very popular, since it can take advantage of all the fantastic features coming with HTML 5 as well as new client-side libraries with ease . But they are much harder to integrate in ASP.NET webForms than MVC.

As the technologies are advancing, things are getting better and better with every advancements. So it’s the trend which will lead us the way we develop the sites.

So I don’t think that a technology is coming that would replace everything, rather think that new improvements would be made in the existing technology and knowledge of current technology would help you adapt to those new changes.

What do you think the future of ASP.NET and MVC should be? Thumbs up, or thumbs down? Share your thoughts please.

Must Have Tools, Utilities, References for a Developer

In this post, I want to list out free tools, utilities and references for a developer (in no specific/particular order)

MSDN Library – An essential source of information for developers using Microsoft tools, products, technologies and services.

jQuery – A fast, small, and feature-rich JavaScript library.

VirtualBox –  It is a virtualization software package. It supports 32/64 bit Linux, Mac OS X, Windows, Solaris operating systems.

Firebug –  The most popular and powerful web development tool that can be used to edit, debug, and monitor CSS, HTML, and JavaScript live in any web page.

WinMerge – It is differencing and merging tool for Windows.

Color-hex – It gives information about colors including different color models like RGB, HSL etc. It also generates a simple css code for the selected color.

SQL Dumper – It enables you to dump selected SQL Server database tables into SQL INSERT statements.

Color Picker – It enables you to pick any color from the screen. – It enables you to easily test code snippets like HTML, CSS, javascript etc online.

Glimpse – It shows execution timings, server configuration, request data and more, all in browser, with no changes to your application code.

Moq – The simplest mocking library for .NET and Silverlight.

Imgur – An online image hosting service.

NUnit – A unit-testing framework for all .Net languages.

Fiddler – It is a free web debugging tool which logs all HTTP(S) traffic between your computer and the Internet. It can be an awesome tool for troubleshooting things like AJAX Requests.

AjaxControl Toolkit – It contains more than 30 controls that enable you to easily create rich, interactive web pages.

The ASP.NET Community Control Gallery – A user-driven area with hundreds of openly available controls.

JSBin – (Very much simillar to JSFiddle) It’s an online environment that can be used to create and share examples using Javascript, HTML, External Libraries and CSS.

Google PageSpeed Insights – An online analyzer to find areas of improvement to optimize your web site.

SQLFiddle – A great tool for performing online testing of SQL database code. It allows you to create schemas and query them and you can easily share your creations via URL.

Microsoft Expression Web – A full-featured professional tool for designing, developing, and publishing compelling, feature-rich websites.

Google’s Closure Compiler Online – An awesome tool for optimizing Javascript.

Online GUID Generator – A very basic online GUID generator.

Web Developer Checklist – The ultimate checklist for web developers.

LINQPad – A tool to query databases in a modern query language: LINQ.

ILSpy – Open-source .NET assembly browser and decompiler.

Sysinternals – A tool to manage, troubleshoot and diagnose Windows systems and applications.

Expresso – A regular expression development tool.

log4net – A tool to help the programmer output log statements to a variety of output targets.

Lucene – A high-performance, full-featured text search engine library.

iTextSharp – An open source library for PDF generation and manipulation.

Enterprise Library – A collection of reusable software components such as logging, validation, data access, exception handling, and many others.

C# to VB.NET Code Converter – A code conversion tool from C# to VB.NET.

CKEditor (FckEditor) – A ready-for-use WYSIWYG HTML text editor.

Browsers – Such as Internet Explorer, Firefox, Google Chrome, Opera, Safari etc.

Snipping tool – A tool to capture a screen shot of anything on your desktop.

TortoiseSVN – An Apache Subversion (SVN) client

GitHub – Online project hosting using Git.

CodePlex – Microsoft’s open source project hosting web site.

Ohloh Code – An open source code search engine.

Sourceforge – A web-based source code repository.

cdnjs – A CDN hosting site for the most popular libraries

If I miss anything here, Please suggest.

Replace All Occurrences of a String in JavaScript

In this article, let’s discuss about how to replace all the occurrences of a string in a javascript.

To make it generic, Lets define a replaceall method in javascript.

Case sensitive replace all

Following code will replace all occurrences of a string globally using case sensitive pattern.

We are using regular expression to replace a string occurrence globally ‘g’.

String.prototype.replaceAll = function (targetString, subString) {
 var inputString = this;
 inputString = inputString.replace(new RegExp(targetString, 'g'), subString); //replace a string globally and case sensitive

return (inputString);

Prototype is a global property which is available with almost all JavaScript objects. It allows you to add properties and methods to an object.

JavaScript prototype Property Syntax:


var inputString = "This is aBc. aBC is not a bad start. This is good ABC";

inputString = inputString.replaceAll("aBc", "xyz"); //replace all case sensitive

alert(inputString); //This will print "This is xyz. aBC is not a bad start. This is good ABC"

Case insensitive replace all

We are using regular expression to replace a string occurrence globally and case insensitive which is ‘gi’.

String.prototype.replaceAllCaseInSensitive = function (targetString, subString) {
 var inputString = this;
 inputString = inputString.replace(new RegExp(targetString, 'gi'), subString); //replace a string globally and case-insensitive

return (inputString);


var inputString = "This is aBc. aBC is not a bad start. This is good ABC";

inputString = inputString.replaceAll("abc", "xyz"); //replace all case sensitive

alert(inputString); //This will print "This is xyz. xyz is not a bad start. This is good xyz"

jsFiddle example

Related articles

Inline Expressions in ASP.NET

Inline expressions are used to write server side code directly on aspx, ascx, javascript pages or files.

Let’s discuss Inline expressions in ASP.NET

1. <% … %> embedded code blocks

They are supported in ASP.NET Web pages primarily to preserve backward compatibility with older ASP technology. It is NOT recommended to use embedded code blocks for complex programming logic, because when the code is mixed on the page with markup, it can be difficult to debug and maintain. Also the code is executed only during the page’s render phase

Consider following example, it shows an ASP.NET page with an embedded code block that displays the results of a for loop.

<%@ Page Language="C#" %></pre>
<form id="form1">
 <% for(int index=0;index<10;index++){%>
 <% Response.Write(index)%>
 <% }%>

2. <%= … %> displaying expression

It is an equivalent of the embedded code block. It is the simplest way to display information from an ASP.NET program such as a single string, an int variable, or a constant.

For example, the following sample code displays the current time:

<%@ Page Language="C#" %>

<form id="form1">
 <%=DateTime.Now.ToString() %>

3. <%@ … %> directive expression

It is the syntax that specifies settings that are used by the page and by user control.

The @ Page directive can be used only in .aspx files, and the @ Control directive can be used only in .ascx files.

The ASP.NET page framework supports directives such as @ Page, @ Control, @ Register etc.

4. <%# … %> data-binding expression

It creates binding between a server control property and a datasource when the control’s DataBind method of this server control is called on the page.


<%@ Page Language="C#" %>
<script type="text/javascript">// <![CDATA[
 Protected string SayHello()
 Return "Hello World";
// ]]></script>

<form id="form1"></form>

5. <%$ … %> expression builder

The expression builder is used to set values of control properties based on the informationthat is contained in an application’s configuration or resource files. The following is the basic syntax of the expression builder:

<%$ Expression Prefix: Expression Value %>

The dollar sign ($) indicates to ASP.NET that the following expression is an expression builder. The expression prefix defines the kind of expression, such as AppSettings, ConnectionStrings, or Resources. Additionally, you can create and define your own expression builder. The expression value that follows the colon (:) is what ASP.NET will actually use as the value of a certain property.


The expression builder can be used in the ASP.NET Web Form page as:

6. <%– … — %> server-side comments block

It will allow developers to embed code comments in any location of the HTML source except for within <script> code blocks.

The following code example shows how to use the server-side comments block in an ASP.NET page:

<%@ Page Language="C#" %>

<form id="form1">
 <%-- This is comment and wont be rendered