Thursday, December 27, 2012

Open Explorer from command console or powershell

I was reading this post about how to open command line from an explorer window at the same path. This is very helpful to speed up works a little bit.

In order to open command line in current directory you just need to type 'cmd' in address bar. Also you can type 'powershell' if you need powershell.

However, in reverse if you want to open windows explorer from command line this is what you need to type in command line:

explorer .

note that if you miss explorer then it will open your user's documents folder.
And for powershell the command is:

ii .

note: ii is alias for invoke-item.

Friday, December 7, 2012

Introduction to DotNetAuth

Recently I have been working on implementation of OAuth protocol. The outcome was not that much bad, so I decided to make it available for others to use it free. Although I am still working on its features, it is fully functional. I have used it in several of my projects.

OAuth protocol is a protocol which is implemented by a lot of famous social networks and is the fundamental key to working with most of their APIs, specially to access to methods which requires some of identity of the requester. So if you want to integrate your website with Facebaook or Google Plus or LinkedIn etc probably your first step would be to handle OAuth protocol.

Also it is a common practice to use OAuth for authenticating user's in your website. Instead of the classic set of username/password credentials, you can simply deliver the user identification to these social networks and ask for user's primary set of information like name, date of birth, gender etc through their API.

OAuth protocol is a complete protocol as it considers all the parties(one which needs to authorize, one which need to make an authorized request, end user who authorizes) and all common scenarios in ways of communication between parties.

DotNetAuth is a an implementation of the OAuth protocol which only supports the consumption of protocol, and it is only for server side flow. So if you are the developing a website which wants to makes user-authorized requests to social network sites like Facebook or Google API this library is for. Also this library helps you take advantage of the OAuth protcol to identify users of your website and use OAuth for user membership(sign up, sign in features).

Source Code:

Nuget Packages:

Install-Package DotNetAuth
Install-Package DotNetAuth.Profiles

Asp.Net MVC Sample:
This is just a sample to show what it would look like.
Just add above packages and then you can have the following methods in your ProfileController:

public class ProfileController : Controller
    ProfileProperty[] requiredProperties = new[] { ProfileProperty.Email, ProfileProperty.DisplayName, ProfileProperty.UniqueID, ProfileProperty.DisplayName };
    // GET: /Profile/
    public ActionResult Index()
        return View();
    public RedirectResult Login()
        var userProcessUri = Url.Action("Callback""Profile"null, protocol: Request.Url.Scheme);
        var provider = LoginProvider.Get(LoginProviderRegistry.Facebook.Fullname);
        var authorizationUrl = DotNetAuth.Profiles.Login.GetAuthenticationUri(provider, new Uri(userProcessUri), new DefaultLoginStateManager(Session), requiredProperties);
        return Redirect(authorizationUrl.Result.AbsoluteUri);
    // GET: /Process
    public ActionResult Callback(string providerName)
        var userProcessUri = Url.Action("Callback""Profile"null, protocol: Request.Url.Scheme);
        var provider = LoginProvider.Get(LoginProviderRegistry.Facebook.Fullname);
        var profile = DotNetAuth.Profiles.Login.GetProfile(provider, Request.Url, userProcessUri, new DefaultLoginStateManager(Session), requiredProperties);
        return Content(profile.Result.ToString());

And that's it.

Friday, November 30, 2012

Bundling using Cassette in Asp.Net MVC

I am a big fan of Cassette library. It is an ending to lots of problems you will face in managing your web application scripts and style sheets. Basically what it does is serving JavaScript files and CSS files in a much more efficient and manageable way.

In short these are benefits of using Cassette:
  • bundling assets
    • multiple files concatenation into single file, so fewer HTTP requests
    • reference management
    • avoiding including unnecessary assets in a page 
  • performance improvements
    • assets auto versioning and caching 
    • performance achievements through caching 
    • HTTP compression
  • good transforms
    • script minification
    • support for CoffeeScript
    • support for SASS 
    • support for LESS 
    • support for hogan html templates which means precompiled html templates 
    • embedding small images into CSS files 
  • a little bit of access control over script files. 
  • debug friendly
Although Cassette is for both JavaScript and style sheets, if you do it for JavaScript files the same process is for style sheets and HTML templates. So, let start by JavaScript files.

Setting up the Cassette in your web project

First of all we need to do a little work to make Cassette features working in our web projects.

The automatic way:

Using nuget package, just run the following command:
install-package cassette.aspnet

The manual way:

You may be a control freak like me, I need to do the things manually in order to make sure that I do know what is happening in my web application, and hence I know what is wrong in case of a failure.

So here are the things that should be done to make Cassette working:
  1. Configuring web.config to 
    1. add required HTTP module and HTTP handler 
    2. add Cassette.Views to razor page namespaces, you have to do this step for areas manually, even if using nuget package. 
  2. Adding CassetteConfiguration class 
  3. Add references to required assemblies:
    • Cassette
    • Cassette.Views
    • Cassette.Aspnet
    • AjaxMin
      For all the features:
    • Cassette.CoffeeScript
    • Cassette.Sass
    • Cassette.Hogan
    • IronRuby
    • IronRuby.Libraries
    • IronRuby.Libraries.Yaml
    • Jurassic
This is the HTTP module you need to add to configuration>system.web>httpModules:

<add name="CassetteHttpModule" type="Cassette.Aspnet.CassetteHttpModule, Cassette.Aspnet" />
You may add the same to configuration>system.webServer>httpModules.

This is the HTTP handler you need to add to configuration>system.web>httpHandlers

<add name="CassetteHttpHandler" path="cassette.axd" preCondition="integratedMode" verb="*" allowPathInfo="true" type="Cassette.Aspnet.CassetteHttpHandler, Cassette.Aspnet" />
You may add the same entry to  configuration>system.webServer>httpHandlers.

And you have to include Cassette.Views in configuration>system.web>pages>namespaces:

<add namespace="Cassette.Views" />
If you are using Asp.Net MVC Areas, Add the above namespace to every area's web.config.

How to implement Cassette

Simply there is only three steps:
1. create bundles to bundle a set of scripts together by writing the following line in CassetteConfiguration:

This will create a bundle named lib/js which bundles all files in lib/js folder.

2. reference bundles to specify which script is required in your razor page by writing:

It records a flag that bundle lib/js should be rendered when rendering scripts.

3. create the script tag(s) to load all the referenced libraries. in your razor page you write:

It renders all the so far mentioned bundles into one or several script tags.

Step 1. Creating and configuration of bundles

In step one you specify which files to be included in a bundle called "lib/js", you may also specify more advanced setting for bundle, like how to search for files, which files should be ignored, etc.

When bundling you specify a folder path, then according to some rules, script files within that path will be added to the bundle. Default rules exclude -vsdoc.js files and also if alternative .min or .debug file exists, then only one file is picked.

Step 2. Adding references to scripts

In step two you only mention that the specified bundle is required, you can do this 'referencing bundles' anywhere, it could be the layout page, a partial view. So you ask for a bundle to be included only when it is required and at the place that requirement is raised. For example you have a partial view that requires a specific script, so you add a reference to that script in that partial view. Assuming that no other view or partial view has a demand for that script, then that script only will be loaded for pages which contains that partial view.

The reference you specify is a bundle path. So if you write @Bundles.Reference("X") then you should have bundles.Add("X") in your Cassette configuration, or you should have a bundles.Add("Y") where X can be find in Y.

Step 3. Rendering the actual script tags

In step three you actually create script tags. So the bundles you have mentioned so far using the @Bundles.Reference will be rendered into one or multiple script tags. If your compliation debug attribute is set to true, then Cassette does not join scripts and does not minify them, so you still can debug your scripts. In contrast, if debug="false", then Cassette concatenates scripts files into a single file and also minifies them.

It may be a little bit confusing, at least it was for me. As I described it here, the step one may seems unnecessary, but you should note that in step two "lib/js" does not refer to a scripts folder, but it is referring to the bundle we created at step one.

Rendering script tags is where you get the point of Cassette, the way that Cassette renders script tags and brings scripts into your page has several benefits. But before going forward to discuss the benefits, first let me describe some facts about how Cassette works, so then I can tell how those benefits are achieved.

  1. Cassette exposes a HTTP handler for sending back scripts to client.
  2. Cassette computes a hash for each bundle. If the scripts change, the hash value will change.
  3. Cassette will return a bundle even if you asked for a single script file. For example you asked for "lib/js/MySpecificLib.js", then Cassette will return bundle "lib/js".
  4. Cassette will include dependencies and order scripts based on their dependencies.

So the benefits are:

 - You can prevent direct access to your script libraries. So if you are using Cassette for all your resources  then you may restrict direct access to libraries folder.

 - Unless you created a bundle you can not reference to a script file. So there is a limited number of bundles all defined in CassetteConfiguration class. Each bundle is accessed via Cassette's HTTP handler and has a URL which is consisted of bundle's hash. So if you change the scripts then the hash changes and the URL changes, so the browser would not use the cached version and hence you forced browser to fetch the new version of bundle. And as long as the scripts are the same you can rely the browser caching. Here I have to point out an important guideline: put third parties libraries and your own libraries in different bundles, because they have different change frequencies  Your app's scripts change more often, so they bundle need to be reloaded more often.

 - When referencing you can be specific about exactly which scripts you need, you don't have to mention the bundle itself. If you specify a script file instead of a bundle, then cassette will render a script tag pointing to any bundle which contains that file, chances are that file already has been loaded once. However because you specified the file name rather than the bundle name, you can move that file to another bundle, for example make your bundles more granular and specific, without being worried about places which that bundle was referenced.

 - You only need to reference the scripts you directly need, you don't need to be worried about if you have included the required libraries which your scripts requires.

 - One important thing you should know is that the way script tags are rendered is dependent on compilation debug attribute. If it's value is true, Cassette will generate debug friendly script tags and script files are rendered as it is. In contrast, if debug value is false, then Cassette will generate efficient script tags and script files are concatenated and minified.

 - Probably you are using layout pages in a way that your pages are not concerned with the head section of html. Using Cassette you render scripts only in layout page and then reference the bundles in page whenever they are required, so when each page is served the scripts(bundles) related to that specific page is rendered.

Note: For simplicity, I have written this article for scripts. However the same story happens for style sheets, the only difference is that instead of ScriptBundle you use StylesheetBundle. And instead of @Bundles.RenderScripts() you will write @Bundles.RenderStylesheets() .

Targeted Bundles

When defining a bundle you can restrict it to a specific target. Actually, the Cassette itself referes to it as PageLocation, however you can use this feature beyond page location, so I named it targetted bundling.

Thursday, November 29, 2012

A behavior to keep DataGrid's SelectedItem into View

The following simple behavior will forces a DataGrid to keep its SelectedItem into view. The way that it works is simply hooking SelectionChanged event and calling DataGrid.ScrollIntoView method.

An advice : Remove code behind files in WPF

In WPF when using MVVM it is better to delete the code behind file straight away. Those almost empty code files are not necessary at all and the project will compile without them. Moreover, if you have removed the code behind file an press F7 key, then nothing happens. It matters to me because I have a habit to press F7 to navigate to code related to XAML, and doing so it always opens code behind file which is not desired.

Tuesday, August 7, 2012

Meetup Invalid Authorization request

Trying to connect to API using OAuth2.0 I had a problem which I find out this is not documented in their API documentation.
The redirect_url parameter is case sensitive. So if this is the case then you will recieve the error message :

Invalid Authorization request

If you were directed here by another application, contact its developer

So make sure that the redirect uri of your application defined at exactly(case wise) matches the redirect_uri parameter you pass in your authorization request.

Monday, April 23, 2012

Automata and Compilers courses from coursera

I did write ve parser without any technical knowledge about parsing algorithms, I always wanted to improve my knowledge in this area and now I have the chance to do it.
I am very excited to start two online free courses today. These courses are Automata and Compilers.

There are some other computer science courses available on Have a look at it, there is also courses in other fields.

Thursday, March 29, 2012

WPF Grid Layout Simplified Using Rows and Columns Attached Properties

A major problem with WPF and XAML is that XAML code tends to be very cluttered and after a little your XAML code gets too much complicated. In a recent project I suggested to define new controls by deriving from existing controls, so you can assign a shorter name to them or avoiding setting the same property the same value for thousand of time(e.g. Horizontal orientation stack panel).

Here is another tip to make you XAML code less cluttered. One area that you may find it hard to write and read and maintain is Grid layout control. Defining RowDefinitions and ColumnDefinitions waste too much space and adds too unnecessary lines of code. Hence it become too complicated to handle it.
The solution I am sugessting here is to use some attached properties to define RowDefinitions and ColumnDefinitions in a smarter way.
You can fetch the code for attached properties here:
This code adds these attached properties to Grid

  • Grid.Rows
  • Grid.Columns

and adds these attached properties to UIElemnet

  • Cell

Grid.Rows and Grid.Columns are same thing but one is for specifying rows and one is for columns. These two properties are simply text value which you can set it according to the following Rules:
  • Separate items with semi colon(;) , Example "auto;auto;*"
  • Use auto for adding an Auto sized row or column , Example "auto;auto"
  • Specify * for adding an star sized row or column, Example "1*,2*, *"
  • Specify only a number for adding a fixed size row or column, Example "200,200,100"
  • Append # followed by a number to add multiple rows and columns of same sizing. "1*#4,auto"
  • The number of starts in an item will multiplies star factor. Example "**,***,*" instead of "2*,3*,*"

XAML Sample:

<Grid s:Grid.Rows="auto;1*;auto;auto" s:Grid.Columns="*#5;auto"> ... </Grid>

Adds 4 rows to grid which are all Auto sized except the second row which occupies all remained space. Also adds 5 star columns followed by an Auto sized column.
As I said this is simply 3 attached properties which allows you to specify the rows and columns using a textual representation. Here is the function which converts the textual value into a GridLength value:

public static GridLength ParseGridLength(string text)
    text = text.Trim();
    if (text.ToLower() == "auto")
        return GridLength.Auto;
    if (text.Contains("*"))
        var startCount = text.ToCharArray().Count(c => c == '*');
        var pureNumber = text.Replace("*""");
        var ratio = string.IsNullOrWhiteSpace(pureNumber) ? 1 : double.Parse(pureNumber);
        return new GridLength(startCount * ratio, GridUnitType.Star);
    var pixelsCount = double.Parse(text);
    return new GridLength(pixelsCount, GridUnitType.Pixel);

And here is the function which makes # operator working:

public static IEnumerable<GridLength> Parse(string text)
    if (text.Contains("#"))
        var parts = text.Split(new[] { '#' }, StringSplitOptions.RemoveEmptyEntries);
        var count = int.Parse(parts[1].Trim());
        return Enumerable.Repeat(ParseGridLength(parts[0]), count);
        return new[] { ParseGridLength(text) };

And finally the attached property change callback:

var grid = d as System.Windows.Controls.Grid;
var oldValue = e.OldValue as string;
var newValue = e.NewValue as string;
if (oldValue == null || newValue == null)
if (oldValue != newValue)
        .Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
        .Select(l => new ColumnDefinition { Width = l })

The above code is for Columns attached property but this is the same for Rows attached property as well.

The whole source code for these attached properties:

Tuesday, March 27, 2012

GitHub Gist

Love sharing? Are you a social coder? A lot of times you may wanted to share piece of code but you give up just because it was going to be a cumbersome process to create a project on CodePlex or GitHub.
I just see a simple feature of GitHub, named Gist. It's a simple method for sharing your code that you find useful for others. For example, having to implement online payment functionality for my Asp.Net MVC website I ended up with a simple PaymentController which I just shared it with GitHub.
Here is my first gist:

Monday, March 26, 2012

Why Invalid Object Name 'dbo.__MigrationHistory'?

Unfortunately I am using  Entity Framework in my project. After migration support added to Entity Framework I thought using this feature may help me feel a little better about  Entity Framework . But the way migration is implemented in EF shows that nothing has changed. Migration has lots of problems and bugs.
After carefully doing all the required cumbersome procedures  Entity Framework migration failed to work and I found no workaround until I strangely faced the exception 'Invalid Object Name 'dbo.__MigrationHistory''. This exception give me  a clue about the cause of my problems.
It seems that Entity Framework team do not use appropriate testing methods and they only care about the main courses and are very negligent about alternative cases. For example in this case they presumed that always the default schema is dbo. It creates __MigrationHistory on the default schema, but queries for it on the dbo schema.
After a while I find another problem. Entity Framework also tries to insert rows into __MigrationHistory without specifying schema name.

Ok, I wrote this code to make Entity Framework script generator apply 'dbo.' before the __MigrationHistory. I know this is naive solution but at least it works.

A WPF Technique: Decorating controls by deriving from standard control

I always consider StackPanel as Vertical StackPanel as it is Vertical by default, but why there is no layout control that is horizontal by default?. I believe it does not worth for the WPF framework to introduce one as it is very easy to write if you need one. In this post I am going to describe how easy is to create a HorizontalStackPanel and a couple of related useful notes.

Define types by deriving from WPF controls.
The simplest way to write your own controls is to derive from existing ones. You do not need to do anything else. Yes, that it, you have the same control with the same functionalities but with a different Type. For example you may derive a class from TextBlock, it still is a TextBlock but it has its own specific type, so it is behave in a slightly different in some cases, mostly when you refer the types like in a TargetType of a Style.
Here is a summary of benefits of doing so:
  • Defining some common behaviour in code and not using the styles
  • Easier targeting them in styles
  • More readable XAML code
  • Very helpful for code sharing between Silverlight and WPF
HorizontalStackPanel as an example
For example you may define a HorizontalStackPanel by deriving a type from StackPanel and setting its Orientation to Horizontal in its constructor. Actually it is not a horizontal stackpanel but it is InitialyHorizontalStackPanel as the users have the opportunity to change the orientation later using XAML or code.
Also the HorizontalAlignment in StackPanel has a default value of Stretch, you need to set it back to Left and do the same for VerticalAlignment.

public class Horizontal : StackPanel
    public Horizontal()
        Orientation = Orientation.Horizontal;
public class Vertical : StackPanel
    public Vertical()
        Orientation = Orientation.Vertical;

So now you can write these XAML code

  <StackPanel Orientation="Horizontal">

This way


Which is much more readable and less cluttered.

Wednesday, February 15, 2012

Entity Framework 4.3 Released

Just read this announcement about the release of Entity Framework 4.3. Despite some fixes, the only great feature added to this version is the Entity Framework Migration. So now using Entity Framework 4.3 you can keep your data after changing your data model. In the past, you need to drop and recreate database or handle database upgrade manually.

Saturday, January 14, 2012

Using third party web services in your applications

Reading a question in StackOverflow website I thought I have to write about my suggestion to Windows Phone developers regarding the way you should use third party web services in your applications:

Adding a layer of indirection is considerable
It is very common that you need to consume a web service from a third party to show some information to your users or provide some functionality for them. So the easiest way is to add a reference to their web service in your application and call methods.
In certain scenarios you have to employ this method. But I am thinking of not adding a direct dependency to a third party web services. Ans I suggest to add a layer of indirection by implementing your own web service by dispatching the request from your applications to the third party web service.
Application Vulnerability to changes in web service definition
By adding a direct dependency to a third party web service and considering the fact that the web service owners may change the web service definition, all the installed instance of your application may fail to work if such a change happens. Then you have to provide an updated version of your application and wait users to install the update. Some users may not be happy with the situation and decide to uninstall the application instead of updating.
The chance of adding your own functionality
If you directly call the third party web service you are limited to functionalities provided by that web service, for example imagine that you call web service to receive a list of addresses. Now if you want to pin them on a map, you need the latitude and longitude of the addresses which is not provided by the web service. I believe in most of the cases you will be much more productive if you have some power to do the things in your own way.
Performance and efficiency considerations
As the designers of third party web service have thought about some specific scenarios the set of methods they provided may not match your exact needs. For example you may have to make two or three calls to receive all the required data and no single method gives all the response you needed. And the result from the first calls is not enough to provide any feedback to user . Or as an another example you may only need to show a part of received data and have nothing to do with the whole given data. As can be clearly seen by this examples there could be two kind of problems with third party web services, extra round-trips and extra bandwidth consumption, which avoiding them can increase your application performance.
Logging and tracking
Generally a good method for logging and other cross cutting concerns is to have an indirection layer, which receives requests and dispatches them. And here in our topic about third party web services, if we do not sit in user's way to access to data and services we have no chance to track them and have a report of it. So create a web service and dispatch the request to third party web service and meanwhile collect some useful data like error exceptions, calls count, performance logging, caching. And do not forget to be respectful to users privacy. If your application is mostly calling the web service then you could have a nice report your application usage.

Some disadvantages
No need to say, writing your own web service has its own disadvantages. First it is costly, you have to develop, test, maintain the web service. Also you have to pay for hosting, if you do not have a spare web space. And your hosting may not be as powerful and fast as the third party web service is, so your app would not be as fast as it could be. Also there are legal issues about using third party web services, some web services specifically forbidden not using their services directly. I am not very into security, but I have a vague idea about there may be some security issues.

What do you think?
Also there may be some other advantages and disadvantages, I would like to hear about them, so do not hesitate to leave a comment.

Wednesday, January 11, 2012

Assigning null to anonymouse type properties

Just a quick note about handling an issue for anonymous types, if you wanted to assign a null value to a property you will face a compile error which says Cannot assign <null> to anonymous type property, and the easy solution for this is to write to cast the null to desired type, this is important specially if you are creating an array of anonymouse typed objects.

Here is a sample code:

return new[] { 
    new { Name = "Fixed Value", ViewModel = (objectnew B_FixedValue_EditViewModel() } ,
    new { Name = "Fixed List", ViewModel =  null as object} ,
    new { Name = "Calculation on one value", ViewModel = null as object } ,
    new { Name = "Calculation on two values", ViewModel = null as object } ,
    new { Name = "Loading a value from database", ViewModel = null as object } ,
    new { Name = "Conditional Value Provision", ViewModel = null as object} ,