Thursday, February 27, 2014

Bool Methe Nazar Nashili he

بول میٹھے نظر نشیلی ہے 
میں نے دو میکدوں سے پی لی ہے 
میں نے تو تھوڑی سی ڈالی تھی مگر  
شیخ نے بے حساب پی لی ہے 

Saturday, February 22, 2014

Do Ishq by Faiz Ahmad Faiz

پہلا عشق 

تازہ ہیں ابھی یاد میں اے ساقی گلفام
وہ عکس رخ یار سے لہکے ہوئے ایام
وہ پھول سی کھلتی ہوئی دیدار کی ساعت
وہ دل سا دھڑکتا ھوا امید کا ہنگام

امید کہ لو جآگا غم دل کا نصیبا
لو شوق کی ترسی ہوئی شب ھو گئی آخر
لو ڈوب گئے درد کے بے خواب ستارے
اب چمکے گا بے صبر نگاھوں کا مقدر

اس بام سے نکلے گا تیرے حسن کا خورشید
اس کنج سے پھوٹے گی کرن رنگ حنا کی
اس در سے بہے گا تیری رفتار کا سیماب
اس رہ پے پھولے گی شفق تیری قبا کی

پھر دیکھے ہیں وہ ہجر کے تپتے ہوئے دن بھی
جب فکر دل و جاں میں فغاں بھول گئی ہے
ہر شب وہ سیہ بھوجھ کہ دل بیٹھ گیا ہے
ہر صبح کی لو تیر سی سینے میں لگی ہے

تنہائی میں کیا کیا نہ تجھے یاد کیا ہے
کیا کیا نہ دل زار نے ڈھونڈھی ہیں پناہیں
آنکھوں سے لگایا ہے کبھی دست صبا کو
ڈالی ہیں کبھی گردن مہتاب میں بانہیں

دوسرا عشق 

چاہا ہےاسی رنگ سے  لیلہ وطن کو
تڑپا ہے اسی طور سے  دل اس کی لگن میں
ڈھونڈھی ہے یونہی شوق نے آسائش منزل
رخسار کے خم میں کبھی کاکل کی شکن میں 

اس جان جہاں کو بھی یونہی قلب و نظر نے
ہنس ہنس کے صدا دی کبھی رو رو کے پکارا
پورے کیے سب حرف تمنا کے تقاضے
ہر درد کو اجیالا ہر اک غم کو سنوارا

واپس نہیں  پھیرا کوئی فرمان  جنوں کا
تنہا نہیں  لوٹی کبھی  آواز جرس کی
خیریت جاں ،راحت تن، صحت داماں
سب بھول گئیں  مصلحتیں اہل ہوس کی

اس رہ میں سب پے جو گزرتی ہے وہ گزری
تنہا پس زنداں کبھی رسوا سر بازار
گرجے ہیں بہت شیخ سر گوشہ منبر
کڑکے ہیں بہت اہل حکم بر سر دربار

چھوڑا نہیں غیروں نے کوئی ناوک دشنام
چھوٹی نہیں اپنوں سے کوئی طرز ملامت
اس عشق نہ اس عشق پے نادم ہے مگر دل
ہر داغ ہے اس دل میں بجز داغ ندامت 

Saturday, February 15, 2014

How Session is Maintained in .NET Using Cookies

Some time ago, I blogged on how cookies can be used to capture user's preferences. Preferences may apply to a particular page or entire website. In this article we will see how uses cookie to maintain session with a particular browser.
Let's create an empty application in visual studio 2012 as shown in the figure below

Figure 1: Creating Empty Asp.Net Application
We created empty application because we want to avoid noise. we don't need user management, login, logout or register functionality. we will just put a random thing like your name in the session variable and then observe how it works in conjunction with cookies.
Let's now add a web form in our empty web application as shown in Figure 2.

Figure 2: Add Default.aspx to Empty Web Application
On the web form, we just added one asp textbox and one asp button. On top of the page we have a conditional paragraph that will display the name of the user if it is present in the session collection. Below is the code for conditional printing of name if it is stored in session.
<%if(Session["name"] != null)

          { %>

Your name is <%=Session["name"].ToString() %>

        <% }%>
Below that conditional printing are our textbox and button that asks the user for his/her name. Once user enters his name in the textbox and presses enter this value will be saved in session collection with key "name". Here is the code for storing name to the session
protected void Button1_Click(object sender, EventArgs e)
          Session["name"] = TextBox1.Text;
After that user will see his name on the top of the page every time he refreshes the page without restarting the browser. If he restarts the browser or opens the same page on a different browser the name of the user will not be displayed unless he saves his name to the session using textbox and button controls.
Let's see all this in action. When we visit the page for first time, there is no name on the page. There is only one textbox and a save button as shown in figure 3.

Figure 3: Initial view of the page
Once, I enter my name in the textbox and press save, it will be saved to the session and I would see my name on every subsequent refresh unless I close the browser (closing browser ends the session b/w web server and browser). Figrure 4: shows the view of the page after entering name and pressing the save button.

Figure 4: After Entering name
Now, if we open the same page in other browser we should not be able to see the name on top unless we save it for the session of that particular browser. But, how this session things works. I have two browser's on the same machine. If session is established with one browser, what tells the web server that request from second browser should not have access to the session variables of the first browser and vice versa. 
The answer is cookie. When a user issues first request to any site, it writes a cookie to the user's browser named "ASP.NET_SessionId". This cookie tells the web server, which browser (or client) it is interacting with. Let's have a look at cookie and its value in one of my browser

Figure 5: ASP.NET_SessionId Cookie in my browser
The content field in figure 5 shows the value of the cookie. If I restart my browser the new value will be assigned by web server to the SessionId cookie and we will have no access to the session values that we stored in the earlier session. 
This also means that if we can somehow send this value of sesssioId along with our request from some other client (like fiddler) we should be able to access the session values that were set here. So, let's start fiddler and issue the request.

Figure 7: Fiddler Request with Cookie copied from browser
You can see that I just sent the request to default.aspx page with SessionId cookie with its value copied from Firefox. In Firefox, I had saved my name in the session list. When the same sessionId value traveled with request from fiddler, here comes the response. 

Figure 8: Fiddler Response
You can see that response also contained the name string that had been set using Firefox. Only reason, we were able to see it here is because we copied the value of sessionId cookie from Firefox to fiddler. 

In next article, we will take a look at how ASP.NET authentication cookie works to remember the user on the website.

Sunday, July 3, 2011

AjaxOnly Attribute: ActionFilter vs ActionMethodSelector

Today when finding answer to this question, i came across Mike's blog post. In this post Mike inherited the filter from ActionFilterAttribute and checked request status in onActionExecuting method.
I was about to paste the link then i decided to investigate the mechanism of other attributes like AcceptVerb, HttpPost etc. It turned out that they inherit from ActionMethodSelectorAttribute which is an abstarct class and implement its abtsract method IsValidForRequest

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public sealed class HttpPostAttribute : ActionMethodSelectorAttribute {

        private static readonly AcceptVerbsAttribute _innerAttribute = new AcceptVerbsAttribute(HttpVerbs.Post);

        public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo) {
            return _innerAttribute.IsValidForRequest(controllerContext, methodInfo);
Listing 1: Mvc's HttpPostAttribute
After this finding i decided to make a new filter and inherit it from ActionMethodSelectorAttribute so i could implement IsValidForRequest method and it all ended up like
public class AjaxOnlyAttribute : ActionMethodSelectorAttribute 
        public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo)
            return controllerContext.RequestContext.HttpContext.Request.IsAjaxRequest();
Listing 2: AjaxOnlyAttribute
The end result of Mike's AjaxOnlyAttribute and this one is same but what is the result of using either approach in mvc request pipeline. An excerpt  from InvokeAction method of ControllerActionInvoker class could help us here.
ControllerDescriptor controllerDescriptor = GetControllerDescriptor(controllerContext);
            ActionDescriptor actionDescriptor = FindAction(controllerContext, controllerDescriptor, actionName);
            if (actionDescriptor != null) {
                FilterInfo filterInfo = GetFilters(controllerContext, actionDescriptor);

                try {
                    AuthorizationContext authContext = InvokeAuthorizationFilters(controllerContext, filterInfo.AuthorizationFilters, actionDescriptor);
                    if (authContext.Result != null) {
                        // the auth filter signaled that we should let it short-circuit the request
                        InvokeActionResult(controllerContext, authContext.Result);
                    else {
                        if (controllerContext.Controller.ValidateRequest) {

                        IDictionary<string, object> parameters = GetParameterValues(controllerContext, actionDescriptor);
                        ActionExecutedContext postActionContext = InvokeActionMethodWithFilters(controllerContext, filterInfo.ActionFilters, actionDescriptor, parameters);
                        InvokeActionResultWithFilters(controllerContext, filterInfo.ResultFilters, postActionContext.Result);
Listing 3: Excerpt from InvokeAction method
on line 2 of Listing 3 FindAction method of ControllerActionInvoker class is called. This method through series of method calls, calls FindAction method of ActionMethodSelector class. FindAction method in turn runs all the ActionMethodSelecorAttributes on the action method to find out if method is valid for this request.  
It necessarily means that if IsValidForRequest method returns false for any action method it will not be processed further in the request and none of the filters applied to this action method will be executed. 
If AjaxOnly (or any other filter for that matter) is created by inheriting from ActionFilter, AuthorizeFilter, ExceptionFilter or ResultFilter attributes it will be executed later in the request pipeline. This can be observed from code in Listing 3. Information of these filters is acquired on line 4 and until this point all ActionMethodSelector attributes would be executed. 
In the end it is probably safe to state that if AjaxOnlyAttribute inherits from ActionMethodSelectorAttribute mvc will behave as if action method does not exist in case of non-ajax calls. Conversely, if AjaxOnly attribute is implemented by inheriting from ActionFilterAttribute mvc will not allow the action method to execute in case of non-ajax calls. Apparently, there seems to be no consequences of using either approach but i personally feel that this logic belongs to ActionMethodSelectorAttribute

Friday, July 1, 2011

Server side Validation with mvc ajax and Jquery

These days ajax is extensively used to provide good user experience, especially when there is small amount of data exchange. In mvc when we post a form using ajax we normally put validation at two places
  1. Client side (for user experience)
  2. Server side (for validation)
Client validation servers the purpose well in most of the cases but its not reliable validation and one can not trust the input coming from the end user that can potentially be tempered by end user.
Suppose we have a small comment form with three input fields Name, Email and CommentText and we want to post it using ajax to mvc controller action. Furthermore, we have two divs on the page with ids comments and commentform respectively. When this form is post using ajax there are two possibilities.
  • Form is valid: in this case save the comment and return the same comment to client so it could be appended to comments div
  • Form is Invalid: in this case return the form with populated errors and put this response in commentform div

To implement the above mentioned functionality let's have a look at jquery ajax function
<script type="text/javascript">
    $('form').live('submit', function () {
            url: this.action,
            type: "post",
            data: $(this).serialize(),
            success: function (data) {
        return false;
Listing 1: Jquery Ajax function
Below is controller action method that will handle the posted form data
        public ActionResult comment(Comment _Comment) 
            if (!ModelState.IsValid)
                PartialView("RenderForm", _Comment);
            var comments = Session[_CommentKey] as List<Comment>;
            Session[_CommentKey] = comments;
            return PartialView("DisplayComment", _Comment);
Listing 2: Controller Action Method
Ajax function in listing 1 presumes that we always have success in controller action method and it will always receive comment that will be appended to the comments div. But, what if modelstate is not valid in controller action and returned response is comment form populated with posted values and error messages. In that case we have no way of knowing which div to populate (append to comments div or repopulate commentform div)
One way of addressing this issue is to create a json object with isSuccess flag set to true or false depending upon the value of modelstate in the controller and second property of this json object will contain the actual response text. Please read stackoverflow question for details. Another way is to set response code other than 200 in controller action method when modelstate is invalid. This will allow us to receive the response text in error callback rather than success callback. Listing 3 and 4 shows revised jquery ajax function and controller action method.
<script type="text/javascript">
    $('form').live('submit', function () {
            url: this.action,
            type: "post",
            data: $(this).serialize(),
            success: function (data) {
            error: function (xhr, status) {
        return false;
Listing 3: Jquery ajax function with error callback
        public ActionResult comment(Comment _Comment) 
            if (!ModelState.IsValid)
                Response.StatusCode = 500;
                return PartialView("RenderForm", _Comment);
            var comments = Session[_CommentKey] as List<Comment>;
            Session[_CommentKey] = comments;
            return PartialView("DisplayComment", _Comment);
Listing 4: Revised ActionMethod
This approach seems cleaner and more elegant to me than creating and sending the json. However, other thoughts, ideas are very much appreciated. 

Thursday, June 30, 2011

Master detail form in aspnet mvc-3 - III - Remove Duplicate IDs

This post is to address a mistake in previous post. In previous post, when adding new rows for detail portion on client side, duplicate id's were generated.

<select name="OrderLines[9ecd00fe-b5cd-420a-9140-f5c35fad9f3c].ProductID" class="input-validation-error" id="OrderLines___randomNumber___ProductID" data-val-required="The ProductID field is required." data-val-number="The field ProductID must be a number." data-val="true">

Listing 1: Select List for Detail Portion
Listing 1 shows that randomNumber is not replaced by generated random number in id attribute of select list which is generated for detail portion of master detail form so it will result in same id for productID select list in each generated row. Let's have a look at jquery template that is rendered when we call RenderClientTemplate method inside jquery template
<SCRIPT id=OrderLine type=text/x-jQuery-tmpl jQuery15103699563721650198="3">
    <div class="editorRow">
    <input type="hidden" name="OrderLines.index" autocomplete="off" value="${randomNumber}" />

Item: <select data-val="true" data-val-number="The field ProductID must be a number." data-val-required="The ProductID field is required." id="OrderLines___randomNumber___ProductID" name="OrderLines[${randomNumber}].ProductID"><option value="">--Select Product--</option>
<option value="1">Printer</option>
<option value="2">Camera</option>
<option value="3">Monitor</option>

        Quantity: <input data-val="true" data-val-number="The field Quantity must be a number." data-val-required="The Quantity field is required." id="OrderLines___randomNumber___Quantity" name="OrderLines[${randomNumber}].Quantity" type="text" value="0" /> 
        <a href="#" class="deleteRow">delete</a>
        <span class="field-validation-valid" data-valmsg-for="OrderLines[${randomNumber}].ProductID" data-valmsg-replace="true"></span>
        <span class="field-validation-valid" data-valmsg-for="OrderLines[${randomNumber}].Quantity" data-valmsg-replace="true"></span>

Listing 2: Template for Detail Portion
in Listing 2 we can see that "randomNumber" is enclosed in ${} symbol in name attribute thus allowing us to use it as jquery template variable and provide this value when materializing the template into html. But, when we have a look at id attribute, "randomNumber" is output in the template as it is. So, it can not be used as template variable and it produces same ids for every field in each detail row when added on client side. For this reason, xhalent's extension method did not work properly. To address this issue, i wrote a helper method to keep id's unique across all rows of detail method
public static string IDFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expr) 
            string prefix = helper.ViewData.TemplateInfo.HtmlFieldPrefix;
            string name = ExpressionHelper.GetExpressionText(expr);
            return (prefix + "__" + name).Replace("[", "__").Replace("]", "__");
Listing 3: Helper Method for ID generation
helper method is quite simple. It is just replacing "[" and "]" symbols with couple of underscores each. The main purpose of this method is to output "randomNumber" as ${randomNumber} so it could be used when materializing template. There are also some changes in orderLine.asx partial view and Product.ascx editor template
Item: <%= Html.EditorFor(x => x.ProductID, new { id = Html.IDFor(x => x.ProductID) })%> 
        Quantity: <%= Html.TextBoxFor(x => x.Quantity, new { size = 4, id = Html.IDFor(x=>x.Quantity) })%> 
        <a href="#" class="deleteRow">delete</a>
        <%= Html.ValidationMessageFor(x => x.ProductID) %>
        <%= Html.ValidationMessageFor(x => x.Quantity) %>
Listing 4: OrderLine.ascx Partial View
In partial view, i am explicitly setting ID attribute of html elements by calling Html.IDFor helper method for Quantity field and for ProductID field this value is passed through ViewData which is used in Product.ascx Editor template
<%:Html.DropDownList("", new SelectList((List<MasterDetail.Models.Product>)ViewBag.Products, "ProductID", "ProductName", Model), "--Select Product--", new { id = ViewData["id"] })%>
Listing 5: Product Editor Template
This setup insures that unique ids will be generated for each element of detail part of the form thus avoiding any potential DOM malfunctioning. 

Sunday, May 22, 2011

Master detail form in aspnet mvc-3 - II

In my previous post i discussed how we can add and delete rows in detail portion of master detail form without having to go to server side when new rows are inserted. In this post i will discuss adding new rows on client side for detail portion of the form, using select lists ( or  other editor elements) to insert a new row and client validate dynamically added rows. For this purpose, i will be using unobtrusive js that comes with mvc-3 and jquery templating engine. I will not reproduce the code from last entry if there is no change so, please go through the post if you haven't already done it.
So, first change is in our OrderLine view model where we want ProductID quantity to be selected through a select list. For this, its been decorated with UIHint attribute with name of the corresponding editor template.
public class OrderLine
     public int ProductID { get; set; }
     public int Quantity { get; set; }

Listing 1: OrderLine ViewModel
To make Steve's collection helper work with jquery templating engine , i have  made few changes in BeginCollectionItem method
public static IDisposable BeginCollectionItem(this HtmlHelper html, string collectionName, bool isTemplate = false)
    if (isTemplate)
        var randomNumber = "${randomNumber}";
        html.ViewContext.Writer.WriteLine(string.Format("<input type=\"hidden\" name=\"{0}.index\" autocomplete=\"off\" value=\"{1}\" />", collectionName, randomNumber));
        return BeginHtmlFieldPrefixScope(html, string.Format("{0}[{1}]", collectionName, randomNumber));
        var idsToReuse = GetIdsToReuse(html.ViewContext.HttpContext, collectionName);
        string itemIndex = idsToReuse.Count > 0 ? idsToReuse.Dequeue() : Guid.NewGuid().ToString();

        // autocomplete="off" is needed to work around a very annoying Chrome behaviour whereby it reuses old values after the user clicks "Back", which causes the xyz.index and xyz[...] values to get out of sync.
        html.ViewContext.Writer.WriteLine(string.Format("<input type=\"hidden\" name=\"{0}.index\" autocomplete=\"off\" value=\"{1}\" />", collectionName, html.Encode(itemIndex)));

        return BeginHtmlFieldPrefixScope(html, string.Format("{0}[{1}]", collectionName, itemIndex));
Listing 2: Collection Helper
one optional parameter "isTemplate" is added to method's parameter list with default value set to false so it does not affect the code already using this method. when isTemplate is true ${randomNumber} string is used as index of collection item in place of GUID and will produce the output like
<input type= "text" name = "OrderLines[${randomNumber}]" id = "some_Generated_ID" data-*/>
it will help jquery insert the random number value on client side when new row is added. Please visit this article to learn how jquery templating engine works. If value of isTemplate is false or unspecified the ids are generated as usual.
Next, there is only one change in index ActionResult that renders the form
public ActionResult Index()
     ViewBag.Products = Session[_productKey] as List<Product>;
     Order _order = new Order { CustomerID = 1, OrderDate = DateTime.Now, OrderID = 1 };
     _order.OrderLines = new List<OrderLine> { new OrderLine { ProductID = 1, Quantity = 3 }, new OrderLine { ProductID = 2, Quantity = 56 } };
     _order.Customers = Session[_customerKey] as List<Customer>; 
     return View(_order);
Listing 3: Index ActionResult (HttpGet)
in this method ViewBag.Products property is set to list of Products. This will be used by Product Editor templage that we annotated ProductID property with. Some changes have also been made in index view and OrderLine partial view.
<%Html.BeginForm(); %>
    <div id="orderMaster">
            <%:Html.LabelFor(x =>x.OrderID)%>
            <%:Html.LabelFor(x =>x.CustomerID)%>
            <%:Html.DropDownListFor(x => x.CustomerID, new SelectList(Model.Customers, "CustomerID", "CustomerName"), "Select Customer", new { @class = "xyz" })%>
            <%:Html.LabelFor(x =>x.OrderDate)%>
    <div id="orderDetail">
        <%foreach (var x in Model.OrderLines)
             <div class="editorRow">
               <%using(Html.BeginCollectionItem("OrderLines")) {
        <%} %>
    <a href="#" id="add">Add Another</a>
    <input type="submit" value="save" />
    <%Html.EndForm(); %>
    <script id="OrderLine" type="text/x-jQuery-tmpl">
    <div class="editorRow">
    <%using(Html.BeginCollectionItem("OrderLines",true)) { %>
        <%Html.RenderClientTemplate(typeof(MasterDetail.Models.OrderLine), "OrderLine"); %>
        <%} %>
Listing 4: Index View
First change in index view is at line 19 and 20. I have moved editor row div and BeginCollectionItem method call from partial view to the index view so we can set the value of isTemplate parameter of the method. At line 30 jquery client template that will be used to add rows dynamically on the detail portion of the form. Inside this template same BeginCollectionItem is called but this time with isTemplate value set to true. This will enable us to set values of index on client side. On line 33 RenderClientTemplate helper is called which produces all the inputs (selectlists etc.) required to add an OrderLine type object. Listing 5 shows the code of  RenderClientTemplate helper
public static void RenderClientTemplate(this HtmlHelper helper, Type _type, string _partialViewName) 
    object model = Activator.CreateInstance(_type);
    helper.RenderPartial(_partialViewName, model);
Listing 5: Client Template Helper
ClientTemplateHelper accepts two inputs (except html helper itself): first is the type of object that we want to render a template for and second is partial view that will be used to render the template. Inside the helper model object is created using reflection and passed to the partial view to render. When this method is called from index view it will render the same partial view that was used for the OrderLine objects present in the Order object. The only difference this time is that the value of index this time will be set to ${randomNumber} allowing us to use this template multiple times on client side.
There are of course some changes in click event handler of anchor tag used to render the new row.
$('#add').live('click', function () {
    obj = { randomNumber: GetRandomGUI() }
    return false;
Listing 6: Adding New Row in Javascript
Just line 2 creates an object with property randomNumber that is acquired by a javascript function. Line 3 is generating actual html content by providing the value of obj and appending it to the end of orderDetail div element. Line 4 calls a function that parses newly added html to turn on client validation for them. Listing 7 shows pareseDynamicContent function

(function ($) {
    $.validator.unobtrusive.parseDynamicContent = function (selector) {
        //use the normal unobstrusive.parse method

        $(selector).find('*[data-val = true]').each(function(){

        //get the relevant form
        var form = $(selector).first().closest('form');
        //get the collections of unobstrusive validators, and jquery validators
        //and compare the two
        var unobtrusiveValidation ='unobtrusiveValidation');
        var validator = form.validate();
        $.each(unobtrusiveValidation.options.rules, function (elname, elrules) {
            if (validator.settings.rules[elname] == undefined) {
                var args = {};
                $.extend(args, elrules);
                args.messages = unobtrusiveValidation.options.messages[elname];
                $('[name="' + elname + '"]').rules("add", args);
            } else {
                $.each(elrules, function (rulename, data) {
                    rulename = rulename;
                    data = data;
                    if (validator.settings.rules[elname][rulename] == undefined) {
                        var args = {};
                        args[rulename] = data;
                        args.messages = unobtrusiveValidation.options.messages[elname][rulename];
                        $('[name="' + elname + '"]').rules("add", args);
Listing 7: JS Function for Switching on Client Validation
This function is taken from xhalent's blog and there you can find more explanation on switching on client validation on dynamically added fields. There is one change that has been made in his function. Line 5 was replaced by Line 6,7 and 8.
Note: I have found conflicting material on turning on client side validation for newly added fields. Brad Wilson says that calling Jquery.validator.unobtrusive.parse() will turn on client validation on newly added html but it did not work for me and i had to use xhalent's function  but it didn't work for me either until i changed line 5 with 6, 7 and 8 in listing 7
Pleas find Demo Code Here
Note: Duplicate ids are generated for similar elements of each row in detail portion of the form resulting in some DOM malfunctions. To address the issue pleas follow this link