How to consume wcf service using JavaScript Proxy

Hello All,

Today I am going to discuss one another great feature of WCF. Do you know that a WCF service allows us to create a JavaScript Proxy?

Yes it does!!

But let’s first understand that what is a proxy? As we already know whenever we have to use any web service or WCF service, we need to create proxy of that service and with the help of proxy, we use the functionalists provided by the web/WCF service.  Proxy acts a intermediary between the client of the service and the actual service. Proxy provides a simple interface to the consumer of service and all the intricacies like creating a connection, creating and sending the request, getting the response etc is handled by the proxy itself.

Continue reading

Claim based Authentication : Part 4

Its a little gap in between my third and fourth part, anyways I am going to write 4th part of the series. First you can read my earlier parts from the link below.

As if you have read my earlier posts in the series, you can visualize  that in my first post I discussed about the Idea about Claim based authentication, basics and various components of Claim based authentication.

Continue reading

Authentication and Session timeout – Session expired message on clicking the login button

In my starting phase of Career, My client reported me a peculiar issue. They said that they get redirected to session expired page even before they actually Login.

In that application, We developed a generic methodology, then whenever a user clicks on any action that requires a post back, it first checks whether session is expired or not and if expired then redirects to a custom session expired page. Later, user can click on login link and redirected to Login page.

[As asked by one of my blog readers, There could be many ways for the generic methodology. I have seen people place common code at several place like Master Page,  some put in base class that further worked as base class for all the web pages. I used it in a base class. In my view there are other places like Global.asax and methods could be Application_PreRequestHandlerExecute, Application_AcquireRequestState .]

I analyzed that Issue and found that users used to open the website first page which is obviously the Login page and some of them left the page for a while around 15 or more minutes and after that they when they again back to system, used to enter the credentials and click on login button, it redirects them to session expired page.

It left them annoying and even me too. I have myself seen to many application where I open the Login page and after sometime when I enter my Login details but it redirects me to session expired page.

Some of my colleagues was saying, how a session can expire even before successfully login. I have also found many other developers have same question. So I thought of writing a blog post on it.

So first let me explain, how session works

Session_Life_Cycle

So as you can see above, as soon as user accesses the site and the first page gets opened, the countdown of the session timeout starts. So it does not matter whether you Login or not, session will be expired after the specified amount of time. So if your website does not have a check on session expiration before Login then it wont be visible to your user and even if user Logins after the specified amount of time, A new session will be created.

But so many people get confused about authentication and session. Session start and expire does not have any connection with authentication start and authentication timeout. Authentication works separately.

As you know, A user request any Page, It goes through many HTTPModules and lastly served by a HTTPHandler. We can show it pictorially as

ASP.NET Request Proessing

As you can see, An asp.net request goes through many HTTPModules and finally served by a HTTPHandler. Many features of ASP.NET are developed as HTTP Module. Session and Authentication are also developed as HTTPModules . For session handling we have SessionStateModule which is available under the namespace System.Web.SessionState and various Authentication mechanism in ASP.NET like Form Authentication is also available via a HTTPModule FormsAuthenticationModule which is under the namespace System.Web.Security.  So these two are separate modules and works independently.

Normally in our application, as soon as user clicks on sign out, we used to kill session. Normally, we set authentication time out and session timeout same but what may happen if we have

<forms timeout="15" loginUrl="Login.aspx" name=".ASPXFORMSAUTH">

and

<sessionState timeout="10">

What could happen

user's browsing history

As you can see in the above scenario, I have set session time out is less than authentication timeout. After browsing for 5 mins, I left it for around 12 mins and my session got timeout.  As my session time out is 10 mins while my authentication time out is 15 mins. But I’ll be still authenticated and able to browse application even my session expired and got recreated and my existing session data will be lost.

So normally we put the authentication time out and same time out as same. This is just first step to avoid the discrepancy between the timeout of Authentication and Session.

But at certain browsers, it behaves differently. Like Session gets time out if the last request made was 10 (in my example session timeout is 10 minutes) or more minutes and on every request the counter get resets for 10 minutes but Authentication timeout does not work in same ways in different browsers. Like if have authentication timeout for 10 minutes, the authentication timeout counter does not get reset on every request to 10 minutes. Sometimes there are some performance improvement has been done which resets on the counter only at certain points say if after 5 or 7 minutes as to reset the authentication timeout on very request is costly. And this may lead to discrepancy.

Other scenario, If some how IIS gets reset the sessions of the users connected to that web server will become invalid while the user authentication will still be valid.

To avoid any unprecedented event like above, I put a check for an authentication and session on every page, So that user cannot continue further if session or authentication is not valid. Also if we found user is not authenticated any more then used to clear and abandon the session and redirects the user to login page. Similarly, if session is not available then the remove the user the authentication as well.

Also, at the time of user clicking on Logoff, one should clear and abandon the session. So that same session is not available after Logoff.

So as you can see, that session and authentication works separately and they work parallely and independently.

So for the problem stated earlier in this post, I suggested a solution to avoid the issue but you can yourself can put your own logic to prevent the issue.

Hope you all have enjoyed this post. Please share your valuable feedback.

Cheers,
Brij

FriendlyURL : A new and exciting feature of ASP.NET

This is going to be the last post of 2012 by me. I am very happy that I am writing about a very exciting feature that is coming with ASP.NET.

I am really excited to learn and write on this. I really hated the ugly URLs and the extensions of the page that always visible when one opens the application unless and until you write your own custom url processor. With ASP.NET 4.0, Routing was introduced, which provided the capability to ASP.NET to have easier, manageable and SEO friendly urls, I wrote a post on it. You can click below to have a look on it.

URL Routing with ASP.NET 4.0

But that is little tidy to write. And it looks like writing extra code that does not produces any business functionality.

FriendlyURL as the name suggests gives a clean and SEO friendly URL.Currently it is available via NuGet and in pre release version.

So For this post, I have used my Visual Studio 2012 IDE. I created a new project as File-> New -> Website -> ASP.NET Empty Website.

Once the project got created. I require to install the NuGet for my application. So got to Tools-> Library Package Manager-> Package Manager Console

Package Manager Console

It opens a console then type Install-Package Microsoft.AspNet.FriendlyUrls -Pre and press enter as

FriendlyURL NugetInstallation

As you can see, I typed the command and can be seen in  the first red encircled area and press enter. It’ll install the NuGet and you can see the last red encircled area which shows FirendlyUrl is successfully added.

This can be used with two ASP.NET versions: ASP.NET 4.5 and ASP.NET 4.0.

Now you are ready for working with friendly URLs.

If you have  read the Readme.text. It gives a clear  idea how to start with. But I’ll take you through the steps. So let’s start

Step 1-> Add and Create a Class name preferably RouteConfig.cs ( You can have any name. I used MyRouteConfig.cs) and make it static. Also add the name space in the class Microsoft.AspNet.FriendlyUrls

Step 2-> Create a static Function in the class preferably named as RegisterRoutes with a Parameter of type RouteCollection and add  a line  routes.EnableFriendlyUrls() in the method as

public static class MyRouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.EnableFriendlyUrls();
    }
}

Step 3-> Add Global.asax file and add the following line in Application_Start as

  void Application_Start(object sender, EventArgs e)
    {
        MyRouteConfig.RegisterRoutes(RouteTable.Routes)
    }

Now you can start the development of your application. I have created two pages First.aspx and Second.aspx in my solution

That’s it. Now your code is ready for run.

First PageIf you see the above circled area in the above pic, it does not contain page extension (aspx). So now the url looks pretty. As an end user, I don’t care about the page extension and even some time it just irritates me.

Now if you want to redirect to another page, you can redirect by typing URL without page extension as

Response.Redirect("~\\Second");

There is one caveat here. You can not have a folder and Page with same name at the same level. If you have the name of a folder and the name of aspx page at same level, you would not be able to access the page without extension. So please keep it in mind.

Now you must have a question in Querystring. What will happen with Querystring?

You don’t need to worry at all. QueryStrings will work as earlier . Let’s have a look to the URL http://localhost:57353/First?Id=1001 then you can read the QueryString as below similar as earlier

string Id = Request.QueryString["Id"] as string;

Next point, if I have a URL say http://localhost:57353/First/Products/NewProduct and there is no page as NewProduct. What will happen It’ll open First.aspx.

But, How it works?

It starts from last segment (NewProduct) and will check if there is any NewProduct.aspx. If not then it moves to next segment and continue till it finds the exact aspx page.

Let’s explore more. Go to the server side of the page and include the namespace Microsoft.AspNet.FriendlyUrls. You’ll get bunch of methods that will be very useful at certain times.

  • Request.GetFriendlyUrlSegments() – It returns a collections of string which represents the URL segments. So if I have a URL http://localhost:57353/First/Products/NewProduct and the page exists First.aspx then it returns.
    URLSegments
    So you can see above, there is two segments and one can iterate through it. These url segments can be used to pass the values to a page via URL instead of QueryString. It also looks pretty.
  • Request.GetFriendlyUrlFileVirtualPath() – It returns the File virtual path. For the URL, discussed in the above example it will show as
    File Virtual Path
    You can see it shows the Virtual path of the file.
  • Request.GetFriendlyUrlFileExtension() -It returns the extension of the file. For the above url, it will be shown as File Extension
    As you can see, the extension of the page. As now with friendly url, the page extension is not shown. You can get the extension by the above method.

There are other important methods/features available that can be used to generate the URL etc. I’ll discuss some of those here

An available class FriendlyURL provides few static functions/properties that is very useful. Let’s see

  • FriendlyUrl.Segments ; Returns the segments of of the current URL similar as returned by Request.GetFriendlyUrlSegments()
  • FriendlyUrl.Resolve : This can be used to resolve the FriendlyUrl
    • FriendlyUrl.Href – It takes few parameters virtual path and list of url segments and generate the friendly URL out of it. And it is very useful while generating the URL in data binding and several other places. We can write
      FriendlyUrl.Href("~/First", "Product", 1001);
      

      And what it will return
      FriendlyURLgeneration

Hope you must have liked this new coming feature of ASP.NET. This will will let you get rid of aspx extension at URL , Frankly speaking, during my earlier days of career, I used to see the extension to check if the website is developed in asp.net.

I find this feature as one of the most of the exciting features of ASP.NET. Hope you all enjoy it and also like the post.

Enjoy and Love ASP.NET. And A very Happy New Year to all.
Cheers.
Brij

How to access the input control’s data at Server side during Client Callback : A useful trick

Client callback is one way to update the webpage without performing the full page postback. It maintains the Client state while updating the Webpage. During Client callback the webpage runs through modifies version of Page Life Cycle.

The LifeCycle of a page in Client Call Back is  as

Page Lifecycle iin Callback

If you want to learn  more about Client Callback, click here.

But the main drawback of  Client Callback, The input data is not posted from Client to Server. Also,  It does not maintain the view state during partial postback as you can see the Page life cycle of Client callbak it is not saved or SaveViewState event is not fired.

Lets see it with an example.

I have created a simple form to collect some information of an person data. And it has a submit button, which initiates a Callback. As

 <table>
 <tr><td><asp:Label id="lblFName" runat="server" Text="First Name" /> </td>
 <td><asp:TextBox ID="tbFName" runat="server"></asp:TextBox></td></tr><tr>
 <td><asp:Label id="lblMName" runat="server" Text="Middile Name" /> </td>
 <td><asp:TextBox ID="tbMName" runat="server"></asp:TextBox></td></tr><tr>
 <td><asp:Label id="lblLName" runat="server" Text="Last Name" /></td><td><asp:TextBox ID="tbLName" runat="server"></asp:TextBox></td></tr><tr>
 <td><asp:Label id="lblAge" runat="server" Text="Age" /></td><td><asp:TextBox ID="tbAge" runat="server"></asp:TextBox></td></tr><tr>
 <td><asp:Label id="lblMailId" runat="server" Text="Email" /></td><td><asp:TextBox ID="tbEMail" runat="server"></asp:TextBox></td></tr><tr>
 <td><asp:Label id="lblSex" runat="server" Text="Sex" /></td><td><asp:TextBox ID="tbSex" runat="server"></asp:TextBox></td></tr><tr>
 <td colspan="2"><input id="btnCallBack" type="button" value="Submit" onclick="InitiateCallBack();"/></td></tr>
</table>

Server side code is as

public partial class Callback : System.Web.UI.Page,ICallbackEventHandler
{
    string result;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsCallback)
            return;
        //Creating a reference of Client side Method, that is called after callback on server
        String cbReference = Page.ClientScript.GetCallbackEventReference(this, "arg",
            "ReceiveServerData", "");

        //Putting the reference in the method that will initiate Callback
        String callbackScript = "function CallServer(arg, context) {" +
            cbReference + "; }";

        //Registering the method
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
            "CallServer", callbackScript, true);
    }
    public void RaiseCallbackEvent(String eventArgument)
    {
        string firstName = tbFName.Text;
        //Read other data as well

    }
    public string GetCallbackResult()
    {
        return result;
    }
}

And the client side method is

function InitiateCallBack() {
     //Intiate the callback
     CallServer("",'');
}

// Called after the server side processing is done
function ReceiveServerData(arg, context) {
    //arg: hold the result
    //Updating the UI
    document.getElementById('divCallbacl').innerHTML = arg;
}

After filling this form, I submitted it. Now if you try to access the entered using control’s property, you would not get it.

Let’s dig it more and check the form collection, whether the data is passed from Client to server or not

So as you can see that the data is not passed in form collection

But let’s put the following lines of code in java-script, just before initiating the call for Callback as

 function InitiateCallBack() {
	__theFormPostCollection.length = 0;
        __theFormPostData = "";
        WebForm_InitCallback();

        //Intiate the callback
        CallServer("",'');
}

Now let’s run the code and submit the form as earlier.

Now let’s check the form collection.

What a surprise, we got all the input data in form collection. That’s nice.

Now access the data using control’s property.

and you got it.

Now let’s try to see, what does the extra lines of code does

//This Clear the earlier the old data in form collection.
__theFormPostCollection.length = 0;
//It sets the forms data to empty
__theFormPostData = "";
//This method builds the body of the POST request when the page loads. The body of the page is a string 
//(that is __theFormPostData) filled with the contents 
of the view state and all of the input fields in the form.
WebForm_InitCallback();

But I would suggest to use these line at caution. Use only when you need to collect the update from Page during Callback. If you don’t need to get some data or it is in readonly page, don’t use it it introduce extra overhead to your page and costs at performance point of view.

Hope you  all have enjoyed the post.

Writing asynchronous HTTP Module in ASP.NET 4.5

Today again, I am going to discuss , one of the new features that got enhanced in ASP.NET 4.5. And It is Asynchronous HTTP Module . And it’s going to be very useful if used meticulously.

First Just to give a brief Idea, why Asynchronous HTTPModules are important ?

As we all know, web is stateless. A Web page is created from scratch every time whenever it is posted back to the server. In traditional web programming, all the information within the page and control gets wiped off on every postback. Every request in ASP.NET goes through a series of events.

Every request is served by am HTTP handler and it goes a series of HTTPModules (HTTPPipeline) which can be read, update the request. A lot of features of ASP.NET like Authentication, Authorization, Session etc are implemented as HTTP Module in ASP.NET. Let’s have a view on the Request Processing

ASP.NET Request Processing : HTTPPipeline and HTTPHandler


Now as you can see the request is assigned to a thread T1 from the available threads is thread pool. And the request is passed through several HTTPModules and finally served my HTTPHandler and response is send back with the same thread (T1).

During the entire processing, same thread is engaged in serving  the same request and cannot be used by any another request till request processing completes.  During the request processing if any HTTPModules depends on some entities like I/O based operations, web services, Databases queries etc then it takes long to complete which makes the thread busy for long which makes asp.net thread will not do anything during that duration and will be useless.  In this kind of scenarios the throughput goes down rapidly.

In the above scenario, synchronous HTTPModule can degrade the site performance a lot. So if we can make  HTTPModules as asynchronous  that can increase the through put a lot.  In asynchronous mode, ASP.NET thread get released as soon as the control get passed to another component/module, it does not wait. And the thread becomes available in thread pool and can be used to serve another request. When the component completes its assigned task then it got assigned to new ASP.NET thread which completes the request. The flow can be graphically presented as

Working of an asynchronous HTTPModule

In the above picture, An asp.net thread T1 is assigned from threadpool to server the request. When the control got passed to File System to log message, asp.net thread got  released and when essage logging got completed, control passed to asp.net and it is assigned to another thread say T2 from thread pool.
In .NET Framework 4.o, there was some major enhancement made for asynchronous programming model. Any asynchronous operation is represents a Task and it comes under the namespace System.Threading.Tasks.Task.

In .NET 4.5, there are some new operator and keyword introduced that makes the life easy for implement Asynchronous feature. One is async keyword and await operator.

These two enables us to write the asynchronous code is similar fashion as we write for synchronous mode.

And these features can be easily used while writing HTTPModules and HTTPHandlers. We’ll be using these enhancements in writing our custom asynchronous HTTPModule.

In my sample as depicted in image, I am creating a module that writes some log messages in a text file for every request made.

So to create a Custom HTTPModule, Create a class library project. And create a class  say named LogModule which implements IHttpModule. For this you need to add a reference of Assembly System.Web.

LogModule would contains the methods discussed below.

We need to implement two methods Init and Dispose that are part of IHTTPModule interface.

Here first , I have written an asynchronous method that actually reads the information from the request and writes in the log file asynchronously . For this I have used WriteAsync of FileStream

private async Task WriteLogmessages(object sender, EventArgs e)
{
	HttpApplication app = (HttpApplication)sender;
        DateTime time = DateTime.Now;

        string line = String.Format(
        "{0,10:d}    {1,11:T}    {2, 32}   {3}\r\n",
        time, time,
        app.Request.UserHostAddress,
        app.Request.Url);
        using (_file = new FileStream(
            HttpContext.Current.Server.MapPath(
              "~/App_Data/RequestLog.txt"),
            FileMode.OpenOrCreate, FileAccess.Write,
            FileShare.Write, 1024, true))
        {
            line = line + "  ," + threaddetails;
            byte[] output = Encoding.ASCII.GetBytes(line);

            _file.Seek(_position, SeekOrigin.Begin);
            _position += output.Length;
            await _file.WriteAsync(output, 0, output.Length);
        }

}

Here you can see the await key word, what it means..

As per msdn “An await expression does not block the thread on which it is executing. Instead, it causes the compiler to sign up the rest of the async method as a continuation on the awaited task. Control then returns to the caller of the async method. When the task completes, it invokes its continuation, and execution of the async method resumes where it left off.

await is used with some asynchronous method that returns task and is used suspend the execution of the method until the task completes and control is returned back to the caller to execute further. await should be used with the last expression of any code block.

And Init method would be like

public void Init(HttpApplication context)
{
        // It wraps the Task-based method
        EventHandlerTaskAsyncHelper asyncHelper =
           new EventHandlerTaskAsyncHelper(WriteLogmessages);

        //asyncHelper's BeginEventHandler and EndEventHandler eventhandler that is used
        //as Begin and End methods for Asynchronous HTTP modules
        context.AddOnPostAuthorizeRequestAsync(
        asyncHelper.BeginEventHandler, asyncHelper.EndEventHandler);

}

So apart from above these methods, we need to implement the dispose method.

Now compile your class library and use the reference in your ASP.NET website . Now as you must be knowing that we need to need to add the entry in the config file. So it’ll be as

<system.webServer>
<modules>
<add name="MyCustomHTTPModule" type="MyCustomHTTPModule.LogModule, MyCustomHTTPModule"/>
</modules>
</system.webServer>

Now when you run your application, you will see the logs are created in a text file in App_Data folder as mentioned path in the code.

Hope you all have liked this new feature.

Limiting the accessibility- Another way of Friend Assemblies

In my last post, I discussed, how to access internal class of one assembly in another assembly and that is easily achieved with the help of a C# feature called Friend Assemblies. It allows us to call the internal methods of another assembly. It is very much required at several occasions like the one I discussed in my last post, Unit Testing. It is often required to test the internal classes of the assembly in another project of Unit testing and It can be done easily via Friend Assembly.

To see my last post Please click here How to access internal class of one assembly to other assembly

But in some other scenarios Friend assemblies solution may not work. Like if you have two assemblies and one assembly accesses other assembly using Friend assembly. It’ll be fine as long as both assembly are compatible and shipped at same point of time. And if it does not happen on regular basis or in every release/update of assembly this may be hazardous.

To avoid it, we should implement it in another way. Here we declare the method as public but will limit to its accessibility to some specific assembly. It can be achieved by using LinkCommand with StrongNameIdentityPermission.

Continue reading

Unobtrusive Validation with ASP.NET 4.5

ASP.NET 4.5 has been improved and latest version ASP.NET. It includes an array of new and modified features. Today we’ll discuss one new feature Unobtrusive Validation that is introduced with ASP.NET 4.5 .

So what is Unobtrusive Validation?

In a normal validation scenario,when we use a validator to validate any any control and use Client side validation, some JavaScript is generated and rendered as HTML. Also some supportive JavaScript files is also get loaded by the browser for the validation.

Now with feature Unobtrusive Validation, inline JavaScript is not generated and rendered to handle the Client Side validation. Instead of this it uses HTML5 data-* attributes for all these validation.

Continue reading

Exploring Nullable types : Part 2

This is second and last part of the post on Nullable type series. You can view the first part from here

Exploring Nullable types : Part 1

In this series, I will talking certain rules that we need to take care while using Nullable type. I will be taking scenario wise.

First scenario:

Int? a=8;
object o = a;
long d = (long)c;

It will be compiled successfully but will throw and Invalid Cast Exception. Means, you cannot cast it to any other type except the underlying type which is here int although  int type can be hold by long.

Continue reading