Showing posts with label Twitter. Show all posts
Showing posts with label Twitter. Show all posts

Convert Linq Entity Query into T-SQL

Convert Linq Entity Query into T-SQL


Why Should We Convert ?

1. We all know we are better T-Sql professionals than quite new Entity framework.So by converting entity query into T-Sql we can understand the job we want to do by using Entity query is happening.

2. We can use generated T-Sql query to identify the Index Keys for tables which are needed for gain more performance.(as a input for Database Engine Tuning Adviser- my next blog-post will explain how to do)

3. By studying those generated T-Sql we can improve our Entity query for better performances (using SQL Server Execution Plans etc.).

How To Do That?

Method 1 :

You can use LINQPad.It's Free http://www.linqpad.net/
(Note: my next blog-post will explain how to configure LinqPad with Visual Studio )


Method 2 :

You can use SQL Server Profiler inside the Sql Server (Tools --> SQL Server Profiler)



Method 3 :

You can use Visual Studio Debugger for Generate T-Sql.(with any visual studio version)


Note: One thing I need to mention here is After request the data from Database Server by using FirstOrDefault() , ToList() ,etc then you cannot use above method.So you have to investigate T-Sql Before calling it to the Database server (the way I showed in above image).

Conclusion
You can use one of the above method to investigate the T-Sql generation from EF Query Without using High Paid 3rd party tools or Visual Studio Ultimate edition.
Continue Reading

Use Entity Framework SelectMany

Use Entity Framework SelectMany

What is SelectMany ?

1. SelectMany Operator is part of the projection query operator supported by Linq.

                        What is Projection ?
                                  - operation of transforming an object into a new form that often consists
                                      only of those properties that will be subsequently used
                                  - e.g:  select , SelectMany

2. SelectMany operator is mainly used for flattening out the hierarchy of collections into one single
    collection of objects.

3. It merges each item into a Single Sequence that gets returned by the query results.

Let's Try with Working Example.

Scenario 1: 

Linq to Object

I have created a Console application like below by using visual studio 2010.

Entity Framework Method Based Syntax

 public class Program
    {
        static void Main(string[] args)
        {
            var fruits = new List<string>() { "Orange Apple Peach Plum Banana" };

            var query = fruits.SelectMany(f => f.Split(' '));

            foreach (string s in query)
              {
                   Console.WriteLine(s);
               }
         }
    }

Result










Entity Framework Query Based Syntax

We can write above code as below for giving Same Result as above.

public class Program
    {
        static void Main(string[] args)
        {
            var fruits = new List<string>() { "Orange Apple Peach Plum Banana" };

            var query = from f in fruits
                              from word in f.Split(' ')
                              select word;

              foreach (string s in query)
              {              
                 Console.WriteLine(s);
              }
       }
    }

Note The Result of the above query is Exactly the Same,but the Query Based Syntax is much
               easier to follow and more readable.


Scenario 2: 

Linq To SQL

You can use SelectMany  with Linq To SQL as below.

Models

  public class Appointment 
    {
        public string AppointmentId { get; set; }
public virtual Provider Provider { get; set; }
public virtual IList<Allocation> Allocations { get; set; }
    }

   public class Allocation 
     {
       public Guid AllocationId { get; set; }
       public virtual Appointment Appointment { get; set; }
     }

  public class Provider
    {
       public Guid Id { get; set; }
       public string Key { get; set; }
       public virtual ICollection<Appointment> Appointments { get; set; }
    }

Entity Framework Method Based Syntax


 public Allocation GetAllocationDetails(string providerKey, Guid allocationId)
        {
            var catalog = new DataCatalog();

            var allocation =
                (catalog.Appointments.Where(a => a.Provider.Key == providerKey)
                .SelectMany(l => l.Allocations.Where(b => b.AllocationId == allocationId)))
                .FirstOrDefault();

            return allocation;
        }


Entity Framework Query Based Syntax

    public Allocation GetAllocationDetails(string providerKey, Guid allocationId)
        {
            var catalog = new DataCatalog();

            var allocation = (from a in catalog.Appointments
                                    where a.Provider.Key == providerKey
                                    from l in a.Allocations
                                    where l.AllocationId == allocationId
                                    select l).FirstOrDefault();

            return allocation;
        }

Both methods are giving Same Result as below.


Conclusion
  • So in Linq there are 2 ways to write queries.
  • One is Query Based Syntax and other is Method Based Syntax.
  • Who is coming from T-Sql environment are more familiar with Query Based Syntax.Its easy to understand and readability is high.
  • Method Based Syntax is suitable for more advance users who is having very good knowledge about Entity frame work Extension methods.
  • But both are giving Same Result at the end.

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

Create a Custom Action Filter for MVC 3

Create a Custom Action Filter for MVC 3

What is an Action Filter ?
  • It's an Attribute
  • Could be applied on a particular Action
  • Could be applied on a Controller
  • It modifies the way Action Executes
  • An Action Filter is a class that inherits from the FilterAttribute base class
  • Filters are used to inject an extra logic into the MVC request processing
  • Filters to define logic which is used to apply add-on functionality to the application
  • e.g. defining Authorization, Caching, Logging, Exception etc.

What are the Types of Action Filters ?




















What is 1-2-3-4 ?
  • If an Action Method has more than One Action Filter applied,
  • Then the order in which they are executed
  • i.e. Action Filters are Executed in the order 1-2-3-4 
  • Firstly Executes Authorization Filters
  • Lastly Executes Exception Filters

What is an Authorization Filter ?
  • These filters are always run first before any other filters
  • They implement IAuthorizationFilter interface
  • Provides AuthorizeAttribute as the default class implementation
How to Do That ?
MyAuthorizationFilterAttribute.cs

using System.Web.Mvc;

namespace CustomActionFilter.CustomActionFilters
 {
 public class MyAuthorizationFilterAttribute:FilterAttribute,IAuthorizationFilter
  {
      public void OnAuthorization(AuthorizationContextfilterContext)
      {
          if(filterContext.HttpContext.Request.IsAuthenticated)
          {
              //The action filter logic
          }
      }
  }
}

HomeController.cs
using System.Web.Mvc;
using CustomActionFilter.CustomActionFilters;
namespace CustomActionFilter.Controllers
{
    public class HomeController: Controller
    {
        [MyAuthorizationFilter]
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";
            returnView();
        }
    }
}


What is an Action Filter ?
  • It Implements IActionFilter interface
  • It Executes before and after action result is executed
  • Provides ActionFilterAttribute as the default class implementation

How to Do That ?

MyActionFilterAttribute.cs

using System.Web.Mvc;
namespace CustomActionFilter.CustomActionFilters
{
    public class MyActionFilterAttribute: FilterAttribute, IActionFilter
    {
        public void OnActionExecuting(ActionExecutingContextfilterContext)
        {
            //The action filter logic - before
        }
        public void OnActionExecuted(ActionExecutedContextfilterContext)
        {
            //The action filter logic - after
        }
    }
}
HomeController.cs

using System.Web.Mvc;
using CustomActionFilter.CustomActionFilters;
namespace CustomActionFilter.Controllers
{
    public class HomeController: Controller
    {
        [MyActionFilter]
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";
            returnView();
        }
    }
}
What is a Result Filter ?
  • It Implements IResultFilter interface
  • It Executes before and after action result is executed

How to Do That ?
MyResultFilterAttribute.cs

using System.Web.Mvc;
namespace CustomActionFilter.CustomActionFilters
{
    public class MyResultFilterAttribute: FilterAttribute, IResultFilter
    {
        public void OnResultExecuting(ResultExecutingContextfilterContext)
        {
            //The action filter logic - before
        }
        public void OnResultExecuted(ResultExecutedContextfilterContext)
        {
            //The action filter logic - after
        }
    }
}
HomeController.cs
using System.Web.Mvc;
using CustomActionFilter.CustomActionFilters;
namespace CustomActionFilter.Controllers
{
    public class HomeController: Controller
    {
        [MyResultFilter]
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";
            returnView();
        }
    }
}

What is an Exception Filter ?
  • It Implements IExceptionFilter interface
  • It Executes only if exception is thrown by action method or an action result
  • Provides HandleErrorAttribute as the default class implementation

How to Do That ?
MyExceptionFilterAttribute.cs

using System.Web.Mvc;
namespace CustomActionFilter.CustomActionFilters
{
    public class MyExceptionFilterAttribute: FilterAttribute, IExceptionFilter
    {
        public void OnException(ExceptionContextfilterContext)
        {
            if(filterContext.Exception != null)
            {
                //The action filter logic
            }
        }
    }
}
HomeController.cs
using System.Web.Mvc;
using CustomActionFilter.CustomActionFilters;
namespace CustomActionFilter.Controllers
{
    public class HomeController: Controller
    {
        [MyExceptionFilter]
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";
            returnView();
        }
    }
}
Note :

  • I have used VS 2010 with Asp.Net MVC 3 and C# for develop above code samples.

CustomActionFilter's Project Tree is as below :
Finally, the HomeController with All the Custom Action Filters are as below :
using System.Web.Mvc;
using CustomActionFilter.CustomActionFilters;
namespace CustomActionFilter.Controllers
{
    public class HomeController: Controller
    {
        [MyAuthorizationFilter]
        [MyActionFilter]
        [MyResultFilter]
        [MyExceptionFilter]
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";
            returnView();
        }
    }
}
That's It.You're Done. 

Do you need to Download this Sample Project ?


Conclusion
  • Action Filters allow you to do some extra pre or post processing to be carried out,in addition to the code written in the action methods
  • Depending on your need you can implement IAuthorizationFilter, IActionFilter, IResultFilter or IExceptionFilter interfaces to make your filter an Authorization filter, Action filter, Result filter or Exception filter respectively
  • These interfaces decide the order in which the action filters are executed
  • Which makes your application more flexible and maintainable


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

Use Twitter Bootstrap with Asp.Net MVC 3

How to use Twitter Bootstrap with Asp.Net MVC 3 ?

What is Twitter Bootstrap (TB) ?
  • TB is a Free (open source) collection of tools for creating web applications
  • It contains HTML and CSS-based design templates for typography, forms, buttons, charts, navigation and other interface components
  • As well as optional JavaScript extensions
  • TB has supported for HTML5 and CSS 3
  • It is compatible with all major browsers
  • It also supports Responsive Design
           - This means the graphic design of web pages adjusts dynamically, taking into account
              the characteristics of the device used (PC, tablet, mobile phone)


How to Download Twitter Bootstrap ?


Step 1 :


Step 2 : 
  • After unzip the content,You will have below mentioned folders
  • CSS folder's content is as below

  • IMG folder's content is as below

  • JS folder's content is as below

How to create Asp.Net MVC 3 project using Visual Studio 2010 ?
Step 1 :  Click,  File ==> New Project
Step 2 :  Select, Internet Application Template
Step 3 :  MVC 3 Internet Application Template generated Solution Explore is as below
How to add Twitter Bootstrap UI Framework for Asp.Net MVC 3 project ?
css and img :
  • Create a folder named "bootstrap" under the Content folder
  • Create 2 sub-folders named "css" and "img" under that
  • Add the .css files into css folder and .png files into img folder
Note: The framework assumes that the .png images are located under a folder
           named "img" under the parent folder of the folder in which the .css files are located  
scripts :
  • Create a folder named "bootstrap" under the Scripts folder
  • Add the bootstrap javaScript files into it

After that solution explore looks like below


Let's try to add Bootstrap effects into our Asp.net MVC project

How to Add the Bootstrap CSS ?
  • Open the _Layout.cshtml page
  • Add the following 2 lines in the head tag at the end of its existing content
  • You don't need to remove any of its existing content   
  • You need to make sure that bootstrap-responsive.min.css appears after the bootstrap.min.css 

<head>
<link href="@Url.Content("~/Content/bootstrap/css/bootstrap.min.css")"
      rel="stylesheet" type="text/css" />
<link href="@Url.Content("~/Content/bootstrap/css/bootstrap-responsive.min.css")"
      rel="stylesheet" type="text/css" />
</head>

How to Add Bootstrap JavaScript ?
  • It is a good practice to add the JavaScript files at the end of the page content
  • Add the following line at the end of the _Layout.cshtml file before ending the body tag

<script src="@Url.Content("~/Scripts/bootstrap/bootstrap.min.js")"
        type="text/javascript"></script>

Let's add some Twitter Bootstrap css styles for our Asp.Net MVC UIs

Site.css
  • Open the Site.css file
  • Look for the "header h1, #header h1" styled item
  • Replace it with the following code block   

header h1, #header h1
{
    font-weight: normal;
    padding: 5px 0;
    margin: 0;
    color: #5c87b2;
    border: none;
    line-height: 2em;
    font-size: 20px !important;
    text-shadow: 1px 1px 1px #111;
}

  • Look for #logindisplay, #logindisplay a:link, #logindisplay a:visited and #logindisplay a:hover styled items
  • Change the color property to #555 instead of white
  • Replace it with following code block   
#logindisplay
{
    font-size: 1.1em;
    display: block;
    text-align: right;
    margin: 10px;
    color: #555;
}
#logindisplay a:link
{
    color: #555;
    text-decoration: underline;
}
#logindisplay a:visited
{
    color: #555;
    text-decoration: underline;
}
#logindisplay a:hover
{
    color: #555;
    text-decoration: none;
}

Let's Modify Body 
  • Open _Layout.cshtml page
  • Replace it with following code block  

_Layout.cshtml (complete code)

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>@ViewBag.Title</title>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet"
      type="text/css" />
<link href="@Url.Content("~/Content/bootstrap/css/bootstrap.min.css")"
      rel="stylesheet" type="text/css" />
<link href="@Url.Content("~/Content/bootstrap/css/bootstrap-responsive.min.css")"
      rel="stylesheet" type="text/css" />
</head>

<body>
    <div class="container-fluid">
        <div id="header" class="row-fluid">
            <div id="title">
                <h1>
                    My MVC Application</h1>
            </div>
            <div id="logindisplay">
                @Html.Partial("_LogOnPartial")
            </div>
        </div>
        <div id="" class="row-fluid">
         <div class="navbar">
           <div class="navbar-inner">
             <div class="container-fluid">
               <div class="nav-collapse">
                 <ul class="nav">
                   <li class="@(ViewBag.Active == "Home" ? "active" : "")">
                       @Html.ActionLink("Home", "Index", "Home")
                    </li>
                    <li class="divider-vertical"></li>
                    <li class="@(ViewBag.Active == "About" ? "active" : "")">
                       @Html.ActionLink("About", "About", "Home")
                    </li>
                  </ul>
               </div>
             </div>
          </div>
         </div>
        </div>
      <div id="" class="row-fluid">
         @RenderBody()
      </div>
      <div id="footer" class="row-fluid">
      </div>
    </div>

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js">
           </script>
    <script src="@Url.Content("~/Scripts/bootstrap/bootstrap.min.js")"
            type="text/javascript"></script>
</body>
</html>
Let's Modify Home Page
  • Open Index.cshtml page
  • Replace it with following code block 

Index.cshtml (complete code)
@{
    ViewBag.Title = "Home Page";
    ViewBag.Active = "Home";
}
<div class="hero-unit">
    <h2>@ViewBag.Message</h2>
    <p>
        This is a template to demonstrate the way to beautify the default
        MVC3 template using Twitter Bootstrap website. It is pretty
        simple and easy.
    </p>
    <p>
        <a href="http://asp.net/mvc" class="btn btn-primary btn-large"
           style="color: White;">
         To learn more about ASP.NET MVC visit &raquo;</a>
    </p>
</div>
Let's Modify About Page
  • Open About.cshtml page
  • Replace it with following code block 

About.cshtml (complete code)
@{
    ViewBag.Title = "About Us";
    ViewBag.Active = "About";
}
<div class="row-fluid">
    <div class="span4">
        <h2>
            About 1</h2>
        <p>
            Your About 1 details.Your About 1 details.Your About 1 details.
            Your About 1 details.Your About 1 details.Your About 1 details.
            Your About 1 details.Your About 1 details.Your About 1 details.
        </p>
        <p>
            <a class="btn" href="#">View details &raquo;</a></p>
    </div>
    <div class="span4">
        <h2>
            About 2</h2>
        <p>
            Your About 2 details.Your About 2 details.Your About 2 details.
            Your About 2 details.Your About 2 details.Your About 2 details.
            Your About 2 details.Your About 2 details.Your About 2 details.
        </p>
        <p>
            <a class="btn" href="#">View details &raquo;</a></p>
    </div>
    <div class="span4">
        <h2>
            About 3</h2>
        <p>
            Your About 3 details.Your About 3 details.Your About 3 details.
            Your About 3 details.Your About 3 details.Your About 3 details.
            Your About 3 details.Your About 3 details.Your About 3 details.
        <p>
            <a class="btn" href="#">View details &raquo;</a></p>
    </div>
</div>


That's it.You're done.

  • Now the Asp.net MVC 3 project with Twitter Bootstrap Template should look like below

Home page (portion)
About page (portion)

Do you need to Download This Sample Project ?


Do you need to dive deep ends of  Twitter Bootstrap ?


Conclusion
  • Bootstrap is a Toolkit from Twitter designed to kick-start development of web-apps and sites
  • You can design highly professional and more sophisticated web sites with minimum effort by using Bootstrap
  • It is Tested and supported in the major modern browsers, such as the Latest versions of Safari, Google Chrome, Firefox 5+, and Internet Explorer 7+
  • With Bootstrap 2.0 and later, Mobile browsers are also supported
  • So Try to use TB with your web projects and Enjoy it 

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


Happy Coding.
Continue Reading