Tuesday, 10 April 2018

MVC 5 Features

What’s New in ASP.NET MVC 5

Attribute Routing
This is where attribute based routing comes in. Using attribute based routing we can define the route in the same place where action method is defined.
   
[Route("Products/Electronics/{id}")]
     public ActionResult GetElectronicItems(string id)
     {
         ViewBag.Id = id;
          return View();
     }

To enable attribute based routing we need to add the following in the RouteConfig file.

      public static void RegisterRoutes(RouteCollection routes)
       {
           routes.MapMvcAttributeRoutes();
       }

Optional Parameter
We can also specify if there is any optional parameter in the URL pattern defined by the Route attribute with the “?” character.

      [Route("Products/Electronics/{id?}")]
      public ActionResult GetElectronicItems(int? id) {
          ViewBag.Id = id; return View();

      }

Route constraints
We can also specify parameter constraints placing the constraint name after the parameter name separated by colon. For example we can specify that the parameter type should be integer by using the following

[Route("Products/Electronics/{id:int}")]

Route Prefix
If we have multiple action methods in a controller all using the same prefix we can use RoutePrefix attribute on the controller instead of putting that prefix on every action method.

Like we can attach the following attribute on the controller
[RoutePrefix("Products")]

So now our Route attribute on our action method does not need to specify the common prefix
[Route("Electronics/{id}")]

Filter's in MVC
Filters in MVC provide us with an elegant way to implement cross cutting concerns.Cross cutting concerns is the functionality that is used across our application in different layers.Common example of such functionality includes caching ,exception handling and logging.

We can create global or controller filters in MVC 4.Global filters are filters that are applied to all the action methods in the application while controller filters apply to all the action methods in the controller.

We can create a global filter by creating a class and registering it as a global filter

public class TestGlobalFilterAttribute : ActionFilterAttribute
   {
       public override void OnActionExecuting(ActionExecutingContext context)
       {
           base.OnActionExecuting(context);
           context.RequestContext.HttpContext.Response.Write("Global filter's in MVC are cool...");
       }
   }

//Register our global filter
GlobalFilters.Filters.Add(new TestGlobalFilterAttribute()); 

Filter Overrides in MVC 5
Now if want to override our global action filter in one of our action method's then we just need to apply the OverrideActionFilters attribute.Below we have applied the attribute to the default About method in the HomeController.

[OverrideActionFilters]
public ActionResult About(){
ViewBag.Message = "Your application description page.";
return View();
}

Scaffolding
Scaffolding means generating code automatically from the model.Suppose we have some model for which we want to generate the skeleton code for the basic Create Read Update and Delete operations then instead writing the common code we can use Scaffolding feature of MVC 5.

Bootstrap
Twitter Bootstrap is added as the default user interface framework for an MVC application. Bootstrap is a free collection of HTML and CSS based design templates created at Twitter for designing forms, navigation, buttons, tables etc.

ASP.NET Identity

One ASP.NET

Continue Reading →

Monday, 9 April 2018

Group by and Partition by - SQL Server

Difference between Group by and Partition by

Now we will list out below difference between two

Group by 
The SQL GROUP BY clause can be used in a SELECT statement to collect data across
multiple records and group the results by one or more columns.

In more simple words GROUP BY statement is used in conjunction with the
aggregate functions to group the result-set by one or more columns.
  1. Reduces the no. of records
  2. In select we need to use only columns which are used in group by. but we can use aggregate functions.
  3. In filter condition we need to use having clause instead of where clause.
Partition By
  1. No. of records will not be reduced. Instead of that it will add one extra column.
  2. In select we can use N no. of columns. No restrictions.
  3. We can use where clause in filter condition apart from partition column.
Now we will try to learn the difference by looking into below the examples.
Take below table data which is used in the the article.

id  firstname                   lastname                    Mark
-------------------------------------------------------------------
1   arun                        prasanth                    40
2   ann                         antony                      45
3   sruthy                      abc                         41
6   new                         abc                         47
1   arun                        prasanth                    45
1   arun                        prasanth                    49
2   ann                         antony                      49
Group by Syntax: 

SELECT expression1, expression2, ... expression_n, 
       aggregate_function (aggregate_expression)
FROM tables
WHERE conditions
GROUP BY expression1, expression2, ... expression_n;
We can apply GroupBy in our table

select SUM(Mark) marksum, firstname from TableA group by id,firstName
Result: 
marksum  firstname
----------------
94      ann                      
134     arun                     
47      new                      
41      sruthy   
In our real table we have 7 rows and when we apply group by id, the server group the results based on id

In simple words
here group by normally reduces the number of rows returned by rolling them up and calculating Sum for each row.

Partition by Query: 

select SUM(Mark) OVER (PARTITION BY id) AS marksum, firstname from TableA
marksum firstname 
-------------------
134     arun                     
134     arun                     
134     arun                     
94      ann                      
94      ann                      
41      sruthy                   
47      new  
look at the results it will partition the rows and results all rows not like group by.
****************************************************************

--BELOW IS A SAMPLE WHICH OUTLINES THE SIMPLE DIFFERENCES
--READ IT AND THEN EXECUTE IT
--THERE ARE THREE ROWS OF EACH COLOR INSERTED INTO THE TABLE
--CREATE A database called testDB

--CREATE DATABASE  testDB;

-- use testDB
USE [TestDB]
GO


-- create Paints table
CREATE TABLE [dbo].[Paints](
    [Color] [varchar](50) NULL,
    [glossLevel] [varchar](50) NULL
) ON [PRIMARY]

GO

-- Populate Table
insert into paints (color, glossLevel)
select 'red', 'eggshell'
union
select 'red', 'glossy'
union
select 'red', 'flat'
union
select 'blue', 'eggshell'
union
select 'blue', 'glossy'
union
select 'blue', 'flat'
union
select 'orange', 'glossy'
union
select 'orange', 'flat'
union
select 'orange', 'eggshell'
union
select 'green', 'eggshell'
union
select 'green', 'glossy'
union
select 'green', 'flat'
union
select 'black', 'eggshell'
union
select 'black', 'glossy'
union
select 'black', 'flat'
union
select 'purple', 'eggshell'
union
select 'purple', 'glossy'
union
select 'purple', 'flat'
union
select 'salmon', 'eggshell'
union
select 'salmon', 'glossy'
union
select 'salmon', 'flat'

-------------------------------------
SELECT * FROM paints

/*   COMPARE 'GROUP BY' color to 'OVER (PARTITION BY Color)'  */

-- GROUP BY Color 
-- row quantity defined by group by aggregate (count(*)) defined by group by
select count(*) as 'count',Color from paints group by color

-- OVER (PARTITION BY... Color 
-- row quantity defined by main query aggregate defined by OVER-PARTITION BY
select color, glossLevel, count(*) OVER (Partition by color) from paints

/* COMPARE 'GROUP BY' color, glossLevel to 'OVER (PARTITION BY Color, GlossLevel)'  */

-- GROUP BY Color, GlossLevel
-- row quantity defined by GROUP BY aggregate (count(*)) defined by GROUP BY
select count(*) from paints group by color, glossLevel

-- Partition by Color, GlossLevel
-- row quantity defined by main query
-- aggregate (count(*)) defined by OVER-PARTITION BY
select color, glossLevel, count(*) OVER (Partition by color, glossLevel) from paints




Continue Reading →

WCF Concurrency

Introduction
Concurrency is the control of multiple threads active in an InstanceContext at any given time. This is controlled using the System.ServiceModel.ServiceBehaviorAttribute. ConcurrencyMode is the ConcurrencyMode enumeration.

WCF concurrency will help us to configure how WCF service instances can serve multiple requests at the same time.

There are three basic types of concurrency supported by WCF 4.0:

  1. Single Concurrency Mode
  2. Multiple Concurrency Mode
  3. Reentrant Concurrency Mode

Single Concurrency Mode
When the service is set to Single Concurrency Mode, each instance context is allowed to have a maximum of one thread processing messages at the same time. In other words, WCF will provide synchronization with the service instance and not allow concurrent calls with a synchronization lock. In short only one request will proceed at any time and the next request must wait until the first request does not proceed.

Every incoming request must try to acquire the sync lock; if no lock is found then it allows access to the service and this request makes a sync lock. When finished operations, WCF will unlock the sync lock and allow other requests to come in. 

[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single)]
public class Service1 : 
IService1{
     public string GetData(int value)
     {
          return string.Format("You entered: {0}", value);
     }
}

Multiple Concurrency Mode
When the service is set to Multiple Concurrency Mode, the service allows multiple accesses at the same time. Simply service instance is not associated with any sync lock. So that concurrent calls are allowed on the service instance. WCF does not create any queue for client messages and replays them as soon as they arrive. Each service has multiple threads processing messages concurrently. The service implementation must be thread-safe to use this concurrency mode.

With Concurrency Mode Multiple, threads can call an operation at any time. It is our responsibility to guard our state with locks. 

[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple)]
public class Service1 : 
IService1{
    readonly object ThisLock = new object();
    public string GetData(int value)
    {
        string myRetString = string.Empty;
        lock (this.ThisLock)
        {
             myRetString = string.Format("You entered: {0}", value);
        }
        return myRetString;
    }
}

Reentrant Concurrency Mode
The Reentrant concurrency mode is nothing but a modified version of the single concurrency mode. Similar to single concurrency, reentrant concurrency is associated with a service instance and also sync lock. So that a concurrent call on the same instance is never called. In other words multiple calls on the same instance is not allowed.

[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Reentrant)]
public class Service3 : 
IService1{
     public string GetData(int value)
     {
          return string.Format("You entered: {0}", value); ;
     }
}

The service instance is single-threaded and accepts reentrant calls. When the reentrant service calls out, the service state must be in a consistent state, because others could be allowed into the service instance while the service calls out.

However, if the reentrant service call to another service or a callback, and that call chain (or causality) somehow wind its way back to the service instance.

The only case where a service configured with the Single Concurrency Mode can call back to its clients is when the callback contract operation is configured as one-way because there will not be a reply message to contend for the lock.


Continue Reading →

Sunday, 8 April 2018

Abstraction in .Net

Encapsulation: Encapsulate hides variables or some implementation that may be changed so often in a class to prevent outsiders access it directly. They must access it via getter and setter methods.

Abstraction: Abstraction is used to showing what is relevant but in a higher degree(class, interface). Clients use an abstract class(or interface) do not care about who or which it was, they just need to know what it can do.

Constructor in abstract class
There's an implicit call to the base constructor prior to the derived constructor execution. Keep in mind that unlike interfaces, abstract classes do contain implementation. That implementation may require field initialization or other instance members. Note the following example and the output:

abstract class Animal
   {
       public string DefaultMessage { get; set; }

       public Animal()
       {
           Console.WriteLine("Animal constructor called");
           DefaultMessage = "Default Speak";
       }
       public virtual void Speak()
       {
           Console.WriteLine(DefaultMessage);
       }
   }

    class Dog : Animal
    {
        public Dog(): base()//base() redundant.  There's an implicit call to base here.
        {
            Console.WriteLine("Dog constructor called");
        }
        public override void Speak()
        {
            Console.WriteLine("Custom Speak");//append new behavior
            base.Speak();//Re-use base behavior too
        }
    }

Although we cannot directly construct an Animal with new, the constructor is implicitly called when we construct a Dog.

OUTPUT:
Animal constructor called
Dog constructor called
Custom Speak
Default Speak

IN Short :
Encapsulation: hiding data using getters and setters etc.
Abstraction: hiding implementation using abstract classes and interfaces etc.
Continue Reading →

Topics

ADO .Net (2) Ajax (1) Angular Js (17) Angular2 (24) ASP .Net (14) Azure (1) Breeze.js (1) C# (49) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DI (3) Dotnet (21) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (9) Lamda (3) Linq (11) Mongodb (1) MVC (48) NodeJS (7) RDLC (1) Report (1) Sql Server (29) SSIS (3) SSRS (2) UI (1) WCF (12) Web Api (10) Web Service (1) XMl (1)