Mehfuz's WebLog

Live crazy, think different!

Sponsors

News

Passionate about cutting edge technologies and facinated by the modern web and phone revolution.Currently working at Telerik Corporation, the leading .net component vendor.
Follow me


Articles


Projects

October 2008 - Posts

I am here at PDC 2008

 dev

Finally, PDC 2008 is going to roll on this Monday, when Ray Ozzie will start the show off with his keynote. This year there will be quite a new things to be announced during the show. There will be first time preview of Windows 7 and Microsoft's new modeling platform Oslo. There will be C# 4.0 talks , Asp.net MVC and more. All these will be covered in couple of keynotes and a load of sessions during the PDC week. Also, there will be some book singing events where Anders Hejlsberg will be signing copies of the C# Programming Language. I am a part of the Telerik PDC crew and it is all fun starting from setting up booth (you must try it to feel the joy :-), team work and IKEA stuffs.) with the team and meeting cool dev's. As many of you know that the soft copy of the early build of windows 7 will be delivered though a 160GB mobile hard-rive  which is really cool. Finally, PDC is never been fun without Scott Guthrie, Scott Hanselman, Don Box, Chris Anderson with their cool keynotes and sessions.

This year Microsoft will be focusing on cloud computing platforms (Dublin and .net services), which is growing popular these days with plenty of API's flying around. I will keep you guys what I learn from the event and about cloud computing.

Some of my favorite sessions follows

Day 1

Some of my Key interest sessions follows

TL16 The Future of C# by Anders Hejlsberg

TL40 "Dublin" and .NET Services: Extending On-Premises Applications to the Cloud

PC20 ASP.NET 4.0 Roadmap By Scott Hunter

PC21 ASP.NET MVC: A New Framework for Building Web Applications by Phill Haack

PC58 Framework Design Guidelines by Brad Adams

TL49 Microsoft .NET Framework: Overview and Applications for Babies by Scott Hanselman

Day 2

TL27 "Oslo": The Language by Don Box

PC31 ASP.NET and JQuery by Stephen Walther

Day 3

BB24 SQL Server 2008: Deep Dive into Spatial Data by Isaac Kunen

TL18 "Oslo": Customizing and Extending the Visual Design Experience by Don Box

PC54 Mono and .NET by Miguel de Icaza

Day 4

TL32 Microsoft Visual Studio: Customizing and Extending the Development Environment

TL31 "Oslo": Building Textual DSLs by Chris Anderson

 

These are only few. More I will decide on demand :-)  Apart from PDC I am really enjoying my stay at LA, its a nice place properly choreographed and I like it all. If you are coming to PDC want to say Hi, or you want me to do that as well. I will be around at the Telerik Booth and of course in the sessions and keynote halls. By the way, today I found that there will be Microsoft Surface booth. Therefore, it will be cool to play around them as well.

If you are not in PDC , don't worry  you can enjoy all of it sitting in-front of your laptop. You can download keynotes and sessions from PDC site. That's all I can remember now and will keep you posted about my experience.

Posted: Oct 26 2008, 04:50 PM by mehfuzh | with no comments |
Filed under:
LinqExtender 1.4.2 - Supporting Complex type arguments

I just made a quick update to the existing release of LinqExtender. I recently found a bug while building a feature for FlickrXplorer is that if you use constant type query with orderby clause it does pretty well, but it simply does not do well with complex ones. I have used the same logic that I have used for where clause arguments. Also, it will be out of the scope for this post to drill it down all the LinqExtender logic fort hat. But I would put a brief overview on it that can help you out while building your own IQueryable implementation.

If I didn't mentioned in my earlier posts. LinqExtender supports two way orderby in your implemented provider

First by the object property  while looks like

var query =  from q in bookContext
             orderby q.LastUpdated descending
             select q;

In this case, Bucket.OrderByClause will be containing the detail of LastUpdated property and its relation to sorting.

Now, it is also possible to do orderby in the following way

var query =  from q in bookContext
             orderby "LastUpdated" descending
             select q;

But what about the query with member access. Let's assume that there is a Instance class and inside there is one method which has a local variable that is a Enum and that changes by user input. Finally, it is passed in a LINQ query.

PhotoOrder order = PhotoOrder.Interestingness;
// more code to change it on user provided order by

var query = (from ph in context.Photos
             where ph.PhotoSize == PhotoSize.Square
                   && ph.SearchMode == SearchMode.FreeText
                   && ph.FilterMode == FilterMode.Safe
                   && ph.Extras == (ExtrasOption.Views | ExtrasOption.Tags)
                   && ph.SearchText == key
             orderby order descending
             select ph).Take(pageLen).Skip(index);

Now, how to parse this or if any sorts of member access is used ? As we know that LINQ expressions are first translated to MethodCallExpression.In case for  orderby the MethodCallExpression.Method.Name name equals "OrderBy". Once you found a way to get around it. You can then easily build up an extension method or in my case, I have created an extension method that dynamically gets the value out of the method call argruments.

public static object GetValueFromExpression(this Expression expression)
{
    object value = null;

    UnaryExpression unaryExpression = GetUnaryExpressionFromMethodCall(expression);
    LambdaExpression lambdaExpression = unaryExpression.Operand as LambdaExpression;
    // get the value by dynamic invocation, used for getting value for MemberType expression.
    value = Expression.Lambda(lambdaExpression.Body).Compile().DynamicInvoke();
    return value;
}

As with the hierarchy expression starts with Unary then goes to Lamda and further down. Once we have the lamda expresion , we can then compile it to method call Delegate , which gives  a nice method named DynamicInvoke that brings out the result. In the code, one more thing that I have done is the extraction of the MethodCallExpression out of UnaryExpression which brings the following code block

public static UnaryExpression GetUnaryExpressionFromMethodCall(Expression expression)
{
    MethodCallExpression mCall = expression as MethodCallExpression;
    UnaryExpression uExp = null;

    foreach (Expression exp in mCall.Arguments)
    {
        if (exp is UnaryExpression)
        {
            uExp = exp as UnaryExpression;
            break;
        }
        else if (exp is MethodCallExpression)
        {
            uExp = GetUnaryExpressionFromMethodCall(exp);
            break;
        }
    }
    return uExp;
}

This simple code block reveals one more thing that each method call can be nested and as such for nested case we need to go to the further leaf and fetch the value.So far, this is really useful to me for parsing query expressions with complex member access arguments. But it also gives a way, if you are planning your own IQueryable implementation.

Moving forward, while working with LinqExtender toolkit, if you like attribute oriented programming, you need to specify and get attributes on objects despite the one defined by the toolkit. That follows

  1. LinqVisibleAttrible (Marks a property to be processed by LinqExtender when used in a query)
  2. OriginalFieldNameAttribute (Overrides the property name, if data store has a different name)
  3. OriginalEnitityNameAttribute (Overrides the class name)
  4. UniqueIdentifierAttribtue (Marks a property Unique which is useful for updating object, please see my earlier post).

So what if you want to have your own and get it in the AddItem, UpdateItem, RemoveItem or Process overrides ? You can do it easily by the following statement.

// let's say during the add i want to track MyAttribute
protected override bool AddItem(Bucket bucket)
{
    MyAttribute attribute = (MyAttribute)item.FindAttribute(typeof(MyAttribute)); 
}

This is all for now. Before I end, I would like to bring down a brief history how I started LinqExtender. Now, there are pretty good amount of LINQ providers out there and still growing and my motto is to help them get started with no pain.When I stared LinqExtender it came with a handful of features which has grown efficient day by day with the help of community. I build everything that people requests me and sounds logical to roadmap of the project. In the end , the basic concept remains the same from day one which is, "build more LINQ providers with less effort and it takes the most complexity on its own without scarifying features (Ex. projection, complex query parsing, etc)". It is basically suited for cloud APIS  like one I have built named Athena (Formarly:LINQ.Flickr) but can be used with ORMs and core data objects to provide custom LINQ support over legacy interface.

Hope that helps

kick it on DotNetKicks.com

Posted: Oct 25 2008, 07:24 PM by mehfuzh | with 1 comment(s) |
Filed under: , ,
Using jQuery to do Ajax Form posts in Asp.net MVC

It is now official from a post by great Scott Guthrie that jQuery is bundled with Asp.net MVC Beta. jQuery is a tiny 15K JavaScript library that contains features from UI tweaks, DOM manipulation to full Ajax control. In my last post, I have shown how to get going with Ajax.Form using Microsoft MVC Ajax library. In this post, I will show how to do Ajax form posts with jQuery but in Ajax.Form style.

To mark the marriage of jQuery, I have released a new version of FlickrXplorer that uses nothing but jQuery on the client. More info on the release can be found at the following URL.

http://www.codeplex.com/FlickrXplorer/Release/ProjectReleases.aspx?ReleaseId=18041

Ajax.Form gives a nice way of adding ajax features with no more tears. Just add a using block with necessary html controls and a submit button, everything else is taken care of on behalf. Being inspired by it, in FlickrXplorer project I have created a Html.JForm that works in a similar way using jQuery library.

To see how it works, it is to mention that Ajax.Form basically creates a html form with onsubmit hook where it injects few JavaScript from Microsoft MVC Ajax Library. To replicate, le's say to do an image list  paging with Html.JForm that gets the data, shows the loader and updates the container

image 

I first added the MVC JavaScript (Ex. Inside default.master) file with ajax stuffs that works with Html.JForm  and referenced the jQuery library.

<script type="text/javascript" src="<%= Page.ResolveClientUrl("~/Content/jquery-1.2.6.min.js") %>" ></script> 
<script src="<%= Page.ResolveClientUrl("~/Content/mvc-jquery.js") %>" type="text/javascript"></script>

Finally, In the actual ascx/aspx file, I wrote the following

 <% 
    using (Html.JForm(VirtualPathUtility.AppendTrailingSlash(HttpContext.Current.Request.Path), "POST", new JOptions
    { 
        TargetPanelId = "imgListContainer", 
        WaitPanelId = "imgListWait"
    }))
                        
    { %>

...
...
<% 
} %>

That's it , also it is to include that this will work with controller actions that return either ContentResult or ActionResult.

Basically, the signature of Html.JForm looks like

Overload 1 : Html.JForm(actionurl, methodType, JOptions);
Html.JForm("/controller/action", "GET/POST",
new JOptions 
{ 
    TargetPanelId = "update containter"
    WaitPanelId = "intermidiate visible panel"
});
Overload 2 : Html.JForm(actionurl, methodType, JOptions, htmlArrributes);
Html.JForm("/controller/action", "GET/POST",
new JOptions 
{ 
    TargetPanelId = "update containter"
    WaitPanelId = "intermidiate visible panel"
}, new { name = "myForm" );

Going deeper, these are actually HtmlHelper extenstion methods

public static IDisposable JForm(this HtmlHelper helper, string action, string method, JOptions options, object htmlAttribtues)
{
    return new JQueryForm(helper, action, method, options, htmlAttribtues);
}

Behind the scene they call a IDisposable class callled JQueryForm that generates the form with actual hookup scripts. The concept is to generate the starting form tag with all the attributes provided during initialization and the ending form tag on dispose call. This basically is done in the Ajax.From that can be found with a little help from reflector.net (or source from codeplex). Now, inside System.Web.Mvc there is a new public class called TagBuilder, which I found really handy for building up html scripts.

Therefore, here is what I have done during initialization of JQueryForm. I have added only code that generates the tag, other things you can find it by yourself in the code provided at the end.

TagBuilder builder = new TagBuilder("form");

builder.MergeAttribute("action", url);
builder.MergeAttribute("method", method);
builder.MergeAttributes<string, object>(new RouteValueDictionary(htmlAttributes));

if (options.CallBack == null)
{
    builder.MergeAttribute("onsubmit",
                           string.Format(jStringOverload, options.WaitPanelId, options.TargetPanelId));
}
else
{
    builder.MergeAttribute("onsubmit",
                           string.Format(jString, options.WaitPanelId, options.TargetPanelId, options.CallBack));
}

responseBase = helper.ViewContext.HttpContext.Response;
responseBase.Write(builder.ToString(TagRenderMode.StartTag));

 

To add attributes MergeAttribute is used that has few overloads and appends the attribute to the generating tag. Finally, to build the string you need to use the ToString overload with proper render mode.I have used TagRenderMode.StartTag which will generate the opening html form tag.Basically, JQueryForm has only a Constructor where I build starting tag and a Dispose method where I just have to close the tag.

responseBase.Write("</form>");

As you can see that I have hooked one method in onsubmit call, the purpose of this method is to prevent default form post, do an ajax callback and get the result to a html container. I named it jAjaxSubmit.

Before jumping to the analysis of the method, let's see how to do ajax calls using jQuery. It is very clean and simple. Therefore, really cool.

$("#" + waitElementId).show();

$.ajax({
    type: actionType,
    dataType: "html",
    url: url,
    data: params,
    success: function(result) {
        $("#" + elementId).html(result);
        $("#" + waitElementId).hide();

        if (typeof callback != 'undefined')
            callback();
    },
    error: function(error) {
        $("#" + waitElementId).hide();
        //TODO:// write your log here
    }
});

This is an example of Ajax callback where I can provide the type [GET|POST], dataType[html|xml|json](i have used "html"), data[serialized form params], success and a failure callback. Those who are new to jQuery, it is to mention that $(..) is equal to the $get in Microsoft Ajax and it accepts element either by id or name (# is used to specify get element by id).

During the submit button click under Html.JForm , we first need to stop the form post. For, Internet Explorer we can do this by sending a return false but for Mozilla based browsers the proper way to do is the stopPropagation() call.

 if (!$.browser.msie) {
        e.stopPropagation();
    }

Inside the using of Html.JForm as we specify  Html elements either by Html extension methods (<%= Html.Textbox("comment") %>) or by hand. we need to get the values of them and pass them as "&" separated way during the submit process. using JQuery, we can easily do that using $(form).serialize() and pass it in the callback. So the final script looks like

function jAjaxSubmit(form, e, waitPanelId, targetToUpdate, methodName) {

if (!$.browser.msie) {
    e.stopPropagation();
}
var isValid = true;

if (typeof methodName != 'undefined') {
    isValid = methodName(form, null);
}

if (isValid) {
    // create the form body
    var body = $(form).serialize();
    renderContent2(targetToUpdate, waitPanelId, form.action, body, form.method);
}
return false;
}

renderContent2 is just a wrap around of the callback script shown earlier. In running project, injected block looks like the following firebug snap.

image

Apart from the internals , all things are done automatically by Html.JForm call, this can be found running in FlickrXplorer project but for your convenience, I have added a sample project using the default MVC template which you can get here.

Of course, you can try browsing the live app at http://www.flickrmvc.net (This gives you a nice way to fast explore millions cool public photos from flickr).

Have Fun!!!

Updated with Asp.net MVC Beta on Oct 19, 2008

kick it on DotNetKicks.com

More Posts