Monday, September 29, 2014

Attribute Based Routing


Developers who are working on MVC applications are familiar with the word called “Route” or Route table.  A Route is the URL specifying any access or Resource and “Routing” is the way of matching any action to URL. Earlier the Route needs to be added on the Route table and inside the RouteConfig.cs we have to call it. A typical Route was written like this.

routes.MapRoute(
name: "ItemPage",
url: "{itemId}/{itemTitle}",
defaults: new { controller = "Items", action = "Show" },
constraints: new { itemId = "\\d+" }
);      

In MVC 5 there is a new way of defining Rote is added called “Attribute Based Routing”, as the name clearly suggest that the routes are added just like any other attribute in MVC. This does not mean that the conventional based routing the old style is not supported it’s still there.

Now the earlier way of defining rotes were involved in the external routes files with exact controller and action method name. In the attribute based routing the routes are defined directly inside the controls action methods name thus it becomes easier to identify the routes and to the no of lines required to create a route is become a single line only.  We can write the above Rote in the easier way as  

[Route("{itemId:int}/{itemTitle}")]
public ActionResult ShowItem(int itemId)
{
  // Ur code goes here
}

Isn’t it easy? Yes it is, to enable attribute based routing we need to do some change in the Route.config file as follows. Use MapMvcAttributeRoutes as below. 

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");                    

routes.MapMvcAttributeRoutes();
}
} 

The same can also be called inside the RegisterRoute methods with the other conventional routes. So now every method present inside a controller can have its own routes in the form of attribute. Or else if we want that some prefix to be fixed for all the action method present inside a controller then we can define it at the controller level like below.

[RoutePrefix("Sample")]
public class SampleController : Controller
{
// eg.: /sample/Index
public ActionResult Index()
{
         return View();
}

// eg.: /sample/About
public ActionResult About ()
 {
    return View();
  

By this all the Rotes will have a default prefix as “ Sample”. Hope you all have got idea that how to Use Attribute based routing and how to use a default prefix.  Now I will show that if there are some default prefix is set at a controller level but still if I want to override any of the default route then how can we do it.  For doing this we have to again call a specified rote with the Route attribute above the action method where we want to use it with a tilde (~) symbol. For example please check the below sample.

[RoutePrefix("Sample")]
public class SampleController : Controller
{
// eg.: /sample/Index
public ActionResult Index()
{
    return View();
}

// eg.: /sample/About
[Route(“~/Newsample/About”)]
public ActionResult About ()
 {
return View();
 }


Hope you have got idea that how to override the prefix for any specific action method.  Any The Same way we can specify the “Optional Parameter” for any route. Marking a optional parameter is very simple in attribute based routing as we simply need to add one Question mark (?) in the route as below.

public class HomeController : Controller
{
      [Route("home/{id?}")]
      public ActionResult Employee(int id)
      {
           ViewBag.Message = "This is Home Index Page";
           return View();
      }
}

This was simple. Hope You all have liked this article. On the Next article I will discuss about how to use Constraints in the Attribute based Routing. Please feel free to provide your valueable comment on this so that  I can improve more on it.

Thanks & Regards
Anil Kumar Pandey
Microsoft MVP, Microsoft MCC, DNS MVM


 

Tuesday, September 23, 2014

Control Template and Templated Parent

Hi Friends,

Recently I was discussing some WPF stuff with one of my friends and  we come up with this Nice article  Here we are going to discuss about creating a Control template and how the communication between them is done.  This is quite useful and 
important to understand the Control template, this will make the life easy by reusing the same template for multiple time if required in the same application.  

By Theory The definition of Control Template is  "Specifies the visual structure and behavioral aspects of a Control that can be shared across multiple instances of the control. Mean we will set the behavior of the controls once and the same will be applied where ever we will use this. Like We want to create a Control or lets say Button like this.





The standard WPF controls all come with default templates that produce the default control
appearances. You can, however, replace those templates with ones of your own design, giving the controls an entirely different appearance. Here is an example of that. Let’s create a sample button


<StackPanel>
  <Button FontWeight="Bold" Click="myButton Click" Name="myButton">
     Click Me
  </Button>
</StackPanel>
private void myButton Click( object sender, RoutedEventArgs e )
{
    MessageBox.Show( "Button Clicked", "Button Message" );
}


To illustrate these concepts, I’ll start with a simple button that uses the default Button template and then replace its control template. The following is the markup that produces a standard button


<StackPanel>
<Button FontWeight="Bold" Click="myButton Click" Name="myButton">
    Click Me
</Button>
</StackPanel>


The next thing I want to do is to create a control template and substitute it for the default Button template. The appearance I want for the button consists of a Border containing a TextBlock


<Window.Resources>
        <ControlTemplate x:Key="myButtonTemplate" >
            <Border Padding="5" Background="AliceBlue" BorderBrush="Green"
                    BorderThickness="5" HorizontalAlignment="Center"
                    CornerRadius="5">
                <TextBlock Text="Control Templates Content"></TextBlock>             
            </Border>        
        </ControlTemplate>
    </Window.Resources>

---------------------------------------------------------------------------------------------------------------------
<StackPanel>
        <Button FontWeight="Bold" Template="{StaticResource myButtonTemplate}"
                Click="Button_Click" Content="Buttons Content1" Name="myButton">       
        </Button>
 </StackPanel>

Let’s run this

It will show Control Template Content. it will not show Buttons content.

To show the Buttons content we need to make following changes
  1. Set the TargetType attribute of the ControlTemplate to Button, as shown in the  following markup line:  
  2. Replace the TextBlock object, which produces the specific output string, with a ContentPresenter object.

To accomplish this, I need to use an object that can retrieve the Content from the templated parent and display that content. The class designed to do this is the ContentPresenter class. To use this, I needed to make two changes to the template declaration they generate the presentation of content to the user interface
The following are some important things to know about the ContentPresenter class:
  1. • The ContentPresenter object acts as a placeholder inside the template to specify where the content should be placed.
  2. • By default, the ContentPresenter gets the actual content from the templated parent and binds it to its own Content property. As a matter of fact, the ContentPresenter doesn’t event allow direct content of its own.
  3. • To use a ContentPresenter, you must set the TargetType attribute of the ControlTemplate to the type of the templated parent.

Template Binding

There are times, however, when you might want the ContentPresenter to use additional properties from the templated parent. The TemplateBinding class is a special type of binding designed for this purpose.
Now I will set the Height and width property of the Button from the Control Template, but it will read the values from the parent Button which is set as Target Type.


<ControlTemplate x:Key="myButtonTemplate" TargetType="Button">
            <Border Padding="5" Background="AliceBlue" BorderBrush="Green"
                    BorderThickness="5" HorizontalAlignment="Center" CornerRadius="5" >
                   
                   
                   <ContentPresenter Width="{TemplateBinding Width}" Height="{TemplateBinding Height}" />             
            </Border>     
        </ControlTemplate>
 <StackPanel>
        <Button FontWeight="Bold" Template="{StaticResource myButtonTemplate}"
                Click="Button_Click" Content="Buttons Content1" Name="myButton"
                Width="180" Height="40">
  </Button>
    </StackPanel>



So some of the important point is 
  1. The appearance of every control is determined by a ControlTemplate object, which specifies the tree of visual elements to be displayed to represent the control.
  2. The control object represented by its visual tree is called the templated parent.
  3. The visual tree of a program consists of the tree comprising the templated parents  and their visual trees.
  4. Inside a ControlTemplate, you can use a ContentPresenter object to display the  Content property of the templated parent.
  5. You can use a template binding to read and use other dependency property values  from the templates parent.
This Article is also published on Technet by one of my Best friend Hemant.  You can Also refer this Here.  "Control Template ". Please provide your thoughts and idea on Control template and or in WPF.


Thanks & Regards
Anil Kumar Pandey
Microsoft MVP, Microsoft MCC, DNS MVM






One ASP.NET

With  Visual Studio 2013, the Application or  project type to choose for creating a web application is not there. There is now only one web project type in Visual Studio. Called ASP.net Web application




Now Once you select this You will come up with multiple option to select with. This is simply give a feeling that every thing is combined to one. There are sub option which you are choose as per your requirement.


Here You can see multiple Sub project option or the ready made scaffolding.

Empty :         Template will come with a project solution on .

Web form :    For traditional Web Form application.

MVC :           Scaffolding for MVC application with inbuilt folders of Model, View and controller.

Web API:       Scaffolding for WEB API, powerful way of handling resource or service.

Single Page : For application having a single page it can be a static or dynamic page but with a single page.

Facebook:    Scaffolding for social networking application like Facebook. 

Now  for this Entire application structure we can have a single authentication option this can be selected suign the Authentication option available in this scaffolding  option. Check the image below.



There are multiple option are available like

No Authentication

Individual User Account

Organisation Account

Windows Authentication


Its now become a part of complete package where all the type are inbuilt a single option called ONE ASP.NET.




Hope you all have got a idea that what is One ASP.NET. Please feel free to provide your comment on the same.



Thanks & Regards
Anil Kumar Pandey
Microsoft MVP, Microsoft MCC, DNS MVM






Tuesday, July 1, 2014

New MVP for July 2014 Quarter

Hi friends,

Please join me in congratulating the Community star, who are awarded by Microsoft for their exceptional contribution towards technical community.


Re-Awardees
New Awardees
Subodh Sohoni - Visual Studio ALM
Venkata Ramesh Raju - Lync (Bangalore)
Abhimanyu Singhal - Visual Studio ALM
Alok Pandey - ASP.NET/IIS (Kathmandu)
Nishanth Anil - Visual C#
Prashant Kumar - Consumer Security (Jamshedpur)
Siddharth Rout - Visual Basic
Deepak Singh Dhami - PowerShell (Bangalore)
Santosh Bhandarkar - Directory Services
Bijaya Sahoo - SharePoint Server (Bangalore)
Ravikanth C - PowerShell
Selva Ganapathy Kathiresan - Visual C# (Chennai)
Shiju Varghese - Microsoft Azure
Kunal Chandratre - Microsoft Azure (Pune)
Vikram Pendse - Windows Development
Sumit Bansal - Excel (Ghaziabad)
Madhivanan JR - SQL Server
Anubhav Ranjan - Windows Development (Bangalore)
Manu Philip - Exchange Server
Amol Ghuge - SharePoint Server
Ashutosh Singh - SharePoint Server
Abhimanyu Vatsa - ASP.NET/IIS
Asheej Kommery - ASP.NET/IIS
Brij Bhushan Mishra - ASP.NET/IIS
Shivprasad Koirala - ASP.NET/IIS
Suprotim Agarwal - ASP.NET/IIS
Nirmal T V - Windows Consumer
Shantanu Kaushik - Windows IT Pro


A Very warm welcome to all the new Folks and Happy to see the names who are re awarded. Hope to see you soon in the community meet.

Thanks & Regards
Anil Kumar Pandey
Microsoft MVP, Microsoft MCC, DNS MVM

Kontera