Wednesday, September 25, 2013

C# sample for Google Geocoding API (JSON output)




C# Google geocoding API (JSON output) sample


Geocoding is the process of converting addresses (like "300 n state st chicago IL") into geographic coordinates (like latitude 37.423021 and longitude -122.083739), which you can use to place markers or position the map.



The Google Geocoding API provides a direct way to access a these services via an HTTP request.


This service is generally designed for geocoding static (known in advance) addresses for placement of application content on a map;



A Geocoding API request must be of the following form:
http://maps.googleapis.com/maps/api/geocode/output?parameters
where output may be either of the following values:
  • json (recommended) indicates output in JavaScript Object Notation (JSON)
  • xml indicates output as XML
Required parameters
  • address — The address that you want to geocode.       or  latlng — The textual latitude/longitude value for which you wish to obtain the closest, human-readable address. 
  • sensor — Indicates whether or not the geocoding request comes from a device with a location sensor. This value must be either true or false.
JSON Output Formats
http://maps.googleapis.com/maps/api/geocode/json?address=300+n+state+st+chicago+Il&sensor=true&components=country:US
We've left the sensor parameter in this example as a variable true_or_false to emphasize that you must set this value to either true or false explicitly.
The JSON returned by this request is shown below. 
{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "300",
               "short_name" : "300",
               "types" : [ "street_number" ]
            },
            {
               "long_name" : "North State Street",
               "short_name" : "N State St",
               "types" : [ "route" ]
            },
            {
               "long_name" : "River North",
               "short_name" : "River North",
               "types" : [ "neighborhood", "political" ]
            },
            {
               "long_name" : "Chicago",
               "short_name" : "Chicago",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Cook",
               "short_name" : "Cook",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "Illinois",
               "short_name" : "IL",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "United States",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            },
            {
               "long_name" : "60654",
               "short_name" : "60654",
               "types" : [ "postal_code" ]
            }
         ],
         "formatted_address" : "300 North State Street, Chicago, IL 60654, USA",
         "geometry" : {
            "location" : {
               "lat" : 41.8883461,
               "lng" : -87.6288376
            },
            "location_type" : "ROOFTOP",
            "viewport" : {
               "northeast" : {
                  "lat" : 41.8896950802915,
                  "lng" : -87.6274886197085
               },
               "southwest" : {
                  "lat" : 41.8869971197085,
                  "lng" : -87.63018658029151
               }
            }
         },
         "types" : [ "street_address" ]
      }
   ],
   "status" : "OK"
}

Note that the JSON response contains two root elements:
  • "status" contains metadata on the request. See Status Codes below.
  • "results" contains an array of geocoded address information and geometry information.
Generally, only one entry in the "results" array is returned for address lookups, though the geocoder may return several results when address queries are ambiguous.
Following C# sample queries Google GeoCoding API and parses json response to custom .Net object. We've utilized Json.Net framework to parsing json object. 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.IO;
using System.Net;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please enter the address to validate:");
            var address = Console.ReadLine();
            NetGoogleGeocoding geoCoder = new NetGoogleGeocoding();
            var response = geoCoder.GoogleGeocode(address);
            Console.WriteLine("*********** validation complete *****************");
            Console.WriteLine(string.Format("House Number ---- {0}",response.GeoCodes[0].HouseNumber));
            Console.WriteLine(string.Format("Street Address -- {0}",response.GeoCodes[0].StreetAddress));
            Console.WriteLine(string.Format("City ------------ {0}",response.GeoCodes[0].City));
            Console.WriteLine(string.Format("County ---------- {0}",response.GeoCodes[0].County));
            Console.WriteLine(string.Format("State ----------- {0}",response.GeoCodes[0].State));
            Console.WriteLine(string.Format("Zip ------------- {0}",response.GeoCodes[0].Zip));
            Console.WriteLine(string.Format("Country --------- {0}",response.GeoCodes[0].Country));
            Console.WriteLine(string.Format("Full Address ---- {0}",response.GeoCodes[0].FullAddress));
            if (response.GeoCodes[0].Types.Count() > 1)
            {
                Console.WriteLine(string.Format("Types ----------- {0},{1}", response.GeoCodes[0].Types[0], response.GeoCodes[0].Types[1]));
            }
            else
            {
                Console.WriteLine(string.Format("Types ----------- {0}", response.GeoCodes[0].Types[0]));
            }
            Console.WriteLine(string.Format("Location Type---- {0}",response.GeoCodes[0].LocationType));
            Console.WriteLine(string.Format("Latitude -------  {0}",response.GeoCodes[0].Latitude.ToString()));
            Console.WriteLine(string.Format("Longitude-------- {0}",response.GeoCodes[0].Longitude.ToString()));
            Console.WriteLine(string.Format("Status   -------- {0}", response.GeoCodes[0].Status));
            Console.ReadLine();
         }
    }
 /// 
 ///   .Net utility for google geocoding API
 /// 
 public class NetGoogleGeocoding {
        public GeocodeJsonResponse GoogleGeoCodeResponse;
  const string GoogleGeoCodeJsonServiceUrl = "http://maps.googleapis.com/maps/api/geocode/json?address={0}&sensor=true&components=country:US";
        public NetGoogleGeocoding()
        {
            GoogleGeoCodeResponse = new GeocodeJsonResponse()
            {
                GeoCodes = new List()
            };
  }
  /// 
  ///   Performs Geocode and returns Object
  /// 
  ///  
        public GeocodeJsonResponse GoogleGeocode(string address)
        {
            using (var cli = new WebClient())
            {
                var addressToValidate = string.Format(GoogleGeoCodeJsonServiceUrl, HttpUtility.UrlEncode(address));
                var response = cli.DownloadString(new Uri(addressToValidate));
                return HydrateJson(response);
           }
  }
  /// 
  /// generic method to read json values from json string
  /// 
  ///  
  ///  
  ///  
  static string GetJsonNodeValue(JToken token, string field) {
   return token["address_components"].Children().Any(x => x["types"].Values().Contains(field))
        ? token["address_components"].Children().First(x => x["types"].Values().Contains(field))["short_name"].Value()
        : string.Empty;
  }
        GeocodeJsonResponse HydrateJson(string jsonResponse)
        {
   var results = (JObject) JsonConvert.DeserializeObject(jsonResponse);
   foreach(
   var googleGeoCode in
      results["results"].Children().Select(
         token =>
   new Geocode {
      HouseNumber = GetJsonNodeValue(token, "street_number"),
      StreetAddress = GetJsonNodeValue(token, "route"),
      City = GetJsonNodeValue(token, "locality"),
      County = GetJsonNodeValue(token, "administrative_area_level_2"),
      State = GetJsonNodeValue(token, "administrative_area_level_1"),
      Zip = GetJsonNodeValue(token, "postal_code"),
      Country = GetJsonNodeValue(token, "country"),
      FullAddress = token["formatted_address"].Value(),
      Types = token["types"].Values().ToList(),
      LocationType = token["geometry"]["location_type"].Value(),
      Latitude = token["geometry"]["location"]["lat"].Value(),
      Longitude = token["geometry"]["location"]["lng"].Value(),
      Status = string.Format("{0}", token["geometry"]["location_type"].Value())
   })) {
    GoogleGeoCodeResponse.GeoCodes.Add(googleGeoCode);
   }
   return GoogleGeoCodeResponse;
  }
 }

    public class GeocodeJsonResponse
    {
        public List GeoCodes { get; set; }
    }
    public class Geocode
    {
        public string HouseNumber { get; set; }
        public string StreetAddress { get; set; }
        public string City { get; set; }
        public string County { get; set; }
        public string State { get; set; }
        public string Zip { get; set; }
        public string Country { get; set; }
        public string FullAddress { get; set; }
        public List Types { get; set; }
        public string LocationType { get; set; }
        public float Latitude { get; set; }
        public float Longitude { get; set; }
        public string Status { get; set; }
    }

}


Sunday, September 22, 2013

ASP.Net MVC interview questions



ASP.Net MVC Interview Questions:


What are fundamental tenets /philosophy behind ASP.Net MVC Framework design?


  • Convention over configuration
  • Don't repeat yourself (DRY)
  • Pluggability/extensibility wherever possible
  • Lean, clean standards based semantic html markup


Can you briefly explain new features in ASP.Net MVC 4 release?

  1. Mobile application project template to create Mobile sites. This is based on jQuery mobile Framework and adaptive rendering to improve display on mobile devices.
  2. Display Modes feature (Browser override) - uses convention based approach to allow selecting views based on browser making the requests. If a mobile browser requests view, the application returns mobile optimized view. 
  3. View Switcher (partial view and supporting controller)  which lets  us switch view display manually between Desktop and Mobile devices.
  4. TPL support for Asynchronous controllers - action methods now return an object of type Task.
  5. Integrated support for Web API framework utilizing asp.net mvc development style (Routing system) but tailored for writing Http Services.
  6. Supports OAuth and OpenID authentication/authorization with external identity providers.
  7. Bundling & Minification support for scripts and content files.

Explain the request life cycle in ASP.Net MVC site?


There are five phases which trigger when you make a request

1. RouteTable
 Of course, this steps happens only once when site starts for the first time. The RouteTable maps route definitions to route handlers.
2. UrlRoutingModule
The UrlRoutingModule intercepts every request and matches incoming request and executes the matching handler (default mvchandler)
3.MvcHandler
The MvcHandler selects the controller that will handle HTTP request and passes the controller a wrapped HttpContext(ControllerContext)
4. Controller
The controller determines which controller method to execute, builds a list of parameters, and executes the method.
5. The RenderView Method is Called
Typically, a controller method calls RenderView() to render content back to the browser. The Controller.RenderView() method delegates its work to a particular ViewEngine.

Explain HTTP Methods?

Web API uses the HTTP method to select the action. 

To find the action, Web API looks at the HTTP method, and then looks for an action whose name begins with that HTTP method name. For example, with a GET request, Web API looks for an action that starts with "Get...", such as "GetUser" or "GetAllUsers".  This convention applies only to GET, POST, PUT, and DELETE methods.

Instead of using the naming convention for HTTP methods, you can explicitly specify the HTTP method for an action by decorating the action method with the HttpGetHttpPutHttpPost, or HttpDelete attribute.

To allow multiple HTTP methods for an action, or to allow HTTP methods other than GET, PUT, POST, and DELETE, use the AcceptVerbs attribute, which takes a list of HTTP methods.

Where are the routes for Web API controller defined?

Routes are defined in the WebApiConfig.cs file, which is placed in the App_Start directory. 

What's default route template for Web API like?

routes.MapHttpRoute(
    name: "API Default",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

What is IControllerActivator?

IControllerActivator gives an opportunity to introduce Dependency Injection (DI) into controllers by creating a controller activator.  The interface contains one method called Create, which is passed a RequestContext and a Type that specifies which controller class should be instantiated.


What are the different types of Filters in MVC?

a. Authorization filter

b. Action filter

c. Result filter

d. Exception filter


What are the different return types supported by Action methods?

1. ViewResult
2. JavaScriptResult
3. RedirectResult
4. ContentResult
5. JsonResult
6. FileResult

Explain IRouteHandler interface?

Whenever a request is received by MVC, it is the job of the routing engine to match the request URL with the registered routes. After finding the matched route, the route handler for the route is being called. Each route can have its own route handler. A route handler is a class that implements IRouteHandler interface.

What is the difference between ViewData, ViewBag and TempData?

ViewData is a dictionary object and requires typecasting for complex types.
ViewBag is a dynamic property.ViewBag doesn't have typecasting and null checks.
TempData stays for the time of an HTTP Request. It maintains data between redirects, i.e., from one controller to the other controller.


Is it possible to abort/timeout Asynchronous action method? 

Asynchronous action methods that return Task instances can support timeouts. To make your action method cancelable, add a parameter of type CancellationToken to the action method signature. 

What is non Action attribute?

To prevent a method from getting invoked as an action, use the NonAction attribute. This signals to the framework that the method is not an action, even if it would otherwise match the routing rules.

Explain order of execution for the Action filters?
Authorization filters run first before the other kinds of filter and last one to run is Exception filter

Can Partial View invoke an action method?
NO.

Explain child actions?

Child actions are action methods invoked from within a view. This lets you avoid repeating controller logic that you want to use in several places in the application. Child actions are to actions as partial views are to views.Used for creating reusable UI controls (partial views). When you use a child action, it invokes an action method, renders a view, and injects the result into the response stream.

What are sections in Razor engine?

Sections allows you to provide regions of content within a layout. Razor sections give greater control over which parts of the view are inserted into the layout and where they are placed.We define sections using the Razor @section tag followed by a name for the section.

Can we have Controller name which doesn't end in "Controller"?

YES. The default controller factory uses "convention" around controller names when it's trying to find a controller to dispatch the request to. You could override if we implement our custom IControllerFactory

Is it possible to have Generic controller in asp.net mvc world?

YES. You just can't use it directly but you can inherit it and use the derived class as controller

 public class Product : Controller
        where T : new()
        { ...... }
public class TestProduct : Product {

}

Can an ASP.Net MVC controller return an Image?

Return FilePathResult using File method of controller

Explain FileResult action result in asp.net mvc?

Represents a base class that is used to send binary file content to the response. There are four types of FileResult.
  • FileContentResult: Sends the contents of a binary file to the response.
  • FilePathResult: Sends the contents of a file to the response
  • FileResult: Returns binary output to write to the response
  • FileStreamResult: Sends binary content to the response by using a Stream instance
Can you overload controller methods in ASP.Net MVC?

YES.  Use ActionName attribute on action method.

Is the following a valid route definition?
routes.MapRoute("", "X{controller}/{action}") ?
YES.

How routes in route system are applied for incoming request?

Routes are generally applied in the order in which we add them to route table.

Is the following a valid route 
routes.MapRoute("MyRoute", "{controller}/{action}/{id}/{*rest}"?

YES. variable length routes are valid.  This route will match any URL, irrespective of the number of placeholders it contains. The first three placeholders are used to set values for controller, action and id variables, additional placeholders are all assigned to rest variable

Can we have two controllers with the same name?

YES. we can. using namespace prioritization when attempting to resolve name of controller.

How can I ensure that only controller names beginning with "p" are available to service incoming request?

We have to define constraints by passing them as a parameter to the MapRoute method. We can define constraint with a regular expression that matches URLS only where value of controller variable with letter P
new { controller = "^P.*",}

Can you request static files like images, html files using ASP.Net MVC architecture with out using controller and action?

YES. The routing system provides support for serving static content. It checks to see if a URL matches a disk file before evaluating the application routes;

How can you bypass specific URL from being evaluated against routes?

USE IgnoreRoute

Difference between @Html.ActionLink and @Html.RouteLink?

You can override the default routing matching behavior by using Html.RouteLink  method, which lets you specify which route you want to use.

What is areas in ASP.Net MVC?

Areas represents a functional segment of the application, such as customer, admin. This is useful in a large project. Each area has it's own folder structure, allowing you to keep everything separate. 

Can you create outbound link to an action in a different area?

YES. Set the variable called area and use it to specify the name of the area you want
@Html.ActionLink("Test area", "Index", new { area = "Test" })

How about linking an action on one of the top-level controllers from an area?

You should set the name of area as empty string.

Explain Web API routing system?

ASP.NET Web API uses the same routing system for mapping URLs to controller actions. It contextualizes the routing to HTTP services by mapping HTTP verbs to actions by convention, which both makes the code easier to read and encourages following RESTful service design.

What are Global Action filters?

Action filters which apply to all action methods in your application. Useful for application wide concerns like logging and error handling.


    Sunday, September 8, 2013

    WPF interview questions




    Windows Presentation Foundation (WPF) Interview questions

    What is WPF?

    Windows Presentation Foundation (WPF) provides developers with a unified programming model for building rich Windows Forms applications that incorporate user interface (UI), media, and documents. WPF enables software developers to deliver a new level of "user experience" (UX) by providing a declarative-based language (XAML) for specifying vector-based graphics that can scale and take advantage of hardware acceleration.All display in WPF is done through the DirectX engine, allowing for efficient hardware and software rendering

    Explain Dependency property
    1. It is a special property system supported by WPF. The purpose of DP is to provide a way to compute the value of a property based on the value of other inputs. 
    2. DependencyObject defines the base class that can register and own a dependency property. DP provides functionality that supports features of WPF like 
      1. 1) Resources
      2. 2) Data Binding
      3. 3) Styles, templates, change notification, animations, property value inheritance 
    3. The value of a dependency property is resolved dynamically when calling the GetValue() method that is inherited from DependencyObject.
    4. The dependency property is a public static read-only field that must be registered first. After it has been registered, this static property is used to get and set the value in the internal storage system.

    What are Attached Properties?
    1. They are a special type of dependency property. With an attached property, the property is defined on a class that isn't the same class for which it's being used.
    2. This is usually used for layout. They are basically meant for the container elements.
    3. WPF elements are built on the principle of composition and component reuse. It is often the case that some containing element (like a Grid layout element) needs additional data on child elements to control its behavior (like the Row/Column information).
    4. Attached properties allow child elements to define values for a parent element’s properties.  They only make sense in the context of a hierarchical element tree.

    WPF styles:
    1. It is a convenient way to apply a set of property values to more than one element to provide a consistent visual appearance.You can use a style on any element that derives from FrameworkElement or FrameworkContentElement. 
    2. Styles are defined as a resource in the Resources section in a xaml file.  Style resources obey scoping rules and are applicable by type.

    WPF Data Templates & HierarchicalDataTemplate
    1. Data Template is about the structure and presentation of data. 
    2. They are reusable. 
    3. ListView,ListBox, drop down list controls employ data templates.  
    4. HierarchicalDataTemplate is useful if you're displaying collections that contains other collections like Menu or Treeview. 
    5. DataTemplateSelector allows you to choose a DataTemplate to use based on custom logic.

    WPF Control Templates:
    1. Controls in WPF have a ControlTemplate that contains the visual tree of that control. 
    2. ControlTemplate – Defines the entire layout of a control (rather than just what is substituted in the ContentPresenter).  It is defined to exist within a Template property for a Control.
    3. When you are defining a new template for the Button control, if you do not specify a ContentPresenter somewhere in your control template, the Button will not behave as intended i.e. no matter what is specified for the Content property , it will not be displayed within your newly templated Button.
    4. Example of Template hierarchy for ItemsControl and buttonControl
      •            ItemsControl -> ItemsPanelTemplate -> ItemTemplate -> DataTemplate
      •            ItemsControl -> ControlTemplate -> ItemPresenter
      •            ButtonControl ->ControlTemplate ->ContentPresenter
    WPF Triggers:
    1. A trigger sets properties or starts actions when a property value changes or when an event is raised. Style, controlTemplate and dataTemplate all have a Triggers property that can contain a set of triggers.
    2. Types of triggers
      • PropertyTriggers – A property reaches some value
      • EventTriggers – A particular event has occurred
      • DataTriggers – A particular property of the DataContext has reached some value
      • MultiTriggers – Several properties have met some condition
    Difference between VisualTree & LogicalTree
    1. The logical tree is the externally visible element hierarchy that a consumer of the control gets to program against.
    2. Visual tree for a control is what contributes to complete look & feel of the control. Ex: border, contentPresenter, grid, rectangle, text block in a button control.
    3. The visual tree represents all of the elements in your UI which render. Walking up and down the visual tree can be a simple matter of just using VisualTreeHelper and some simple recursive methods.

    WPF DataBinding: 
    1. With proper binding expressions and change notifications, when data changes it's value the element that are bound to the data reflect changes automatically. 
    2. Each binding has four components: a binding target object, a target property, binding source and a path to the value in the binding source. For example, if you want to bind the content of a TextBox to the Nameproperty of an Employee object, your target object is the TextBox, the target property is the Text property, the value to use is Name, and the source object is the Employee object.
    3. The data flow of a binding can go from the binding target to the binding source and vice versa. One way, two way and oneWayToSource are different modes of data flow.
    4. OneWay binding applies changes from source property to target property, but changes to the target property are not propagated back to the source property.
    5. TwoWay binding causes changes to either the source property or target property to automatically update the other.
    6. OneWayToSource is the reverse of OneWaybinding; it updates the source property when the target property changes.
    7. To detect source changes, the source must implement property change notification such as INotifyPropertyChanged. 
    8. The UpdateSourceTrigger property of binding determines what triggers the update of the source.

    What is DataContext?
    1. Every WPF control derived from FrameworkElement has a DataContext property. This property is meant to be set to the data object it visualizes. The DataContext property inherits it's value to child elements. 

    ValueConverters:
    1. If you want to bind two properties of different types together, you need to use a  ValueConverter. (Ex: Color object to solidColorBrush to apply for background property). or (binding  a bool member to the visibility property)
    2. A ValueConverter converts the value from a source type to a target type and back. You can write your own converter by implementing IValueConverter interface

    IMultivalueConverter:
    1. A MultiBinding works just a regular Binding except it must have a Converter specified and can have multiple pieces of data bound to it, so when any of these change it fires a re-evaluation of the lot.

    DispatcherObject:
    1. Most objects in WPF derive from DispatcherObject, which provides the basic constructs for dealing with concurrency and threading. All updates to UI thread are dispatched from background threads using dispatcherObject.

    WPF Routed Event Model:
    1. All events in WPF have a notion of routing through the element tree. Events are said to "bubble" if they traverse from a target up the tree to the root, and are said to "tunnel" if that start at the root and traverse down to a target.
    2. Routed events can invoke handlers on other objects in the element tree aside from just the originating object that raised the event.  This means that events for a chain of elements can be triggered in sequence allow them to tunnel down and bubble up the visual & logical trees from element to element
    3. There are 3 types of routing strategies
      • Tunnelling travels towards to the leaves of the visual/logical tree
      • Bubbling travels towards the root of the visual/logical tree
      • Direct can only be handled by the object that raised the event

    Explain FrameworkElement?
    1. FrameworkElement provides a framework of common APIs for objects that participate in application layout. FrameworkElement also defines APIs related to data binding, object tree
    2. The two most critical things that FrameworkElement introduces are data binding and styles.

    What is Content Control and explain difference between ContentPresenter and ItemsPresenter?
    1. ContentControl – A control that allows developers to define UIElements that can be displayed within the control
    2. ContentPresenter – A stub in the ControlTemplate for where the content from the Content property of a ContentControl should be inserted
    3. ItemsControl – Control that displays a collection of items
    4. ItemsPresenter – An ItemsControl.Template can contain a ControlTemplate.  The 
    5. ItemsPresenter is the stub for where the items should be rendered in the ControlTemplate
    Commands:

    1. They provide a method that allows events for multiple elements share the same command
    2. The command is defined in a CommandBindings element.  Any of the child elements of the main container can reference the commands

    ContentControl and ItemsControl:
    1. ContentControl is intended to display a single piece of content.
    2. ItemsControl, as suggested by the name, is meant to display multiple items within it. 

    MVVM architecture:
    1. MVVM is a architectural pattern custom tailored for WPF and Silverlight. 
    2. Views interact with the view model by bindings, commands, events. 
    3. ViewModel is a specialized form of controller. 
    4. The view model of MVVM is a value converter meaning that the view model is responsible for exposing the data objects from the domain model in such a way that those objects are easily managed and consumed
    5. View model: the view model is a “model of the view” meaning it is an abstraction of the view that also serves in mediating between the view and the model which is the target of the view data bindings. 
    6. The view model exposes public properties, commands, and abstractions.

    Prism:
    • Prism is the Microsoft Patterns and Practices Team official guidance for building "composite applications" in WPF and Silverlight.
    • Prism helps you to design and build applications using loosely coupled components that can evolve independently but which can be easily and seamlessly integrated into the overall application. Such applications are known as often referred to as composite applications.
    • Modules contribute the views from which the main composite view (otherwise known as the shell) is created. Modules never directly reference each other, nor do they directly reference the shell. Instead, they utilize services to communicate with one another and with the shell in order to respond to user actions.
    • The CAL provides the services and plumbing for building composite apps. It uses a composition model that allows each of its services to be used piecemeal or together as part of a CAL-designed app. Each service is also easily replaceable without recompilation of the CAL. For example, the CAL ships with an extension that uses the Unity Application Block for dependency injection
    • Its intended to provide guidance on the best practices for building large scale applications which are flexible in terms of development and maintainability.
    • This includes guidance on dependency injection (via Unity or MEF), layout (including using MVVM), composite event handling, etc.
    • In a WPF-Prism-Unity application, the Shell divides its UI up into regions. A region is any one of the XAML controls that implements the IRegion interface and is tagged with the RegionName attribute
    • With the regions defined, the Shell can now use the Prism-provided RegionManager to retrieve views (WPF UserControls defined in a Module) from the Unity container and load them into the UI.
    • Provides guidance and a re-usable library to help you develop flexible, easy to maintain WPF and Silverlight composite applications
    • Helps you to understand, implement and use key design patterns, such as MVVM and Dependency Injection

    Differences between WPF and Silverlight:
    1. Dynamic resource references are not supported in Silverlight; therefore, only static resource references are available.
    2. Silverlight does not currently support MergedDictionaries.
    3. Silverlight does not support triggers in Styles, ControlTemplates, or DataTemplates (the Triggers collection does not exist on these elements). However, similar behavior can be achieved by using the Silverlight Visual State Manager (VSM) to define interactive control templates. Using VSM, the visual behavior of a control, including any animations and transitions, are defined in the control template.
    4. Silverlight does not support the RelativeSource property, which is useful when the binding is specified in a ControlTemplate or a Style.
    5. In Silverlight, there is no OneWayToSource data flow mode.
    6. In Silverlight, there is no UpdateSourceTrigger property. All updates to the source in the two-way binding mode occur immediately, except in the case of TextBox, in which case changes are propagated to the source when the focus is lost.
    7. In Silverlight, there is no ReadOnlyObservableCollection; however, ObservableCollection is supported. ReadOnlyObservableCollection is a read-only wrapper around the ObservableCollection. The ObservableCollection represents a dynamic data collection that provides notifications when items get added, removed, or when the whole collection gets refreshed.
    8. In Silverlight, there is no DataTemplateSelector class. In WPF, this class provides a way to choose a DataTemplate based on the data object and the data-bound element.
    9. Routed commands are not available in Silverlight.


    Page navigation in WPF:
    1. Windows Presentation Foundation (WPF) supports browser-style navigation that can be used in two types of applications: standalone applications and XAML browser applications (XBAPs). 
    2. To package content for navigation, WPF provides the Pageclass. You can navigate from one Page to another declaratively, by using a Hyperlink, or programmatically, by using the NavigationService. 
    3. WPF uses the journal to remember pages that have been navigated from and to navigate back to them.
    4. Page , Hyperlink, NavigationService, and the journal form the core of the navigation support offered by WPF.

    WPF Animation:
    1. In WPF, you animate objects by applying animation to their individual properties. For example, to make a framework element grow, you animate its Width and Height properties. To make an object fade from view, you animate its Opacity property. • It must be a dependency property.
    2. DoubleAnimation creates a transition between two double values. To specify its starting value, you set its From property. To specify its ending value, you set its To property.
    3. The Storyboard has to know where to apply the animation. Use the Storyboard.TargetName attached property to specify the object to animate.
    4. The easiest way to apply and start a Storyboard in XAML is to use an event trigger. This section shows how to associate the Storyboard with a trigger in XAML.
    5. The Visual State Manager allows you to create "states" of objects and then move to those states. Moving to those states can be done through code(just one line of code), or by using behaviors.