Tuesday, October 7, 2014



CREATE FUNCTION [dbo].[csfn_getlist](@I_cList varchar(8000))  
RETURNS @Result TABLE (Element varchar(40)) AS
BEGIN
 DECLARE @Element varchar(40), @Pos int
 IF RIGHT(@I_cList,1)!=',' SET @I_cList=@I_cList+','
 SET @Pos = CHARINDEX(',', @I_cList)
 WHILE @Pos > 0
 BEGIN
  SET @Element=LEFT(@I_cList,@Pos-1)
  INSERT INTO @Result (Element) VALUES (@Element)
  SET @I_cList=RIGHT(@I_cList,LEN(@I_cList)-@Pos)
  SET @Pos = CHARINDEX(',', @I_cList)
 END
 RETURN  
END

Result
--------
declare @list varchar(max)
set @list= '124,45,76'

select * from [dbo].[csfn_getlist] (@list)

124
45
76

Tuesday, June 17, 2014

JQuery Only allow two digits after decimal in textbox

JQuery Only allow two digits after decimal in textbox


<input type="text" class="number" />

$('.number').keypress(function(event) {
  if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
    event.preventDefault();
  }
    if(     ($(this).val().indexOf('.') != -1) &&   ($(this).val().substring($(this).val().indexOf('.'),$(this).val().indexOf('.').length).length>2 )         ){
        event.preventDefault();
    }
});


DEMO: follow the link

http://jsfiddle.net/VRa6n/764/

Tuesday, June 3, 2014

How To Get Multiple Result Sets in LINQ Query ( with entity framework)

There are two methods i have found, by which we can bind the data with Eval in gridview.

   List articleList = new List();
    
   List articleList1 = new List();
#region Method I
        var promotionProductObject = (from p in _dataEntities.Promotions
                           join pa in _dataEntities.PromotionArticles
                           on p.PromotionId equals pa.PromotionId
                           where (pa.DeletedBy == null) && (pa.DeletedOn == null) && (p.PromotionId==14)
                                      select new
                                      {
                                          p,
                                          productlist = (from a in _dataEntities.Artikels
                                                         where pa.ArticleId == a.ID
                                                         select a)
                                      }).ToList();

        if (promotionProductObject != null)
        {
            for (int i = 0; i < promotionProductObject.Count(); i++)
            {
                Artikel article = promotionProductObject[i].productlist.ToList()[0];
                articleList.Add(article);
            }

            grdArticleDetails.DataSource = articleList;
            grdArticleDetails.DataBind();
        }

        #endregion Method I

        #region Method II
        var promotionArtilceObject = (from p in _dataEntities.Promotions
                                      join pa in _dataEntities.PromotionArticles
                                      on p.PromotionId equals pa.PromotionId
                                      join a in _dataEntities.Artikels
                                      on pa.ArticleId equals a.ID
                                      where (pa.DeletedBy == null) 
                                      && (pa.DeletedOn == null) && (p.PromotionId == 14)
                                      select new
                                      {
                                          p,//Promotion
                                          productList = a // Article
                                      }).ToList();

        if (promotionArtilceObject != null)
        {
            for (int i = 0; i < promotionArtilceObject.Count(); i++)
            {
                articleList1.Add(promotionArtilceObject[i].productList);
            }
            grdArticleDetails1.DataSource = articleList1;
            grdArticleDetails1.DataBind();
        }
        #endregion Method II

    }

Wednesday, May 14, 2014

ASP.Net MVC Request Life Cycle

The main components and their role in the Request pipeline.



Introduction

While programming with ASP.Net MVC, we should ndeerstand how ASP.NET MVC processes our requests and how many main stages there are in this process. There are primarily seven stages in the ASP.Net Request Life Cycle.

MVC.jpg

Routing

Routing is the first stage of the MVC Request Life Cycle. All requests to an ASP.NET MVC based application first pass through an UrlRoutingModule object (that is nothing but a HTTP module). The RouteCollection property of UrlRoutingModule contains all routes registered in the Global.asax file. UrlRoutingModule searches and matches for the route that has a URL. When a match is found, it retrieves the IRouteHandler object for that route. The route handler helps to get an IHttpHandler object and that is a HTTP handler for the current request. Route objects are added to the RouteTable object.
protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RegisterRoutes(RouteTable.Routes);
}
public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapRoute(
        "Default"// Route name        "{controller}/{action}/{id}"// URL with parameters        new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults    );
}

MVC Request Handler (MVCRouteHandler)
MVC handler is responsible for initiating MVC applications. The MvcRouteHandler object creates an instance of the MvcHandler and passes the instance of RequestContext to MvcHandler. MvcHandler is implemented from ITttpHandler and it cannot map as a handler. This class does not support a parameterless constructor. It takes RequestContext as a parameter. 

Controller

MVCHandler receives a controller instance from the MVC controller factory (IControllerFactory). This controller handles further processing of the request. The MVCHandler object uses RequestContext (passed as a constructor parameter) instance to identify the IControllerFactory object to create the controller instance. The MvcHandler instance calls the Execute method of controller.

Create and register Custom Controller Factory

public class CustomControllerFactory : IControllerFactory{
    public IController CreateController(RequestContext requestContext, string controllerName)
    {
        //TODO: IoC implementation or Creating controller from request context.          return null;
    }
    public void ReleaseController(IController controller)
    {
        var disposable = controller as IDisposable;
        if (disposable != null)
        {
            disposable.Dispose();
        }
    }
    public System.Web.SessionState.SessionStateBehavior GetControllerSessionBehavior(RequestContextrequestContext, string controllerName)
    {
        throw new NotImplementedException();
    }
}
public class MvcApplication : System.Web.HttpApplication{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        ControllerBuilder.Current.SetControllerFactory(new CustomControllerFactory());
        RegisterRoutes(RouteTable.Routes);
    }
}

Action invocation 

The Controller class is inherited from the ControllerBase. The ControllerActionInvoker object is associated with a controller object that is responsible for determining which action of the controller is called, then the controller invokes this action method. The selected action is called based on the ActionNameSelectorAttribute attribute (by default it is the same as the Action name). This ActionNameSelectorAttribute helps us to select the correct action method if more than one action method is found that has the same name. In this stage the action filters are also applied. There are four types of filters, AuthorizationFilters, ExceptionFilters, ActionFilters and ResultFilters. Action invoker uses a Model Binder object if the action method has argument(s). 

A Model Binder provides a simple way to map posted form value(s). Model Binder is just like a type converter, because it can convert a HTTP Request into an object and pass it to the action method.

Execute Result

The action method is responsible for receiving user input and creating appropriate response data and then executing the result by result type. MVC supports many builtin action result return types, like ViewResult, RidirectToRouteResult, RedirectResult, ContentResult, EmptyResult and JsonResult. We can create our own action result return type.

Refer: Action Return Result Type

View Engine

View Result is responsible for selecting and involving the appropriate View Engine. A View Engine is responsible for rendering HTML to the browser. The View Engine template has different syntax to implement the view. Currently there are four builtin View Engines (Razor, ASPX, Spark and NHaml) supported by MVC. We can also create our own custom View Engine to render a view. All the View Engines may not be supported in all versions of MVC. We can also use multiple View Engines simultaneously in ASP.NET MVC.

Creating Custom View Engine

public class MyViewEngine : IViewEngine{
    public ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, booluseCache)
    {
            //Finds the partial view by using the controller context.        return null;
    }
    public ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName,bool useCache)
    {
        //Finds the view by using the controller context.        return null;
    }
    public void ReleaseView(ControllerContext controllerContext, IView view)
    {
        //Releases the view by using the controller context.    }
}
public class MvcApplication : System.Web.HttpApplication{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        RegisterGlobalFilters(GlobalFilters.Filters);
        //Clear all current register view engine        ViewEngines.Engines.Clear(); 
        //Register Custom View Engine         ViewEngines.Engines.Add(new MyViewEngine());
        RegisterRoutes(RouteTable.Routes);
    }
}

View

An Action method may return JSON data, a simple string or file. Commonly an Action Result returns a ViewResult. ViewResult is rendered and returned as an HTML page to the browser using a View Engine. 

Conclusion

This article helps us to understand the Request Life Cycle in MVC.

Tuesday, May 13, 2014

Top 10 New Features in ASP.net MVC 4


What is New in ASP.net MVC 4 ?

Feature 1 : ASP.net Web API

      What is ASP.net Web API ?

  • New framework for creating HTTP services
  • That can reach a broad range of clients including browsers and mobile devices
  • Web API is also an ideal platform for building RESTful services

Feature 2 : Enhancements to Default Project Templates

  • The Template that is used to create new ASP.net MVC 4 projects has been updated to create a more modern-looking websites

Enhancements to Default Project Templates

  • In addition to cosmetic improvements, there’s improved functionality in the new template
  • The Template employs a technique called Responsive Design to look good in both desktop browsers and mobile browsers without any customization

mobile browsers without any customization


How to See Responsive Design in Action ?
  • You can use a mobile emulator or just try re-sizing the desktop browser window to be smaller
  • When the browser window gets small enough, the layout of the page will change

What is Responsive Web Design (RWD) ?
  • Is a web design approach aimed at crafting sites to provide an optimal viewing experience
  • Easy reading and navigation with a minimum of re-sizing  panning, and scrolling across awide range of devices (from desktop computer monitors to mobile phones)

Feature 3 : Mobile Project Template

  • If you’re starting a new project and want to create a site specifically for mobile and tablet browsers
  • Then you can use the new Mobile Application project Template
  • This is based on jQuery Mobile, an open-source library for building touch-optimized UI
  • This template contains the same application structure as the Internet Application template and the controller code is virtually identical
  • But it's styled using jQuery Mobile

Mobile Project Template


styled using jQuery Mobile



Feature 4 : Display Modes

  • Lets an application select views depending on the browser that's making the request

For example :
  • If a desktop browser requests the Home page, the application might use theViews\Home\Index.cshtml template
  • If a mobile browser requests the Home page, the application might return theViews\Home\Index.mobile.cshtml template
  • Layouts and Partials can also be overridden for particular browser types

That is :
Layouts :
  • If your Views\Shared folder contains both the _Layout.cshtml and _Layout.mobile.cshtmltemplates,
  • Then by default the application will use _Layout.mobile.cshtml during requests from mobile browsers and _Layout.cshtml during other requests

Partials :
  • If a folder contains both _MyPartial.cshtml and _MyPartial.mobile.cshtml,
  • The instruction @Html.Partial("_MyPartial") will render _MyPartial.mobile.cshtml duringrequests from mobile browsers, and _MyPartial.cshtml during other requests

Feature 5 : jQuery Mobile and Mobile Features


  • The jQuery Mobile library provides a user interface framework that works on all the major mobile browsers
  • jQuery Mobile applies progressive enhancement to mobile browsers that support CSS and JavaScript
  • Progressive enhancement allows all browsers to display the basic content of a web page,while allowing more powerful browsers and devices to have a richer display
  • The JavaScript and CSS files that are included with jQuery Mobile style many elements to fit mobile browsers without making any markup changes
  • You can install the jQuery.Mobile.MVC NuGet package, which installs jQuery Mobile and aview-switcher widget


Feature 6 : Task Support for Asynchronous Controllers

  • You can now write asynchronous action methods as single methods that return an object of type Task or Task<ActionResult>

Feature 7 : Azure SDK

  • ASP.net MVC 4 supports the Newer release of the Windows Azure SDK 2.0

Feature 8 : Database Migrations

  • ASP.net MVC 4 projects now include Entity Framework 5
  • One of the great features in Entity Framework 5 is support for database migrations
  • This feature enables you to easily evolve your database schema using a code-focused migration while preserving the data in the database

Feature 9 : Bundling and Minification

  • The bundling and minification framework enables you to reduce the number of HTTP requests
  • That a Web page needs to make by combining individual files into a single,
  • Bundled file for scripts and CSS
  • It can then reduce the overall size of those requests by minifying the contents of the bundle

What is Minifying ?
  • Minifying can include activities like eliminating white space to shortening variable names to even collapsing CSS selectors based on their semantics

How to Handle Bundles ?
  • Bundles are declared and configured in code and are easily referenced in views via helper methods
  • Which can generate either a single link to the bundle or,
  • When debugging, multiple links to the individual contents of the bundle

Feature 10 : Enabling Logins from Facebook and Other Sites Using OAuth
                            and OpenID

  • The default templates in ASP.net MVC 4 Internet Project template now includes support forOAuth and OpenID login using the DotNetOpenAuth library
  • It's on App_Start ==> AuthConfig.cs File


Do You Have Any Problem or Things to Share about ASP.net MVC 4 ?

MVC 4 on Linkedin



Conclusion
  • You can see that lots of new and awesome features have been added to the ASP.net MVC4
  • So, use them and enjoy it

I hope this helps to You.Comments and feedback greatly appreciated.

If you feel it was a good article,Give me a +1.Thank You.