XML transforms, SlowCheetah

I had been working with web applications with the web.config transform. Which is a great feature for the builds automation and deployments.

But it is lack of the support for other config files, such as app.config for windows service projects or console applications. Or maybe an xml configuration file in your project.

After I read the Hanslmen’s blog, I found this little plugin in for Visual Studio called “SlowCheetah”. It enables you to create transforms for any configuration files. How great is that!

Download the plugin and restart your VS.

You will see the “Add Transform” option once you right click the configuration file.

http://visualstudiogallery.msdn.microsoft.com/69023d00-a4f9-4a34-a6cd-7e854ba318b5

To read this Microsoft dude’s blog,

http://sedodream.com/2011/08/17/AppconfigTransformVisualStudioAddIn.aspx

Enjoy the little time saver plugin.

Advertisements

Use Enum & Description to create select list item in MVC

There are always situations that we make good use of enums in projects. I like to use an Enum values to make my select list to save select-list-creation time. Here is what I always do,

Create an Enum, Eg. MonthFilter

 public enum MonthFilter
    { 
        [Description("Last Month")]
        LastMonth = 1,
        [Description("Last 3 Months")]
        Last3Months = 3,
        [Description("Last 6 Months")]
        Last6Months = 6,
        [Description("Last 12 Months")]
        Last12Months = 12,
        [Description("Year on Year")]
        YearOnYear = -1
    }

And then create the SelectListItem using this Enum and its descriptions,

    var monthFilters = from MonthFilter n in Enum.GetValues(typeof(MonthFilter))
                     select new SelectListItem { 
                            Value = ((int)n).ToString(), 
                            Text = Enumerations.GetEnumDescription(n)
                     };

Last step is create the dropdown list, by passing in the “monthFilters” Select List Items,

                @Html.DropDownList("MonthFilterDropDown", monthFilters, "Select...", null)

Setup close tab shortkey in Visual Studio, I find it really useful with Ctrl+W W, and Ctrl+W Ctrl+W

When I get used to the browser close tab short-key “Ctrl+W”, I kind of want to use the same thing for Visual Studio as well. I personally find it really speed up my process of closing a tab/ tabs.

So here I defined,

to close a tab: Ctrl + W, W

to close all but this: Ctrl + W, Ctrl +W

It might overrides some short keys to use the broswers in Visual Studio, which I never get a chance to use at all. I think the built in browser in VS sucks.

To find the place and define your short keys,

1. go to Tools –> Options –> Keyboard.

2. Find your commands: File.Close & File.CloseAllButThis.

image

Windows 8 Core / professional MSDN Version Download

 

If you’re a TechNet or MSDN subscriber, you can head on over to the links embedded at the end of this post to start downloading Windows 8 RTM and get your licence key.

If, however, you’re part of the general public i.e. without TechNet / MSDN access, you will have to wait till October 26th when Windows 8 is released to retailers. When it does, you will be able to upgrade to Windows 8 Pro from XP, Vista or 7 for the price of a $39.99 download. If you prefer a packaged, DVD version, that will cost $69.99. You can check out the features that are offered by different versions here.

Windows 8 RTM for MSDN subscribers
Windows 8 RTM for TechNet subscribers

Source: http://www.redmondpie.com/download-windows-8-rtm-officially-now-from-msdn-and-technet/

Handle Ajax request with expired forms authentication, in MVC ajax.form

There is a situation where I display a screen dynamically load a partial view using ajax.

And when the authentication expires, user initiates an ajax call, then the action is being called without authorization.

It actually returns a login view inside the DOM object on the page rather than returns a expected content with partial view.

The users will have bad UI experience and get confused.

Here I demonstrate the scenario to show you what exactly happens and what we can do about it.

1. Create an ajax.form which simply returns a partial view.


@using (Ajax.BeginForm("AjaxTestNoHandle", "Home", new AjaxOptions { UpdateTargetId = "testcontainer2"}, new { id="test-form"}))
{ 
    
}

<div id="testcontainer2">
</div>

2. Create the action method with “Authorize” attribute and return a partial view “TestPartial”

  [Authorize]
        public ActionResult AjaxTestNoHandle()
        {
            return PartialView("TestPartial");
        }

3. Run the application and click button “No Redirection Handling”. Because the user is not authenticated and it returns a partial view with the whole “Login” page. (I made login page with black background for displaying purpose)

image

Now let’s create  a customized authorize attribute to handle this situation.

1.  Create a CustomizedAuthorizeAttribute to handle login redirection if authentication is expired.  I only override the action HandleUnauthorizedRequest to detect if request is ajax, return a json result with a redirect url.

    public class CustomizedAuthorizeAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            string url = string.Format("{0}?returnUrl={1}",System.Web.Security.FormsAuthentication.LoginUrl,
                filterContext.HttpContext.Server.UrlEncode(filterContext.HttpContext.Request.RawUrl));
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                var redirectResult = filterContext.Result as RedirectResult;
                if (filterContext.Result is RedirectResult)
                {
                    // It was a RedirectResult => we need to calculate the url
                    var result = filterContext.Result as RedirectResult;
                    url = UrlHelper.GenerateContentUrl(result.Url, filterContext.HttpContext);
                }
                else if (filterContext.Result is RedirectToRouteResult)
                {
                    // It was a RedirectToRouteResult => we need to calculate
                    // the target url
                    var result = filterContext.Result as RedirectToRouteResult;
                    url = UrlHelper.GenerateUrl(result.RouteName, null, null, result.RouteValues, RouteTable.Routes, filterContext.RequestContext, false);
                }
                filterContext.Result = new JsonResult
                {
                    Data = new { Redirect = url },
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
            }
            else
            {
                //non-ajax request
                base.HandleUnauthorizedRequest(filterContext);
            }
            
        }

2. Create controller action method with CustomizedAuthorize

        [CustomizedAuthorize]
        public ActionResult AjaxTest()
        {
            return PartialView("TestPartial");
        }

3. Create ajax.form post to “AjaxTest” method.


@using (Ajax.BeginForm("AjaxTest", "Home", new AjaxOptions { UpdateTargetId = "testcontainer" }, new { id="test-form"}))
{ 
    
}

<div id="testcontainer">
</div>

4. Click “Redirection Handling” button on the page without login. In FireBug – Console, you can see a json is returned

{"Redirect":"/Account/Login?returnUrl=%2fHome%2fAjaxTest%3fLength%3d4"}

5. Now let’s add a javascript function to handle the json and redirect to the returned url. Add a OnSuccess event in “AjaxOptions” call “validate”


@using (Ajax.BeginForm("AjaxTest", "Home", new AjaxOptions { UpdateTargetId = "testcontainer", OnSuccess="validate" }, new { id="test-form"}))
{ 
    
}

<div id="testcontainer">
</div>

6. Create javascript function validate.


    function validate(data) {
        if (data.Redirect)
            window.location = data.Redirect;
    }

7. Here you go, all done! When you click the “Redirection Handling” button, it will detect the forms authentication login url and return to the login page inside the ajax request!

Cools!

To download the demo project, go to codeplex https://ajaxrequestauthentic.codeplex.com/