Saturday 6 October 2012

Microsoft's New Language "TypeScript"

After the Google's Dart Microsoft has responded with the "TypeScript"  yet another language that compiles to javascript. TypeScript provides many features for example type inference and concept of classes and modules which have also been proposed by Ecmascript 6 (ES6).

Having said the pleasantries, lets do what we really like to do that is to say hello ... one thing that i really love about Microsoft is that is provides great tooling support, you can download and install the TypeScript editor plugin that integrates with Visual Studio 2012 and provide you with the ready to run TypeScript Application template. TypeScript also provides support for other editors

After you have installed the TS plugin for VS2012 you can fire up the studio and find the TS application template under Visual C# Installed Project templates.



After the project has been successfully created you can simply hit f5 to launch the application and see the greeting message



Another highlight, developers familiar with c# may not find it a new thing but, the use of lambdas to represent the anonymous functions is quite intriguing.


 There is no need to share this getting started code because we have not added a single line of code to the auto generated application code by VS2012.

 The TypeScript is developed on codeplex where you can browse the source code



Wednesday 2 May 2012

Create a simple HTTP server with Node.js

With so much of the hype of node.js and the server side javascript i decided to give it a go, the post is not really as complicated as the title may look like, node.js allows you to get real taste of the core protocols which we tend to ignore while using frameworks, though there are some good application frameworks for building node applications like Express and Geddy but in the initial stage one should learn the way it really works out IMO... so without fuether ado lets get down to writing the http server, i assume that you have success fully installed node.js HERE is a useful link.

After the installation you can check the version of the node by typing

node -v

into the terminal window, i'm using fedora 15 (lovelock). Ok now create a file and name it server.js and put the following code inside it
var http = require("http");

http.createServer(function(request, response) {

  response.writeHead(200, {"Content-Type": "text/plain"});

  response.write("Hello Node");

  response.end();

}).listen(8088);


in-order to listen to port 80 you would require the root privileges so i'm not getting into that.

 The first line of code is used to include pre-build module of http more on node modules in the later posts...

the rest is very obvious, cd to the directory where server.js is residing and type

[fedora@localhost HelloNode]$ node server.js


 now  just redirect your browser to

 http://localhost:8088
 
and it will greet you with the

message "Hello node"...

Congratulations you have made yourself a http server

P.S i took help from this guide

Wednesday 28 December 2011

Controlling Multiple Form Posts in Telerik Grid For MVC

At my work place we are developing a web based application that is very data centric and involves a lot of Grids. After a lot of Grid survey we ended up using the Telerik Grids for MVC. The problem with the grid was that when it was used  with ajax binding and the edit mode set to GridEditMode.PopUp, of the user submits the form twice the value was inserted in the Database multiple times. Click here to enlarge the image




So to filter out the identical form posting i wrote a helper method to generate a GUID

namespace Namespace.FilterAttributes
{

public static class GuidHelper{

  public static MvcHtmlString GetGuid(this HtmlHelper helper)

   {

    var guid = Guid.NewGuid().ToString();

    helper.ViewContext.HttpContext.Session[guid] = "";

    return MvcHtmlString.Create(string.Form  at("<input type='hidden' id='FormGuid' name='FormGuid' value='{0}' />", guid));

 } 


}
in the view to generate the GUID simply
<%@ Import Namespace="Namespace.FilterAttributes" %>

<%:Html.GetGuid()%>

attach a OnSave Client event to the grid so the GUID generate can be transported to the server
function onSave(e) {                 
          e.values["FormGuid"] = $("input[name='FormGuid']").val();
      }

in the ActionFilter attribute look in the session for the GUID if the session is null or empty put the value in the session so that the next time if the same form is posted again it should be filtered out.
public class MultiFormControlAttribute : ActionFilterAttribute   {

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var ctx = filterContext.HttpContext;
            var response = ctx.Response;       
            var session = ctx.Session;
            var fGuid = ctx.Request.Form["FormGuid"];
            if (ctx.Session["fGuid"] != null)
            {
                if (fGuid.Equals(ctx.Session["fGuid"].ToString()))
                {
                    //kill the request kill it!!!       

                   //add the model error 
                    filterContext.Controller.ViewData.ModelState.AddModelError("", "Duplicate form post");
                }
                ctx.Session["fGuid"] = fGuid;
            }
            else
                ctx.Session["fGuid"] = fGuid;            
        }
    }

Decorate the ActionResult responsible for the insertion of the values in the Grid with the MultiFormControl Attribute.
        [GridAction,MultiFormControl]

        public ActionResult _AjaxBindingInsert(User _User) 
        {

             if(ModelState.IsValid){
            _users.Add(_User);
            Session[_user_key] = _users;

         }
            return View(new GridModel(_users));
        }

So far so good but the problem arises after the first value has been inserted upon inserting the second value the GUID was the same old one that was generated for the previous form it was not updated as the form was posted via AJAX. So to refresh the GUID upon submission of the form attach a OnDataBound client event to the Grid and reset the GUID
function OnDataBound(e) {

 $.post('<%= Url.Action("GetGuid") %>', function (data) {

 $("input[name='FormGuid']").val(data);
 });
}

Add an overloaded helper to the GuidHelper class to generate the GUID OnDataBound
  public static string GetGuid(HttpContextBase context)
{

  var guid = Guid.NewGuid().ToString();
           context.Session[guid] = "";// Not null
           return guid;
  }

and an ActionResult by the name of GetGuid
public ActionResult GetGuid()
{

return Content(GuidHelper.GetGuid(HttpContext));
        }

Now upon each successful submission of the form the GUID is regenerate at the same time identical form submissions via ajax are filtered out.

The complete demo can be found here