WCF RESTful service hosting on IIS6 and consuming by jQuery

Couple of days ago I needed to deploy a WCF RESTfull service on IIS6.  Before then I never deployed RESTfull service on IIS6 so it came up with quite configurations for me. While I was deploying this web service on IIS6, I as usual Goggled for some configuration related help, although I found, but most of the stuff were scattered. I mean I didn’t find all in a single post or a blog. So I thought why couldn’t do it.

In this post I developed a WCF RESTfull web service from scratch to hosting on web server and consuming by jQuery ajax.  Here is the service contract. You’ll find UriTemplate with both with parameters  and without parameter.

    ///<website>deepasp.wordpress.com</website>
    [ServiceContract(Name = "DeepASPService", Namespace = "deepasp.wordpress.com")]    
    interface IDeepASPService
    {
        /// <summary>
        /// Returns all articles from the blog.
        /// </summary>        
        /// <returns></returns>
        [OperationContract]
        [WebGet(UriTemplate = "/GetArticles?blogName={blogName}", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]        
        List<Article> GetAllArticles(string blogName);

        [OperationContract]
        [WebGet(UriTemplate = "/GetTagArticles?tagName={tagName}", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
        List<Article> GetArticlesByTagName(string tagName);

        [OperationContract]
        [WebGet(UriTemplate = "/GetArticle?Id={Id}", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
        Article GetArticleById(string Id);

        [OperationContract]
        [WebGet(UriTemplate = "/SaveArticle?authenticationToken={authenticationToken}&title={title}&body={body}&submittedBy={submittedBy}", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
        bool SaveArticle(string authenticationToken, string title, string body, string submittedBy);
    }

Here is the Service implementing above contract. Most of the operations are only defined and not fully implemented as it didn’t need for this post. GetArticles operation returns a generic list in json format.

    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class DeepASPService : IDeepASPService
    {
        public List<Article> GetAllArticles(string blogName)
        {
            return new List<Article>()
            {
                new Article { Id = Guid.NewGuid(), Name=blogName, Title = "WCF RESTfull web service.", Body = "Html body.", Comments=new List<Comment>()
                {
                    new Comment { Id = Guid.NewGuid(), CommentedOn = DateTime.Now, DisplayName = "deepasp.wordpress.com", Email="no-emailId@deepasp.wordpress.com", Replies = null }
                }},
                new Article { Id = Guid.NewGuid(), Name=blogName,Title = "WCF RESTfull web service deploying on IIS 6.", Body = "Html body.", Comments=new List<Comment>()
                    {
                        new Comment { Id = Guid.NewGuid(), CommentedOn = DateTime.Now, DisplayName = "deepasp.wordpress.com", Email="no-emailId@deepasp.wordpress.com", Replies = new List<Comment> ()
                        {
                            new Comment { Id = Guid.NewGuid(), CommentedOn = DateTime.Now, DisplayName = "deepasp.wordpress.com", Email="no-emailId@deepasp.wordpress.com", Replies =null }
                        }
                    }
                }},
            };
        }

        public List<Article> GetArticlesByTagName(string tagName)
        {
            throw new NotImplementedException();
        }

        public Article GetArticleById(string Id)
        {
            throw new NotImplementedException();
        }

        public bool SaveArticle(string authenticationToken, string title, string body, string submittedBy)
        {
            if (AuthenticateRequest(authenticationToken))
            {
                //save article
            }
            return true;
        }

        private bool AuthenticateRequest(string authenticationToken)
        {
            //authentication code
            return true;
        }
    }

In this sample application there are only two data contracts but you can have as many data contracts as you need.
DataContracts:

    [Serializable]
    [DataContract]
    public class Article
    {
        [DataMember]
        public Guid Id { get; set; }

        [DataMember]
        public string Name { get; set; }

        [DataMember]
        public string Title { get; set; }

        [DataMember]
        public string Body { get; set; }

        [DataMember]
        public List<Comment> Comments { get; set; }        
    }
    [Serializable]
    [DataContract]
    public class Comment
    {
        [DataMember]
        public Guid Id { get; set; }

        [DataMember]
        public string DisplayName { get; set; }

        [DataMember]
        public string Body { get; set; }

        [DataMember]
        public DateTime CommentedOn { get; set; }

        [DataMember]
        public string Email { get; set; }

        [DataMember]
        public List<Comment> Replies { get; set; }
    }

Configurations:
Service.svc


 Service="Namespace.serviceName" Factory="System.ServiceModel.Activation.WebServiceHostFactory"

web.config:

<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
    <services>
      <service name="Namespace.ServiceName" behaviorConfiguration="ServiceBehavior">
        <endpoint binding="webHttpBinding" contract="Namespace.InterfaceName"
                  behaviorConfiguration="webHttp"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior" >
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
        <behavior>
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="True"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="webHttp">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
</configuration>

 

Now we will host this service on IIS. So here is the step by step procedure;

1-Right click on website go to New

2-Click Create virtual directory(in this sample code I created a virutal directory in an existing website)

3- A wizard screen will come up like;

CreatingVD

 

 

 

 

 

 

 

 

 

 

 

 

 

 

4-Click Next

5-In Alias textbox give any name for your service e.g. TestRESTfullService

6-Next and browse the path where your service is e.g. wwwroot\RESTfullWCFService

7-Next

8-Next

9-FINISH

Now although you have successfully deployed your service on IIS but hereafter configurations are required to run it properly.

1-Right click on the new virtual directory you created(e.g. TestRESTfullService)

2-Go to properties

3-By default this virtual directory will be shown as a website(globe logo will appear before it) so you need to convert this into an application.

4-Click on Create application button as showing at #1 in the below picture. After creating application your service icon will change from globe to gear.

createApplication

 

 

 

 

 

 

 

 

 

 

 

 

 

figure 2

 

 

 

5-Change execute permissions from None to Scripts only like the process 2 in the above picture

6- Click on Configuration button and you’ll see this screen;

ConfigurationStep1

 

 

 

 

 

 

 

 

 

7-Click on Insert and you’ll see a small screen like this;

ConfigurationStep4

 

 

 

 

8-Click on Browse and select aspnet_isapi.dll from C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll. If you don’t find v4.0.30319 folder and it means you don’t have dotnet framework 4 full version. So you’ll have to download it from microsoft website and install it. After installation complete you’ll find this so then select it.

9- DO NOT FORGET to uncheck “Verify that file exists” checkbox from the above screen.

10- Now click on Directory Security tab from figure 2.

11- In this Authentication Methods screen you will uncheck “Integrated windows authentication” checkbox.

12- Click OK.

13-Now go to ASP.Net tab from figure 2 and select ASP.Net version : 4.0.30313. (Sometimes a message will appear when version is changed so just press OK).

14- Now restart your IIS. It will lose all sessions of websites hosted on this server so be cautious, its better to do at night time.

14-That’s all you needed.You’ve done it !

Your WCF RESTfull service must be running

Now its time to consume your service. Here we will consume using jQuery ajax like;

function GetAllArticles() {
            var url = "/TestRESTfullService/ServiceName.svc/GetArticles?blogName=deepasp";
            $(function() {
                $.ajax({
                    type: "GET",
                    url: url,
                    async: true,
                    dataType: "json",
                    success: function(articles) {
                        if (msg != null) {
                            document.getElementById("response").innerHTML = ConvertObjecToHtml(articles);
                        }
                        else{
                            document.getElementById("response").innerHTML ="No articles published yet on this blog";
                        }
                    },
                    error: function(e) {
                        alert("Error occured while processing service request" + e.responseText);
                    }
                });
            });
        }

Here download the source code;

Session Variables Management

Session variables are used in our web applications quite often. Some of the variables are maintained for the whole session. So we can use them in different places to perform application’s logic. But while getting some values errors happen just because of a small silly spelling mistake and application blows up. We can somehow overcome most of the common session variables spelling mistake problems by using static classes. Because in this way you don’t need to spell each time you access.

In this post I created a static class in Web/UI layer and created properties for all those common session variables used by our application. So in this way you can set or get your session variables just using this class. It also serves you to organize your session variables in your project.
As it is only a class so I captured it in an image, but if you need source code it can be provided.

 /// <summary>
    /// Managing Session Variables
    /// </summary>
    internal static class BlogSessionVariables
    {
        /// <summary>
        /// Gets sets UserIdentification variable.
        /// </summary>
        public static string UserIdentifier
        {
            get { return (HttpContext.Current.Session["UserIdentification"] != null ? Convert.ToString(HttpContext.Current.Session["UserIdentification"]) : string.Empty); }
            set { HttpContext.Current.Session["UserIdentification"] = value; }
        }

        /// <summary>
        /// Gets sets articles variable.
        /// </summary>
        public static List<dynamic> Articles
        {
            get { return (HttpContext.Current.Session["Articles"] != null ? (List<dynamic>)HttpContext.Current.Session["Articles"] : null); }
            set { HttpContext.Current.Session["Articles"] = value; }
        }
    }

Click the image to enlarge so you can view the whole class and test functions.
session variable management

Pure JavaScript Autocomplete in ASP Classic

In this post I implemented auto-suggestion using pure JavaScript. Although if you wanna use jQuery autocomplete you can use it. But if you are only using for this purpose then I would recommend not to use jQuery.

Firstly they are large files which will obviously affect your application’s performance. Secondly it is little slower in DOM traversing than pure JavaScript. Thirdly you can easily change JavaScript code, as you don’t necessarily need to have high level expertise in JavaScript.
In addition to that sometimes it has browser compatibility issues as well. So always try to use more standard and basic way in your programming. At least that’s my practice.

I implemented this JavaScript Autocomplete using ASP Classic as a server side language. But you can use any other language. I tried to make it as simple as possible but you can still make it more simple because there’s always a room for better.

This is the html:

 <input type="text" id="txtSearchEngines" class="data">
 <div id="suggestionBox" style="display:none">sss</div>

CSS classes:

#suggestionBox{
    position: absolute;
    z-index:999;
    border:01 gray solid;
    background-color:#E6E6E6;
    width: 300px;    
}
.suggest-data{
	line-height:20px;
    font-family: Tahoma;
    font-size:12px;
}
.rowSelected{
    background-color:#415C7C;
    color:white;
}

Here’s the JavaScript Code:

var request,xmlhttp,rowToSelect = 0,searchTextBox = document.getElementById("txtSearchEngines"),
_URL="AutoSuggest.asp";	
	BindSearchTextBox();
function BindSearchTextBox(){
	searchTextBox.addEventListener("keyup", KeyUpOnSearchTextBox,false);
	searchTextBox.addEventListener("keydown",HandleTabKey);
	document.getElementsByTagName("body")[0].addEventListener("click",CloseSuggestionBox);
}
function KeyUpOnSearchTextBox(e){
	var suggestBox = document.getElementById("suggestionBox");
	if((e.keyCode >= 65 && e.keyCode <= 90) || (e.keyCode == 40 || e.keyCode == 38 || e.keyCode == 8) ){				
		searchTextBox.removeEventListener("keyup",KeyUpOnSearchTextBox);
		if((e.keyCode == 40 || e.keyCode == 38 ) && suggestBox.style.display != "none"){    				
			SelectSuggestedRow(e.keyCode == 40 ? 1: -1 );
			BindSearchTextBox();
		}
		else{
			if(null != searchTextBox.value && "" != searchTextBox.value) SendAJAXRequestToServer(_URL+"?type=s&searchKey="+searchTextBox.value,ShowSuggestion,true);
			else{ HideSuggestionBox(); BindSearchTextBox();}
		}
	}
	else if(e.keyCode==13){searchTextBox.removeEventListener("keyup",KeyUpOnSearchTextBox); GetSelectedDetail(); }
}
function ShowSuggestion(){
	if (xmlhttp.readyState == 4) {
		if(xmlhttp.responseText != ""){
    		var suggestBox = document.getElementById("suggestionBox"),suggestRow=document.getElementById("suggest-rows");
    		suggestBox.style.display="";
    		suggestBox.style.top= searchTextBox.offsetTop + searchTextBox.offsetHeight+ 02;
    		suggestBox.style.left= searchTextBox.offsetLeft;
    		suggestBox.innerHTML = xmlhttp.responseText;    		
    		suggestBox.style.display="";	
    		SelectSuggestedRow(0);
		}
		else HideSuggestionBox();
		BindSearchTextBox();
	}
}
function CloseSuggestionBox(e){
	var eObj = e || window.event;
	if(eObj.target.className.indexOf("data") == -1) HideSuggestionBox();
}
function HandleTabKey(e){
	if(e.keyCode == 9) GetSelectedDetail();
	else if(e.keyCode == 27) HideSuggestionBox();
}
function HideSuggestionBox(){
	var suggestBox = document.getElementById("suggestionBox");
	suggestBox.innerHTML = null;
	suggestBox.style.display ="none";	
	rowToSelect=0;
	BindSearchTextBox();	
}
function HoverOverSuggestedList(obj){UnselectRow(); rowToSelect = obj.getAttribute("rowIndex"); SelectRow();}
function SelectRow(){document.getElementById("tblSuggest").rows[rowToSelect].className = "suggest-data rowSelected";}
function SelectedRowClicked(e){GetSelectedDetail();}
function UnselectRow(){	var suggestedTable=document.getElementById("tblSuggest");if(suggestedTable != null) suggestedTable.rows[rowToSelect].className = "suggest-data";}
function SelectSuggestedRow(rowCount){
	UnselectRow();
	if(rowToSelect == 0){ if(rowCount == 1) rowToSelect = rowCount;}
	else rowToSelect = rowToSelect + rowCount;
	if(rowToSelect >= document.getElementById("tblSuggest").rows.length){rowToSelect = rowToSelect - 1;SelectRow();}
	else SelectRow();
}
function GetSelectedDetail(){
	var suggestedTable=document.getElementById("tblSuggest");
	if(suggestedTable != null){
    	document.getElementById("lblName").innerHTML=suggestedTable.rows[rowToSelect].cells[1].innerHTML;
    	document.getElementById("lblValue").innerHTML=suggestedTable.rows[rowToSelect].cells[0].innerHTML;
	}
	HideSuggestionBox();
}
function SendAJAXRequestToServer(url,handler,ajax){
	xmlhttp= new XMLHttpRequest();
	xmlhttp.open('GET', url,ajax);
	xmlhttp.onreadystatechange = handler;
	xmlhttp.send(null);
}

ASP Classic code to return the suggestions for the search key;

'put your security/authenciation code here
response.write GetSuggestion
response.end
public Function GetSuggestion
	'Its just a demo you can write your code to get from database.
	dim searchKey 
		searchKey = Request.QueryString("searchKey")
	if(searchKey = "g") then
		GetSuggestion = "<table border='0' cellpadding='0' cellspacing='0' width='100%' id=""tblSuggest""><tr onclick=""SelectedRowClicked(event)"" onmouseover=""HoverOverSuggestedList(this)"" name='suggest-rows' rowIndex=""0"" class='suggest-data data' ><td class=""data"" style=""display:none"">1</td><td class=""data"" align='left' class=""data"">Google</td></tr><tr onmouseover=""HoverOverSuggestedList(this)"" onclick=""SelectedRowClicked(event)"" name='suggest-rows' class='suggest-data data' rowIndex=""2""><td class=""data"" style=""display:none"">3</td><td class=""data"" align='left'>Google2</td></tr></table>"
	else if(searchKey = "b") then
		GetSuggestion = "<table border='0' cellpadding='0' cellspacing='0' width='100%' id=""tblSuggest""><tr onclick=""SelectedRowClicked(event)"" onmouseover=""HoverOverSuggestedList(this)"" name='suggest-rows' class='suggest-data data' rowIndex=""1""><td class=""data"" style=""display:none"">2</td><td class=""data"" align='left'>Bing</td></tr></table>"
	end if
	end if
end function

Instantiate Anonymous Generic List in C#

Sometimes we need anonymous objects in our day to day programming. I used anonymous types in my LINQ queries but I never instantiated an anonymous generic list, I mean I never needed to do it. But now I needed and found an easy way to do it. So if you need it you can enjoy :)

         /// <summary>
        /// Returns geo-location of cities.        
        /// </summary>
        /// <returns></returns>
        internal List<dynamic> GetCitiesGeoLocation()
        {
            List<dynamic> cities = new List<dynamic>(){
                new { Name="Lahore", Latitude ="31.5497N", Longitude="74.3436E" },
                new { Name="London", Latitude ="51.5072N", Longitude="0.1275W" },
                new { Name ="Kansas City", Latitude ="39.0997N", Longitude ="94.5783W"}
            };

            return cities;
        }

Uses of Jquery Filter Selector

Jquery Filter selector becomes very handy for a geek who’s found of lambda function in LINQ. Here are some scenarios where we can easily use filter selector. Its very useful for a complex filter.
Some of the scenarios are;

  1. Dynamically setting the selected option of a dropdownlist
    
      $('#dropdownlistId option').filter(function() {
    return $.trim( $(this).text() ) == "Value to Compare"; })
    .attr('selected',true);
    
    
  2. Dynamically changing the background color of a particular checked checkbox.
    
      $('input:checked').filter(function() { 
    return $.trim( $(this).val() ) == "Value to Compare"; })
    .css('background-color','#fff');
    
    

Could not complete the operation due to error 80020101 in IE11

November 27, 2013 Leave a comment

My asp.net application was working on all browsers before IE11 came in. But when IE11 launched and users started to use it,I got lot of complaints about the UI mess and postbacks . The most irritating thing was neither AJAX UpdatePanel was working nor any postbacks on the page.  So I googled it for almost two days trying different tricks/tips but didn’t work, but then I found this hotfix on microsoft website; http://support.microsoft.com/kb/2836939/en-us.
Most important thing is that after downloading this file you need to install on the server where asp.net website/application is deployed/hosted. Because this error is not an error of your project/application, but its an issue of dotnet framework 4.0 and 2.0.

jQuery Dialog in Asp.Net Master Page

Web developers have been enjoying the elegancy of the jQuery over the years. Many of us have used jQuery Dialog for different purposes.

In this post I’m trying to show how you can easily integrate it in your master page.
You’ll need to import the jquery core and ui libraries before this dialog code.
Define the dialog code in the head section of the master page.
If you want to know all of its properties and configurations then you can find Documentation

<script type="text/javascript">
$(function () {var dialogDefine = $("#divLoginDialog").dialog({
               autoOpen: false,
               modal: true,
               closeOnEscape: true,
               draggable: false,
               resizable: false,
               position: [350, 250],
               title: "Login",
               overlay: "background-color: black; opacity: 90",
               buttons: {
               Cancel: function(){ $(this).dialog('close');},
               Ok: function () { /*Call your custom validation code;*/ }}
         }); //end dialog
$("#hlkShowLogin").click(function () {
            $("#divLoginDialog").dialog('open');
            $("#divLoginDialog").parent().appendTo($("form:first"));
            return;
        });
});//end Jquery
</script>

The hyperlink which will show the dialog is like;

<a href="#" id="hlkShowLogin" class="link">Login</a>

Here’s the login dialog html. In this post I’ve used jQuery buttons, but you can use asp.net buttons.
EDIT:: In ASP.Net sample code jQuery buttons replaced with normal asp.net buttons.

<div id="divLoginDialog" style="display: none;">
<table cellspacing="0" cellpadding="2">
<tr>
<td class="label">User Name:</td>
<td>
<asp:TextBox ID="txtUserName" ClientIDMode="Static"  runat="server"/>
<asp:RequiredFieldValidator ErrorMessage="User name required" ControlToValidate="txtUserName" runat="server" />
</td>
</tr>
<tr>
<td class="label">Password:</td>
<td>
<asp:TextBox ID="txtPassword" Mode="password" ClientIDMode="Static"  runat="server"/>
<asp:RequiredFieldValidator ErrorMessage="Password required" ControlToValidate="txtPassword" runat="server" />
</td>
</tr>
</table>
</div>

Here download the sample solution in asp.net.

Follow

Get every new post delivered to your Inbox.