Saturday, August 23, 2014

ASP.NET MVC3 Vs MVC4 Vs MVC5

ASP.NET MVC 3

  • New Project Templates having support for HTML 5 and CSS 3.
  • Improved Model validation.
  • Razor View Engine introduced with a bundle of new features.
  • Having support for Multiple View Engines i.e. Web Forms view engine, Razor or open source.
  • Controller improvements like ViewBag property and ActionResults Types etc.
  • Unobtrusive JavaScript approach.
  • Improved Dependency Injection with new IDependencyResolver.
  • Partial page output caching.

ASP.NET MVC 4

  • ASP.NET Web API, a framework that simplifies the creation of HTTP services and serving a wide range of clients. Follow to create your first ASP.NET Web API service.
  • Adaptive rendering and other look-n-feel improvements to Default Project Templates.
  • A truly Empty Project Template.
  • Based on jQuery Mobile, new Mobile Project Template introduced.
  • Support for adding controller to other project folders also.
  • Task Support for Asynchronous Controllers.
  • Controlling Bundling and Minification through web.config.
  • Support for OAuth and OpenID logins using DotNetOpenAuth library.
  • Support for Windows Azure SDK 1.6 and new releases.

ASP.NET MVC 5

Creating your first ASP.NET MVC 5 Application in 4 simple steps
  • Bootstrap replaced the default MVC template.
  • ASP.NET Identity for authentication and identity management.
  • Authentication Filters for authenticating user by custom or third-party authentication provider.
  • With the help of Filter overrides, we can now override filters on a method or controller.
  • Attribute Routing is now integrated into MVC 5.
 

Singleton Pattern

In this blog post, I will try to create an example demonstrating the usage of singleton pattern.
When:

  • for situations where you only need one and only one object to exist
  • class needs to be accessible to clients
  • class should not require any parameters for its object creation
  • if creating an object is expensive, singleton can be useful
How:
In this example, we will try to create a LoadBalancer. LoadBalancer monitors the memory, processor resources etc and then decides which server to assign a particular task to. We won't create all those details as they are not necessary for this demonstration. Instead, we will use the C# Random class to make that decision. Why we need singleton pattern in this case? Because we don't want multiple instances of LoadBalancer. There should only be one LoadBalancer who makes the decision about multiple servers. Let's take a look at the consumer code first:

static void Main(string[] args)
        {
            SingletonPatternExample();

            Console.ReadLine();
        }

        private static void SingletonPatternExample()
        {
            for (int i = 0; i < 20; i++)
            {
                LoadBalancer lb = LoadBalancer.GetLoadBalancer();
                Console.WriteLine("Task " + i + " is assigned to " + lb.Server);
                System.Threading.Thread.Sleep(1000);
            }
        }
In this code, I just have a simple for loop to imitate tasks coming in. For every task, we get the LoadBalancer object and assign the Server to it randomly. For this example, you can argue that we could have achieved the same result by declaring the LoadBalancer object outside the for loop. That is true, but that is not the point of this demo. The point here is that singleton pattern is proactively stopping any new instances being created. Let's take a look at the LoadBalancer class now.

sealed class LoadBalancer
    {
        // Static members are lazily initialized. 
        // .NET guarantees thread safety for static initialization 
        private static readonly LoadBalancer instance = new LoadBalancer();

        private ArrayList servers = new ArrayList();
        private Random random = new Random();

        // Note: constructor is private.
        private LoadBalancer()
        {
            // List of available servers 
            servers.Add("Server 1");
            servers.Add("Server 2");
            servers.Add("Server 3");
            servers.Add("Server 4");
            servers.Add("Server 5");
        }

        public static LoadBalancer GetLoadBalancer()
        {
            return instance;
        }

        // Simple, but effective load balancer 
        public string Server
        {
            get
            {
                int r = random.Next(servers.Count);
                return servers[r].ToString();
            }
        }
    } 
The class is sealed so that it can not be inherited. Then we define a LoadBalancer instance as private and as static. If you don't define it a static then its not thread-safe. The class also has an ArrayList of servers and a Random object. The class also has a private constructor which just adds the servers to the ArrayList. Private constructor makes sure that class can not be initialized outside the scope. The GetLoadBalancer() method returns the one and only instance. There is no other way to get hold of this instance. And lastly, the simple Server property does the main work of finding out a Server and then notifying it to the caller.
Here are the results:

Factory Pattern

In this blog post, I will try to create a simple program which will demonstrate the utility and significance of the factory pattern.
When:

  • when many classes are implementing an interface and you are unsure about which concrete implementation to return
  • when you want to separate creation logic from the object's main goal like when creating an object if you want to assign values to many properties and you want to separate this kinda logic from object's main functionality
  • if there are many if-else or switch statements for deciding which object to create
Why:
  • to encapsulate the creation of object
  • to separate the creation of object from the decision about which object to create
  • to allow adding new objects without breaking open closed principle (classes should be open for extension, closed for modification)
  • to allow (if needed) storing which objects to create in a separate place like database or configuration
How:
Let's create an example to see how factory pattern works. Let's say that we have a consumer which wants to perform search. The consumer doesn't care about which actual search engine does the search, as long as it can perform the search. From a factory perspective, we have multiple search providers and we want some kind of configuration to switch the providers. Let's take a look at the consumer code first.
class Program
{
        static void Main(string[] args)
        {
            ISearchEngineFactory factory = LoadFactory();

            ISearchEngine engine = factory.CreateMapSearchEngine();
            engine.Search();

            engine = factory.CreateNormalSearchEngine();
            engine.Search();

            Console.ReadLine();
        }

        private static ISearchEngineFactory LoadFactory()
        {
            string factoryName = Properties.Settings.Default.SearchFactory;
            return Assembly.GetExecutingAssembly().CreateInstance(factoryName) as ISearchEngineFactory;
        }
    }
In this code, first we create a factory by calling the LoadFactory() method. This method looks into the settings file to see which factory to load and then by using reflection creates an instance of that factory. The ISearchEngineFactory defines two methods as shown below: one for normal search and the other for map search.
public interface ISearchEngineFactory
{
        ISearchEngine CreateNormalSearchEngine();

        ISearchEngine CreateMapSearchEngine();
    }
In this example, we are defining two search engines: Google and Bing. So, first up, we create 2 factories for them as shown below:
public class GoogleFactory : ISearchEngineFactory
{
        public ISearchEngine CreateNormalSearchEngine()
        {
            return new Google() as ISearchEngine;
        }

        public ISearchEngine CreateMapSearchEngine()
        {
            Google g = new Google {Context = "Maps"};
            return g as ISearchEngine;
        }
    }
public class BingFactory : ISearchEngineFactory
{
        public ISearchEngine CreateNormalSearchEngine()
        {
            return new Bing() as ISearchEngine;
        }

        public ISearchEngine CreateMapSearchEngine()
        {
            return new BingMaps() as ISearchEngine;
        }
    }
In this example, we are also demonstrating, how the actual object creation can be different. The Bing engine returns Bing object for normal searches and BingMaps object for map searches. The Google engine for normal search, just returns the Google object with context as null. For maps search, it returns the normal google object with Context set as "Maps". All of these engines, implement the ISearchEngine interface which has a Search method and a context property as shown below.
public interface ISearchEngine
{
        void Search();

        string Context { get; set; }
    }
public class Bing : ISearchEngine
{
        public void Search()
        {
            Console.WriteLine("You searched on Bing");
        }

        public string Context { get; set; }

    }
public class BingMaps : ISearchEngine
{
        public void Search()
        {
            Console.WriteLine("You searched on Bing Maps");
        }

        public string Context { get; set; }
    }
public class Google : ISearchEngine
{
        public void Search()
        {
            string str = "You searched on Google";

            if (string.IsNullOrEmpty(Context))
                Console.WriteLine(str);
            else
                Console.WriteLine(str + " " + Context);
        }

        public string Context { get; set; }
    }
When you run this app, with search provider set as Google, you see the following output.



And if you go to settings page and change the settings configuration to use Bing as the search provider, the output is as below:




Once we have set up the factory pattern in our code, we can easily add newer factories and newer search engine classes without affecting any of the other classes, hence respecting the Open-Closed principle. Once that is done, you can easily change the configuration to point to say Yahoo factory and the factory pattern will take care of correct object creations.

LINQ Examples

In this blog, I will try to create samples of LINQ extension methods which are very helpful in accomplishing things which earlier would take 10-15 lines (or more) of code and were difficult to manage as well as to understand. I will also try to keep this blog as a running list of good LINQ extension methods.
First up, let's see the whole code listing. For my data, I have created a simple SportsPerson class and have populated with arbitrary values.

public class A07LinqExamples
    {
        public static void Run()
        {
            ToLookupExample();

            ToDictionaryExample();
        }

        private static void ToDictionaryExample()
        {
            Console.WriteLine("\n---------ToDictionaryExample-----------------");
            var sportsPersons = LoadSportsPerson();

            // get a dictionary with id as id and value as SportsPerson
            var sportsPersonDict = sportsPersons.ToDictionary(sp => sp.Id, sp => sp);

            // get sportsperson with id 8
            var val = sportsPersonDict[8];
            Console.WriteLine(val.Name + "(" + val.Sport + ")");
        }

        public static void ToLookupExample()
        {
            Console.WriteLine("\n---------ToLookupExample-----------------");
            var sportsPersons = LoadSportsPerson();

            // get a lookup with id as sport and value as list of SportsPerson
            var sportsPersonsCategorized = sportsPersons.ToLookup(sp => sp.Sport, sp => sp);

            // get all sportsperson who play cricket
            foreach (var lkup in sportsPersonsCategorized["Cricket"])
                Console.WriteLine(lkup.Name);
        }

        private static IEnumerable LoadSportsPerson()
        {
            return new List()
                       {
                           new SportsPerson() {Id = 1, Name = "Sachin Tendulkar", Sport = "Cricket"},
                           new SportsPerson() {Id = 10, Name = "Roger Federer", Sport = "Tennis"},
                           new SportsPerson() {Id = 8, Name = "Rafael Nadal", Sport = "Tennis"},
                           new SportsPerson() {Id = 6, Name = "Pete Sampras", Sport = "Tennis"},
                           new SportsPerson() {Id = 5, Name = "Andre Agassi", Sport = "Tennis"},
                           new SportsPerson() {Id = 4, Name = "Brian Lara", Sport = "Cricket"},
                           new SportsPerson() {Id = 7, Name = "Glenn McGrath", Sport = "Cricket"},
                           new SportsPerson() {Id = 3, Name = "Michael Jordan", Sport = "Basketball"},
                           new SportsPerson() {Id = 9, Name = "Magic Johnson", Sport = "Basketball"},
                           new SportsPerson() {Id = 2, Name = "Steve Nash", Sport = "Basketball"}
                       };
        }
    }

    public class SportsPerson
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Sport { get; set; }
    }
ToDictionary
ToDictionary creates a key-value pair from an IEnumerable where all the keys have to be unique. The inputs that you have to provide are obviously the key and the value.

ToLookup
Many a times there is a need to create a lookup structure with some kind of grouping. For example, in our case, we want all sports persons to be categorized based on the sports they play. Lookup provides a simple key-value pair approach where the key can be the sports category and value can be all the sportsperson that belong to that sport. This is very different than dictionary. In a dictionary the key has to be unique. In Lookup keys can be the same.

Result

Simple jQuery getJSON Example in ASP.NET MVC

In this post, I will create a very basic and simple example demonstrating jQuery's getJSON method using ASP.NET MVC.

First up, I create an empty MVC project with one Controller. The code for this controller is shown below. For simplicity, the data model is also stored here and we create the data on fly. In a production application, this will be separated using multiple layers and the data, of course, would come from the database.
public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public JsonResult GetJsonData()
        {
            var persons = new List
                              {
                                  new Person{Id = 1, FirstName = "F1", 
                                      LastName = "L1", 
                                      Addresses = new List
{ new Address{Line1 = "LaneA"}, new Address{Line1 = "LaneB"} }}, new Person{Id = 2, FirstName = "F2", LastName = "L2", Addresses = new List
{ new Address{Line1 = "LaneC"}, new Address{Line1 = "LaneD"} }}}; return Json(persons, JsonRequestBehavior.AllowGet); } } public class Person { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public List
Addresses { get; set; } } public class Address { public string Line1 { get; set; } public string Line2 { get; set; } public string ZipCode { get; set; } public string City { get; set; } public string State { get; set; } public string Country { get; set; } }
This controller has just 2 actions. The Index action has a view associated with it and that view contains a button which will fire a JSON request. That request would be handled by the GetJsonData action method. As you can see, our data model is pretty simple and it contains a list of persons and each person can have multiple addresses.
The Index view contains just a button and an empty div tag in the beginning. The javascript code block contains the click handler for this button. When this button is clicked, we use the getJSON method to call the GetJsonData action. Once this data is returned we use the .each() jQuery method to loop through each person and then through each address and append some of their properties to the div tag. Code for Index view and the output when we click on the button is shown below.
<input id="btnGetPersons" type="button" value="Get Persons" />
<div>
    <div id="ajaxDiv">
    </div>
</div>
<script type="text/javascript">
    $(document).ready(function () {
        $('#btnGetPersons').click(function () {
            $.getJSON("/Home/GetJsonData", null, function (data) {
                var div = $('#ajaxDiv');
                div.html("
 " + "Persons received from server: " + "
");
                $.each(data, function (i, item) {
                    printPerson(div, item);
                });
            });
        });
    });

    function printPerson(div, item) {
        div.append("
" + "FName: " + item.FirstName + ", LName: " + item.LastName);
        $.each(item.Addresses, function (i, addr) {
            printAddress(div, addr);
        });
    }

    function printAddress(div, item) {
        div.append("
" + "   " + "Line1: " + item.Line1);
    }
</script>
The output looks like:
In the getJSON method we can pass parameters as well. For ex, if we had to pass the number of persons to retrieve, we could have passed something like {count:"5"} instead of null and then in the action method we could have changed the GetJsonData() method to GetJsonData(int count).

jQuery AutoComplete by Example in ASP.NET

This article helps you to create AutoComplete textbox using jQuery library. This will also give you details about jQuery AutoComplete UI, CSS and select event.
In this example you will create a ASP.NET Web Form application which will connect to Northwind database.  The AutoComplete TextBox's change event will call PageMethod written in WebForm code behind file. This method will get country names from Customer table and return as suggestion for AutoComplete TextBox.

jQuery AutoComplete Widget

jQuery AutoComplete Widget gives pre-populated list of suggestions as user types in input field. You need to provide array of strings as source to this widget. Array can be created by some static values or get values from database. Also you can mention minLength to specify after how many characters input call for suggestions to be made.

Implement jQuery AutoComplete

  1. jQuery.Ajax() with PageMethod

     It has a DropDownList control to display Country and a Table object to display Customer details of selected country. On change event of DropDownList control customer detail will be read from database using jQuery.Ajax() call and append as row to Table object.
    In this article we will add a TextBox control which will be AutoComplete to suggest countries and replace functionality of existing DropDownList control.
  2. TextBox with AutoComplete

    Open Default.aspx page and add a TextBox control. Name it as txtCountry. Whenever user types some characters in txtCountry it will make jQuery.Ajax() to Northwind database and select related Country names which will be associated as source for AutoComplete widget.
        
        
  3. WebMethod for GetCountryNames

    The method GetCountryNames is a WebMetod meaning that it can be called from client side script code like JavaScript. It accepts parameter keyword and get Country names which contains specific keyword from database. Those country names will be return as array of string to AutoComplete widget.

    Add below code in Default.aspx.cs file
        [WebMethod]
        public static string[] GetCountryNames(string keyword)
        {
            List country = new List();  
            string query = string.Format("SELECT DISTINCT Country FROM 
                    Customers WHERE Country LIKE '%{0}%'", keyword);
    
            using (SqlConnection con =
                    new SqlConnection("your connection string"))
            {
                using (SqlCommand cmd = new SqlCommand(query, con))
                {
                    con.Open();
                    SqlDataReader reader = cmd.ExecuteReader();
    
                    while (reader.Read())
                    {
                        country.Add(reader.GetString(0));    
                    }
                }
            }
            return country.ToArray();
        }
         
         
  4. TextBox Autocomplete event

    AutoComplete widget has many properties which you can use to customize your execution and control look and feel.
    For this tutorial we will use Source, minLength and Select event.
    From Solution Explorer -> Scripts folder open Customer.js. It contains a jQuery method for getting customer from Database and append customer details to Table object.
    below jQuery code to Customer.js file.
     $("#MainContent_txtCountry").autocomplete({
        source: function (request, response) {
        var param = { keyword: $('#MainContent_txtCountry').val() };
        $.ajax({
            url: "Default.aspx/GetCountryNames",
            data: JSON.stringify(param),
            dataType: "json",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataFilter: function (data) { return data; },
            success: function (data) {
                response($.map(data.d, function (item) {
                    return {
                        value: item
                    }
                }))
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }
        });
        },
        select: function (event, ui) {
            if (ui.item) {
                GetCustomerDetails(ui.item.value);
            }
        },
        minLength: 2
    });         
                
    We have added Source method which makes a call to GetCountryNames PageMethod written in code behind file. The return values from method shown as pre populated suggestions for user.
    We mentioned minLength as 2, it means when ever user enter 2 character in TextBox the AutoComplete method will fire and get its source data.
    Select event gives you selected value by user. The value can be read by ui.item.value
  5. jQuery AutoComplete Select Event

    In this step we will use selected value by user and perform required operation.

    For this tutorial you are going to make another jQuery.Ajax() call and get customer details who belongs to selected country.

    In Previous step we mention that on selection of value from pre populated list of AutoComplete TextBox we will call jQuery GetCustomerDetails function. It takes Country name as input parameter, make ajax call to WebMethod get Customer details and render in table object. 
         
  1. Add below GetCustomerDetails function in Customer.js
    function GetCustomerDetails(country) {
        
    $("#tblCustomers tbody tr").remove();
    
    $.ajax({
        type: "POST",
        url: "Default.aspx/GetCustomers",
        data: '{country: "' + country + '" }',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
        response($.map(data.d, function (item) {
            var rows = "
    "
                + "" + item.CustomerID + ""
                + "" + item.CompanyName + ""
                + "" + item.ContactName + ""
                + "" + item.ContactTitle + ""
                + "" + item.City + ""
                + "" + item.Phone + ""
                + "
    ";
            $('#tblCustomers tbody').append(rows);
        }))
        },
        failure: function (response) {
            alert(response.d);
        }
    });
    }
    
    GetCustomers PageMethod already written in Default.aspx.cs file.
  2. jQuery AutoComplete ui

    You will have to include required jQuery and css files. jQuery AutoComplete UI provides those files, using it your TextBox will perform autocomplete and render suggestions for user.
    Add reference to those files in Site.Master file.
    
    
    
        
      
    
     
    
         
          
    

jQuery AutoComplete by example in asp.net

Tuesday, July 1, 2014

Win8Dev Tutorial: Know about LayoutAwarePage of Wndows Store app



In last chapter “Navigate between Pages” we discussed the basics of page navigation, where we navigated from one page to another page using the Frame.Navigate(type, obj). We also discussed how to pass an object as query string parameter.

Today in this chapter we will discuss more advanced page navigation using the LayoutAwarePage which comes with the Grid and Split application template by default.

Continuing the last chapter on building Windows Store application, today we will explore more about the standard navigation. If you create a Grid app or a Split app, you will find some common files created inside the project under the “Common” folder. Among them “LayoutAwarePage” implements many navigational APIs to do the standard navigational operations.

Windows Store Project

“LayoutAwarePage” inherits from “Page” and hence you will be able to use all the basic operations that Page class offers you. In addition to those, you will find more new APIs in that. If you are using a blank XAML page, you just have to use “LayoutAwarePage” insists of “Page” as shown below in order to use the advanced layout and navigation features,

LayoutAwarePage of a Windows Store Project

It is always better to use this class as the root of the page if you are using navigations from one page to another. The important methods that you will be able to use from this page are: “GoHome()”, “GoBack()” and “GoForward()” which implicitly calls the Frame methods to complete these operations. The implementation of those methods are shared here for clear visibility:
 
// Invoked as an event handler to navigate backward in the page's associated
// Frame until it reaches the top of the navigation stack.
protected virtual void GoHome(object sender, RoutedEventArgs e)
{
    // Use the navigation frame to return to the topmost page
    if (this.Frame != null)
    {
        while (this.Frame.CanGoBack) this.Frame.GoBack();
    }
}
 
// Invoked as an event handler to navigate backward in the navigation stack
// associated with this page's Frame.
protected virtual void GoBack(object sender, RoutedEventArgs e)
{
    // Use the navigation frame to return to the previous page
    if (this.Frame != null && this.Frame.CanGoBack) this.Frame.GoBack();
}
 
// Invoked as an event handler to navigate forward in the navigation stack
// associated with this page's Frame
protected virtual void GoForward(object sender, RoutedEventArgs e)
{
    // Use the navigation frame to move to the next page
    if (this.Frame != null && this.Frame.CanGoForward) this.Frame.GoForward();
}


To see how these methods work, you can chose any one of the Grid and Split applications from the Windows Store project template. Let’s take Grid app for an example here. The main screen of the Grid app uses a GridView to show thumbnails of the groups as below:

Grid app of Windows Store Project

Clicking the group header will navigate you to the group details page. You can see a back button here just before the page title. It is by default available in all the pages but based on navigation status it becomes visible or collapse. Here’s the code to show the back button and page title:
 
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Button x:Name="backButton" Click="GoBack" 
            IsEnabled="{Binding Frame.CanGoBack, ElementName=pageRoot}"
            Style="{StaticResource BackButtonStyle}"/>
    <TextBlock x:Name="pageTitle" Grid.Column="1" 
               Text="{StaticResource AppName}"
               Style="{StaticResource PageHeaderTextStyle}"/>
</Grid>

Grid app of Windows Store Project

Similarly clicking the items from the group page or group details page will navigate you to the group item details page. You can easily navigate to the next or previous item by just sliding the screen or navigational keys of the keyboard.

Grid app of Windows Store Project

This navigational operations are handle by the two events named AcceleratorKeyActivated and PointerPressed of the core window. The first invokes when a user uses keystrokes to navigate and the second one invokes when a user uses mouse clicks, touch screen taps or other similar interactions to navigate between pages. Here comes the declaration of the said events:
 
// Invoked on every keystroke, including system keys such as Alt key combinations,
// when this page is active and occupies the entire window. Used to detect keyboard
// navigation between pages even when the page itself doesn't have focus.
private void CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher sender,
                                                    AcceleratorKeyEventArgs args);
 
// Invoked on every mouse click, touch screen tap, or equivalent interaction when
// this page is active and occupies the entire window. Used to detect browser-style 
// next and previous mouse button clicks to navigate between pages.
private void CoreWindow_PointerPressed(CoreWindow sender, PointerEventArgs args);

In the below screenshot you can see the navigational arrows that pops up when you move your mouse inside the screen. An user can easily navigate between the pages by tapping those buttons or pressing the navigational keys in the keyboard.

Grid app of Windows Store Project

Not only this, the LayoutAwarePage also automatically handles the screen orientation changes properly. You can use visual states of each pages to visualize the screen orientation and view.

This post will help you to understand the LayoutAwarePage implementation and uses of it. Try out by creating a sample project yourself, you will come to know more about it. If you have any queries, drop a line below and I will try to answer you as soon as I can. Happy coding.

Win8Dev Tutorial: Navigate between Pages in Windows Store apps



Let’s begin with our fourth chapter of building Windows Store application development using Visual Studio 2012. In the previous chapters of this tutorial series, we got familiar with this project template and built a basic “Hello World” application.

Today in this chapter we will learn how to navigate from one page to another page in Windows 8 Store applications. So, continue reading.

Introduction to Page Navigation

It’s not at all difficult to implement the navigation in Windows Store applications but if you are a Silverlight and/or Windows Phone application developer and just moved to this field, you might find difficulty developing a navigation application. In Windows Phone, we use NavigationService.Navigate() to navigate to a different page from a page. Also, we pass a relative or absolute URL to the Navigate() method. Here it’s bit different. Let’s discuss on it more.

In Windows 8 Store applications, every page has a “Frame” object, which implements the following properties and methods to support easy navigations:

GoBack()Navigates to the most recent item in back navigation history, if a Frame manages its own navigation history.
GoForward()Navigates to the most recent item in forward navigation history, if a Frame manages its own navigation history.
Navigate(type, args)Navigates to the page specified.
BackStackDepthThe number of entries in the navigation back stack.
CanGoBackGets a value that indicates whether there is at least one entry in back navigation history.
CanGoForwardGets a value that indicates whether there is at least one entry in forward navigation history.

Check out the parameters of Navigate(type, args) method. You can see that, you can’t pass navigation Uri like we did in Silverlight and Windows Phone. Instead of passing the relative/absolute Uri path here, we have to pass the type of the page.

Let’s suppose we want to navigate from MainPage.xaml to SecondaryPage.xaml. You have to call navigate method by passing the type of second page. For example:
 
Frame.Navigate(typeof(SecondaryPage)); // simple navigation
Frame.Navigate(typeof(SecondaryPage), obj); // navigation with query parameter

Let’s see a practical example. For this, we will need to create a basic blank Windows Store application. For more details, check out the previous chapter: “Begin with your First 'Hello World' app”, which will give you the basic idea.

Begin with XAML Screen

Once you created the project, you will find a page called “MainPage.xaml”. Open it and modify the XAML code with a Button and a TextBlock as shared below (assuming you are familiar with XAML):
 
<Page
    x:Class="NavigationDemo.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <TextBlock Text="Main Page" Style="{StaticResource HeaderTextStyle}"
                   Margin="100,50"/>
        <Button Style="{StaticResource BackButtonStyle}" Margin="403,0,0,668"
                RenderTransformOrigin="0.5, 0.5" Tapped="OnNextButtonTapped">
            <Button.RenderTransform>
                <RotateTransform Angle="180"/>
            </Button.RenderTransform>
        </Button>
    </Grid>
</Page>

This will change the MainPage UI as shown below. We will implement the next button tap event to handle the navigation to a different page later.

Main Page

Now create another page named as “SecondaryPage.xaml” in the root folder and modify this page with the following code. This will have a back button and a TextBlock.
 
<Page
    x:Class="NavigationDemo.SecondaryPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <TextBlock Text="Secondary Page" Style="{StaticResource HeaderTextStyle}" 
                   Margin="100,50"/>
        <Button Style="{StaticResource BackButtonStyle}" Margin="29,0,0,674" 
                Tapped="OnBackButtonTapped"/>
    </Grid>
</Page>

The new page will look as below. Here the back button implementation will have logic to navigate to the previous page in the navigation stack.

Secondary Page

This ends the basic design of our sample application. You can do more with that but it is not require to complex this demo as you are reading it to know more about this implementation.

Implementing the Navigation between Pages

To implement the navigation between those pages, you need to modify the code behind of both the screens. In both the cs file, you will find the Tap event. In the MainPage.xaml.cs implementation, call the Navigate() method and pass the other page type as shown below, which when called will navigate you to the secondary page:
 
// Forward button tap implementation (in MainPage.xaml.cs)
private void OnNextButtonTapped(object sender, TappedRoutedEventArgs e)
{
    Frame.Navigate(typeof (SecondaryPage));
}
 
 
// Back button tap implementation  (in SecondaryPage.xaml.cs)
private void OnBackButtonTapped(object sender, TappedRoutedEventArgs e)
{
    if (Frame.CanGoBack)
    {
        Frame.GoBack();
    }
}

In the SecondaryPage.xaml.cs implementation (as shown above), first check whether the navigation can go to the previous page and if it can go, call the GoBack() method from the Frame itself.

As mentioned above, if you want to pass a query string parameter to the second page where you are navigating to, you can do so by passing the value or object as second parameter to the Navigate() method.

End Note

I hope that, this post will help you to understand the navigation mechanism in Windows Store application. After reading this chapter, you will be able to navigate the user from one page to another and also you will be able to send message to the other page.

Win8Dev Tutorial: Begin with your First “Hello World” Windows Store app

How to create your first Windows Store application?

Let’s open the Visual Studio 2012 IDE and go to File – New – Project to create a new Windows Store project. From the Visual C# category, we will select the Windows Store template category. In the right panel, chose Blank App (XAML) and give a good name (in our case, it is “HelloWorld”). Now click “OK” to continue. Momentarily the IDE will start creating your first project.

Create HelloWorld Windows Store app in Visual Studio 2012

Once the project has been created by the IDE, open the MainPage.xaml file and add a TextBlock from the toolbox inside the Grid as shown below:

Design the UI of the Application with a TextBlock

Select the TextBlock and move to the Properties panel. There you can set the text property of the control. Visual Studio 2012 gives a proper way to bind styles from the local resource. Click the small rectangle near to the Style property, navigate to Local Resource and from the secondary menu, select a style (e.g. HeaderTextStyle) as shown in the below screenshots:

Use the properties panel to style the control     Style the TextBlock with Local Resources

Styled TextBlock in the designer window

Here is the XAML code of what we have designed just now:
 
<Page x:Class="HelloWorld.MainPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
 
    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <TextBlock HorizontalAlignment="Left" Height="101" Margin="81,99,0,0" 
                   TextWrapping="Wrap" Text="Hello World" VerticalAlignment="Top" 
                   Width="598" Style="{StaticResource HeaderTextStyle}"/>
    </Grid>
</Page>

Now in the design window, you will see similar to the above screen. You can drag other controls too and create your own UI for your first “HelloWorld” Windows Store application. Once your application design is ready, you can build and run that app to see what we developed just now.

Building and Running the Windows Store application

It’s time to build the project and run it to see our application running inside Windows 8. You can chose any one of the three options that Visual Studio 2012 provides to test our app. You can chose between the following locations:
      • Simulator – The app will be deployed in a simulator
      • Local Machine – The app will be deployed in your local development machine
      • Remote Machine – The app will be deployed in a remote Windows 8 PC
When you move your mouse to the debug option menu inside your Visual Studio 2012 IDE, you will see all the three options as shown below:

Choose the deployment environment

You can chose the one where you want to deploy and test your application. In our case, we will deploy it to Simulator to see how it looks inside a tablet. Here is the screenshot of the application hosted in the simulator:

Run the application inside Simulator

Now you are done with your first Windows Store application using Visual C# (XAML) and now you will be able to develop more applications using that simple project template.

End Note

In the next chapter, we will learn more about Windows Store application configuration and then we will proceed towards the other templates and coding tricks. Till then enjoy doing your hands dirty developing Windows Store applications.

Win8Dev Tutorial: Understand WinRT Project Templates and Structure

What are the Common Templates in each Category?

Each category has it’s own templates but among them three are common and they are “Blank App”, “Grid App” and “Split App”. You will find them in all the four categories and you will need any one of them while creating your Windows Store applications. Before going to other categories, let’s discuss these common basic templates first.

Blank Template

“Blank App” template creates a single page project for a Windows Store application which has no predefined controls of layouts. In the UI page, you will see it completely blank and you have to create everything from scratch.

Grid Template

“Grid App” template creates a three page project structure for a Windows Store application that navigates among grouped items arranged in a grid. The main page display all items in groups. When clicked, the page navigates to details pages of individual item.

Split Template

“Split App” template generates a two paged project for a Windows Store application that also navigates among a set of grouped items. The main page allows group selection while the other page displays an item list along with details for the selected item.

What are the Structures of individual core project?

When you create a Windows Store project with any one of the above mentioned templates, it will create the following project structures (shown as per each individual template):

Windows Store Various Project Structure

In the above project structures you will see a similarity between each one of them. Every project has two folders, App.xaml, a .pfx file and a .appxmanifest file in it. The basic folders are Assets (used to store resource images required by the application) and Common (to store the common code files used across the application). There is a third folder named DataModel (a repository of Models, View Models and Sample Data Source used by it) available only in Grid and Split project.

Each and every project will have a App.xaml file which is the basic entry point to the application, a Package.appxmanifest file to set the manifest information of the app and a [APPLICATION_NAME]_TemporaryKey.pfx file which stores the certificate key information. Rest of them are xaml pages based on the above selection.

What are the other Project Templates in each Category?

Apart from the common templates, each category has a set of various templates. Let’s see what are those in each category. This will make it easier for you to chose the category and project template before starting a new project.

In Visual C# and Visual Basic category, we have 3 additional project templates named “Class Library”, “Windows Runtime Component” and “Unit Test Library” as shown below:

Windows Store (Visual C#) Template

The class library project creates a managed class library for Windows Store apps and Windows Runtime Component. Windows Runtime Components can be used by Windows Store apps regardless of the programming languages in which the apps were written. The other template gives you easy access to write unit testing code directly.

Windows Store (Visual Basic) Template

If you are going to develop a direct 2D or direct 3D application, you should chose Visual C++ category as this category provides you the basic templates to start with that. In this category you will find the following additional templates:
        • Direct 2D App
        • Direct 3D App
        • DLL Library project
        • Static Library for Windows Store apps
        • Windows Runtime Component
        • Unit Test Library
Windows Store (Visual C  ) Template

The JavaScript category has “Fixed Layout” and “Navigation” templates to create a static and navigational Windows Store apps.

Windows Store (JavaScript) Template

Do remember that, if you chose JavaScript category, the application will be build using html, scripts and css where as in other categories the UI of the application will be build in XAML.

Summary

Today we discussed about the various project templates and project structures. Up to this, it was just the introduction to Windows Store apps for a beginners who came here to understand the requirements and to kick start their hands dirty with this.

From now onwards, we will work on C# category and focus on the development stuffs to learn Windows Store application development and continue on this series. Don’t forget to check out the coming chapters on this topic.

Monday, March 10, 2014

Difference between inner join and equi join and natural join

SQL join clause is used to to retrieve data from two or more database tables. In previous article, I have explained the Different Types of SQL Joins. In this article, I would explain the difference among inner join, equi join and natural join.

Inner Join

This is the most used join in the SQL. this join returns only those records/rows that match/exists in both the database tables.

Inner Join Example

  1. SELECT * FROM tblEmp JOIN tblDept
  2. ON tblEmp.DeptID = tblDept.DeptID;
In the join condition, you can also use other operators like <,>,<>.

Equi Join

Equi join is a special type of join in which we use only equality operator. Hence, when you make a query for join using equality operator then that join query comes under Equi join.

Equi Join Example

  1. SELECT * FROM tblEmp JOIN tblDept
  2. ON tblEmp.DeptID = tblDept.DeptID;
  3. --Using Clause is not supported by SQL Server
  4. --Oracle and MySQL Query
  5. SELECT * FROM tblEmp INNER JOIN tblDept USING(DeptID)

Note

  1. Inner join can have equality (=) and other operators (like <,>,<>) in the join condition.
  2. Equi join only have equality (=) operator in the join condition.
  3. Equi join can be an Inner join, Left Outer join, Right Outer join
  4. The USING clause is not supported by SQL Server and Sybase. This clause is supported by Oracle and MySQL.

Natural Join

Natural join is a type of equi join which occurs implicitly by comparing all the same names columns in both tables. The join result have only one column for each pair of equally named columns.

Natural Join Example

  1. --Run in Oracle and MySQL
  2. SELECT * FROM tblEmp NATURAL JOIN tblDept

In the above join result we have only one column "DeptID" for each pair of equally named columns.

Note

  1. In Natural join, you can't see what columns from both the tables will be used in the join. In Natural join, you might not get the desired result what you are expecting.
  2. Natural join clause is not supported by SQL Server, it is supported by Oracle and MySQL.