Wednesday, 23 May 2012

FAQ's - WPF (Windows Presentation Foundation)

WPF is Windows Presentation Foundation Framework that shipped as part of the .NET Framework 3.0 . First it has shipped with Windows Vista OS in built, and is re-distributable for Windows XP or Windows Server 2008.
WPF is Object Oriented , XAML based.
  • It Uses DirectX Engine for rendering GUI
  • It do not use GDI 32 programming at all as opposed to Win32 applications
  • It do not require more time or cost for graphics, drawing or animation programming
  • It is Easy to change resolution unlike win32 application
  • It is XAML Friendly.
  • It has .NET API that has integrated to XAML (Xtensible Application Markup Language)
  • Easily select the Controls unlike Win32 Controls.
  • It has the ability to create 3D graphics in windows apps
  • It contains Separate API for graphics and animation
  • Most powerful Windows UI Framework
It is used for the
  • For the better User Interface & the  Design
  • Customization of Controls
  • Integrating Flash, Direct, Win32, Windows Forms
  • For Generic consistency professional look (Using Styles like CSS in Web)WPF Provides an unified Model for producing high end GUI easily using normal XML syntax  to render output on graphics devices than using GDI components.

  • XAML stands for 'Xtensible Application Markup Language'
  • It is Declarative Markup Language.
  • It simplifies creating a UI for a .NET Framework application.
  • It can create visible UI elements in XAML , and then separate the UI definition from the run-time logic by using code-behind files. This joined to the markup through partial class definitions. XAML represents the instantiation of objects in a special set of backing types defined in assemblies.
  • It enables a workflow where separate parties can work on the UI and the logic of an application, using different tools. ex: Expression Blend and Visual Studio
  • It is Visual designer to create User friendly UI
  • XAML is not dependent on WPF or WPF is not dependent on XAML. WPF Designed to be XAML Friendly


  • Every UIElement in WPF is derived from DispatcherObject which defines a property called Dispatcher that points to the UI thread.
  • A dispatcher is used to raise calls on another thread.
  • Dispatcher can also be called as a  class that handles thread affinity.
Thread Affinity
As mentioned  above Dispatcher thread holds all UI elements. This is called thread affinity. All Most all of the WPF elements have thread affinity. If we have a background thread working, and if at all we need to update the UI thread, then a dispatcher is definitely required for this. Thus from any other thread, if at all we want to access UI component, we need to do it using Dispatcher thread.
DispatcherObject class contains two methods .
1. CheckAccess() : This method provides access to current dispatcher that an object is tied to . This returns a Boolean value as true if the current thread has access to use the object and returns false if the current thread can not use the object.
2. VerifyAccess() : The purpose of this method is to Verify  if the thread has access to the object. If the thread does not have access to the object, an exception is thrown.
If we make a call to a DispatcherObject from a non-UI thread, it will throw an exception. So if we are working on a non-UI thread, we need to update DispatcherObjects by using dispatcher.
The below picture represents object hierarchy in WPF.  It gets inherited from Object class.
WPF-object-heirarchy
Dispatcher object  represents an object associated with a System.Threading.Dispatcher.
As conclusion, we can say that, it is actually an important message loop through which all elements are managed.


  • Most of the WPF classes derive from Dependency Object. All UI Elements are derived from Dependency Object.
  • The Dependency Object class gives all the functionality of the WPF dependency property system.
  • Dependency Object defines WPF Property System.
  • System.Windows.DependencyObject is used to create Dependency Property.
  • Dependency properties are the  special property in WPF that are used to support many features in WPF.
The following are steps to create DP
1. Creating Dependency Property
  Create a Property that gets inherited from dependency object
2. Register the Property, This should be public static readonly. Visual Studio 2010 gives code snippet for this (propdp). This is the property that us used to identify target property while databinding .
3. Use Property accesses' as GetValue SetValue , GetValue is used to Read the property and SetValue is used to write the property .
Below is the example for this
01.class Foo : DependencyObject
02.{
03.public int MyCustomProperty
04.{
05.get return (int)GetValue(MyCustomPropertyProperty);
06.}
07.set { SetValue(MyCustomPropertyProperty, value);
08.}
09.}
10. 
11.//Using a DependencyProperty as the backing store for MyCustomProperty.
1.//This enables //animation, styling, binding, etc...//Registering the property
2. 
3.public static readonly DependencyProperty MyCustomPropertyProperty =
4. 
5.DependencyProperty.Register("MyCustomProperty"typeof(int), typeof(Foo), new UIPropertyMetadata(0));
6.}
While registering we need to pass the parameters as Name, Type, Type that owns property and the metadata that contains property  .
Meta Data Contains Default Value of properties information.


WPF has Presentation Framework, Presentation Core & Composition Engine (MIL).
Each one sit on the top of the other in the following order
1. Composition Engine
2. Presentation Core &
3. Presentation Framework
WPF uses 3D pipeline to render everything.  It uses 3d hardware and graphics card while rendering, even to render 2D graphics.
clip_image002[4]
1. Composition Engine Is also called MIL, Media Integration Layer. It takes Bitmaps, Vectors, and media render them to the DirectX. MIL sits as unmanaged layer to minimize CPU usage
2. Presentation Core
It provides .NET API that uses rendering services for the MIL. During graphics programming we work with Core API.
3. Presentation Framework
Most of the important WPF elements are in Presentation Framework. Provides high-level services like layout, data binding, command handling.


Event Routing or A Routed Event is a type of event that is has the ability to invoke handlers not only on the object that raised the event but also on multiple listeners in an element tree. 
There are 3 types of events in WPF
1. Bubbling
2. Tunneling
3. Direct
Event Bubbling
It starts from Target and then bubbles up to the root  . Imagine that we have  Stack Panel inside Window , a rectangle control  inside the StackPanel.   If you we fire a bubbled event on a  rectangle ,  it will be first fired on the rectangle , then  StackPanel  and then on window .
  • Most routed events use the bubbling routing .
  • Bubbling routed events are  used to report input changes from  other UI elements.
  • All Main events Bubble.
ex: MouseDown
Event Tunneling
The order of events firing for the controls  in Event Tunneling is exactly opposite to the event Bubbling.  Do not get confused of the concept.  Let me make it very simple and clear. Imagine that we have  Stack Panel inside Window , a rectangle control  inside the StackPanel.   If we fire  a tunneled event on a Window ,  it will be first fired on the Window, then  StackPanel  and then on rectangle .
  •   All the Preview events tunnels down
ex: PreviewMouseDown
Direct Routing This is similar to the "routing" that Windows Forms uses for events .These are also called  CLR events which we all are used to in .NET environment. Only that event fires.
ex: Mouse Enter
Advantages in RealTime
Routed events support a class handling mechanism in which the class  specifies static methods that  handles routed events before  registered instance handlers can access them. This is  concept is  useful in control design as custom class can enforce event-driven class behaviors .
In the next post I will discuss practical implementation and how to use event routing in real time applications


7. What is difference between Event Bubbling Vs Event Tunneling? When to apply what?

WPF is a huge shift from WinForms . If you are planning to migrate from WinForms to WPF these are the benefits .
Benefits of WPF  over Winforms
  • Rich UI can be made very easily especially for the Windows Applications.
  • WPF Supports animations and Special Effects easily through Graphics API.
  • It has DPI settings for the application in built.
  • DataBinding makes WPF more easier to bind data from database dynamically
  • Templating (Control, Data and Item) makes extending controls or adjust controls  easily.
  • We can  add shapes, lines, and arbitrary drawings to the application using Vs IDE itself . Every component of these can be data-bound and animated, or controlled by code.
  • There are lot of things added in Graphics part colors, gradient brushes ,fancy fonts, rotations , tile brushes . Now graphically you can do anything that you want in Windows.
  • Customize the Controls, extends Custom Controls, User Controls .
  • Easy Maintainability .
Considerations – WPF over Winforms
  • Definitely costlier than Winforms but not too much costlier.
  • WPF stores its data more efficiently hence individual objects will be small, but there tend to be more objects in WPF than in WinForms .This would require more RAM than Windows Application.
  • CPU utilization will go up compared to WinForms   WPF objects onscreen takes more CPU as normal WinForms rendering (again depending on the requirement) .
When to Choose What ?
If application spends most of its time updating the screen, WPF is not the right case to choose .  ex: Applications that are written directly to DirectX.


9. What are different types of Panels in WPF ? Explain them?
10. What is difference between StackPanel, DockPanel, WrapPanel and Grid?
11. What are Primitive Controls and Look Less Controls?
12. What are different important components to know in WPF? Explain them?
13. Why do you think WPF has more power?
14. What is difference between WPF and Web Applications which do you prefer? When to choose what?
15. Is Silverlight part of WPF  or subset of WPF? What is difference between WPF and Silverlight?
16. What is the class name from which all WPF objects are derived from?
17. How did you create Dependency Object?
18. How did you implement Dependency Property?
Prism is a Framework for developing Composite or Complex applications specific to WPF or Silverlight or Windows Phone.
It uses modularity; It allows to break application into pieces can be called as Modules.
It uses design patterns like MVVM, Command Patterns, Dependency Injection (DI), and Inversion of Control (IC), Separation of Concerns to achieve loosely coupling.

Advantages

Reusability: It allows building component in one framework (WPF) and reusing it in other platforms (Silverlight).
Extensibility: Due to its design patterns nature new functionality that is to be added is easily extensible for future purpose.
Flexibility: PRISM is flexible to develop large complex applications
Team Collaboration: Simultaneous module development is possible and Multiple teams can work on different modules simultaneously.
Fault Tolerance : It allows components to be thoroughly and completely tested thus results in error free application development of better quality. 
Maintainability: The large scale complex applications developed using PRISM are maintenance friendly
Modularity: As everything is break down into modules, prism supports modularity due to this PRISM is flexible, extensible .

Components of PRISM

  1. Shell : Template that Defines structure of the UI. Shell contains several regions.
  2. Regions: Regions are used to specify specific portion of shell as elements to inject view at runtime
  3. Modules: These are major functional areas of the application. Each module need to be independent of other,
  4. Views: Modules contains number of views. Views in Prism are built using MVVM design pattern.
  5. Boot-Strapper: This component is Responsible for Creating Shell and initializing application. 
Well. Now I got some basic idea of the PRISM How to get it ?
You can download the prism framework from patterns and practices


10. How did you install and implement PRISM in real-time applications?

11.What are WPF Commands and Events

The following are important features of jQuery.
Extensibility
The jQuery Framework is easily extensible. 
DOM elements manipulations
It easily handles DOM element selections functions, manipulations, traversal and modification.
Event Handling
We can implement Event Handling at client side.
CSS manipulation
It provides the flexibility for CSS manipulation. We can apply or change CSS dynamically using jQuery.
Animations
Advanced effects and animations are possible using jQuery.
Cross Browser Compatibility
It is Consistent across all browsers.
Easy Plugins
Number of plug-in or widgets available to achieve certain functionality like paging, sorting, drag , accordion etc.




Monday, 14 May 2012

ASP.NET MVC - Table sorting & pagination with jQuery and Razor

Table sorting & pagination with jQuery and Razor in ASP.NET MVC

Introduction
jQuery enjoys living inside pages which are built on top of ASP.NET MVC Framework.
The ASP.NET MVC is a place where things are organized very well and it is quite hard to make them dirty, especially because the pattern enforces you on purity (you can still make it dirty if you want so ;) ).
We all know how easy is to build a HTML table with a header row, footer row and table rows showing some data. With ASP.NET MVC we can do this pretty easy, but, the result will be pure HTML table which only shows data, but does not includes sorting, pagination or some other advanced features that we were used to have in the ASP.NET WebForms GridView. Ok, there is the WebGrid MVC Helper, but what if we want to make something from pure table in our own clean style?
In one of my recent projects, I’ve been using the jQuery tablesorter and tablesorter.pager plugins that go along. You don’t need to know jQuery to make this work… You need to know little CSS to create nice design for your table, but of course you can use mine from the demo… So, what you will see in this blog is how to attach this plugin to your pure html table and a div for pagination and make your table with advanced sorting and pagination features.

Demo Project Resources
The resources I’m using for this demo project are shown in the following solution explorer window print screen:

  • Content/images – folder that contains all the up/down arrow images, pagination buttons etc. You can freely replace them with your own, but keep the names the same if you don’t want to change anything in the CSS we will built later.
  • Content/Site.css – The main css theme, where we will add the theme for our table too
  • Controllers/HomeController.cs – The controller I’m using for this project
  • Models/Person.cs – For this demo, I’m using Person.cs class
  • Scripts – jquery-1.4.4.min.js, jquery.tablesorter.js, jquery.tablesorter.pager.js – required script to make the magic happens
  • Views/Home/Index.cshtml – Index view (razor view engine)
the other items are not important for the demo.

ASP.NET MVC
1. Model
In this demo I use only one Person class which defines Person entity with several properties. You can use your own model, maybe one which will access data from database or any other resource.
Person.cs
public class Person
{
    public string Name { get; set; }
    public string Surname { get; set; }
    public string Email { get; set; }
    public int? Phone { get; set; }
    public DateTime? DateAdded { get; set; }
    public int? Age { get; set; }

    public Person(string name, string surname, string email,
        int? phone, DateTime? dateadded, int? age)
    {
        Name = name;
        Surname = surname;
        Email = email;
        Phone = phone;
        DateAdded = dateadded;
        Age = age;
    }
}
2. View
In our example, we have only one Index.chtml page where Razor View engine is used. Razor view engine is my favorite for ASP.NET MVC because it’s very intuitive, fluid and keeps your code clean.
3. Controller
Since this is simple example with one page, we use one HomeController.cs where we have two methods, one of ActionResult type (Index) and another GetPeople() used to create and return list of people.
HomeController.cs
public class HomeController : Controller
{
    //
    // GET: /Home/

    public ActionResult Index()
    {
        ViewBag.People = GetPeople();
        return View();
    }

    public List<Person> GetPeople()
    {
        List<Person> listPeople = new List<Person>();
      
        listPeople.Add(new Person("Hajan", "Selmani", "hajan@hajan.com", 070070070,DateTime.Now, 25));          
        listPeople.Add(new Person("Straight", "Dean", "email@address.com", 123456789, DateTime.Now.AddDays(-5), 35));
        listPeople.Add(new Person("Karsen", "Livia", "karsen@livia.com", 46874651, DateTime.Now.AddDays(-2), 31));
        listPeople.Add(new Person("Ringer", "Anne", "anne@ringer.org", null, DateTime.Now, null));
        listPeople.Add(new Person("O'Leary", "Michael", "23sssa@asssa.org", 32424344, DateTime.Now, 44));
        listPeople.Add(new Person("Gringlesby", "Anne", "email@yahoo.org", null, DateTime.Now.AddDays(-9), 18));
        listPeople.Add(new Person("Locksley", "Stearns", "my@email.org", 2135345, DateTime.Now, null));
        listPeople.Add(new Person("DeFrance", "Michel", "email@address.com", 235325352, DateTime.Now.AddDays(-18), null));
        listPeople.Add(new Person("White", "Johnson", null, null, DateTime.Now.AddDays(-22), 55));
        listPeople.Add(new Person("Panteley", "Sylvia", null, 23233223, DateTime.Now.AddDays(-1), 32));
        listPeople.Add(new Person("Blotchet-Halls", "Reginald", null, 323243423, DateTime.Now, 26));
        listPeople.Add(new Person("Merr", "South", "merr@hotmail.com", 3232442, DateTime.Now.AddDays(-5), 85));
        listPeople.Add(new Person("MacFeather", "Stearns", "mcstearns@live.com", null, DateTime.Now, null));

        return listPeople;
    }
}

TABLE CSS/HTML DESIGN
Now, lets start with the implementation. First of all, lets create the table structure and the main CSS.
1. HTML Structure
@{
    Layout = null;  
}
DOCTYPE html>
<html>
<head>
    <title>ASP.NET & jQuerytitle>
    
head>
<body>
    <div>
        <table class="tablesorter">
            <thead>
                <tr>
                    <th> value th>
                tr>
            thead>
            <tbody>
                <tr>
                    <td>valuetd>
                tr>
            tbody>
            <tfoot>
                <tr>
                    <th> value th>
                tr>
            tfoot>
        table>
        <div id="pager">
          
        div>
    div>
body>
html>
So, this is the main structure you need to create for each of your tables where you want to apply the functionality we will create. Of course the scripts are referenced once ;).
As you see, our table has class tablesorter and also we have a div with id pager. In the next steps we will use both these to create the needed functionalities.
The complete Index.cshtml coded to get the data from controller and display in the page is:
<body>
    <div>
        <table class="tablesorter">
            <thead>
                <tr>
                    <th>Nameth>
                    <th>Surnameth>
                    <th>Emailth>
                    <th>Phoneth>
                    <th>Date Addedth>
                tr>
            thead>
            <tbody>
                @{
                    foreach (var p in ViewBag.People)
                    {          
                    <tr>
                        <td>@p.Nametd>
                        <td>@p.Surnametd>
                        <td>@p.Emailtd>
                        <td>@p.Phonetd>
                        <td>@p.DateAddedtd>
                    tr>
                    }
                }
            tbody>
            <tfoot>
                <tr>
                    <th>Nameth>
                    <th>Surnameth>
                    <th>Emailth>
                    <th>Phoneth>
                    <th>Date Addedth>
                tr>
            tfoot>
        table>
        <div id="pager" style="position: none;">
            <form>
            <img src="@Url.Content("~/Content/images/first.png")" class="first" />
            <img src="@Url.Content("~/Content/images/prev.png")" class="prev" />
            <input type="text" class="pagedisplay" />
            <img src="@Url.Content("~/Content/images/next.png")" class="next" />
            <img src="@Url.Content("~/Content/images/last.png")" class="last" />
            <select class="pagesize">
                <option selected="selected" value="5">5option>
                <option value="10">10option>
                <option value="20">20option>
                <option value="30">30option>
                <option value="40">40option>
            select>
            form>
        div>
    div>
body>
So, mainly the structure is the same. I have added @Razor code to create table with data retrieved from the ViewBag.People which has been filled with data in the home controller.
2. CSS Design
The CSS code I’ve created is:
/* DEMO TABLE */
body {
    font-size: 75%;
    font-family: Verdana, Tahoma, Arial, "Helvetica Neue", Helvetica, Sans-Serif;
    color: #232323;
    background-color: #fff;
}
table { border-spacing:0; border:1px solid gray;}
table.tablesorter thead tr .header {
    background-image: url(images/bg.png);
    background-repeat: no-repeat;
    background-position: center right;
    cursor: pointer;
}
table.tablesorter tbody td {
    color: #3D3D3D;
    padding: 4px;
    background-color: #FFF;
    vertical-align: top;
}
table.tablesorter tbody tr.odd td {
    background-color:#F0F0F6;
}
table.tablesorter thead tr .headerSortUp {
    background-image: url(images/asc.png);
}
table.tablesorter thead tr .headerSortDown {
    background-image: url(images/desc.png);
}
table th { width:150px;
           border:1px outset gray;
           background-color:#3C78B5;
           color:White;
           cursor:pointer;
}
table thead th:hover { background-color:Yellow; color:Black;}
table td { width:150px; border:1px solid gray;}

PAGINATION AND SORTING

Now, when everything is ready and we have the data, lets make pagination and sorting functionalities
1. jQuery Scripts referencing
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript">script>
<script src="@Url.Content("~/Scripts/jquery.tablesorter.js")" type="text/javascript">script>
<script src="@Url.Content("~/Scripts/jquery.tablesorter.pager.js")" type="text/javascript">script>
2. jQuery Sorting and Pagination script

<script type="text/javascript">
    $(function () {
        $("table.tablesorter").tablesorter({ widthFixed: true, sortList: [[0, 0]] })
        .tablesorterPager({ container: $("#pager"), size: $(".pagesize option:selected").val() });
    });
script>
So, with only two lines of code, I’m using both tablesorter and tablesorterPager plugins, giving some options to both these.
Options added:
  • tablesorter - widthFixed: true – gives fixed width of the columns
  • tablesorter - sortList[[0,0]] – An array of instructions for per-column sorting and direction in the format: [[columnIndex, sortDirection], ... ] where columnIndex is a zero-based index for your columns left-to-right and sortDirection is 0 for Ascending and 1 for Descending. A valid argument that sorts ascending first by column 1 and then column 2 looks like: [[0,0],[1,0]] (source: http://tablesorter.com/docs/)
  • tablesorterPager – container: $(“#pager”) – tells the pager container, the div with id pager in our case.
  • tablesorterPager – size: the default size of each page, where I get the default value selected, so if you put selected to any other of the options in your select list, you will have this number of rows as default per page for the table too.
END RESULTS
1. Table once the page is loaded (default results per page is 5 and is automatically sorted by 1st column as sortList is specified)

2. Sorted by Phone Descending

3. Changed pagination to 10 items per page


4. Sorted by Phone and Name (use SHIFT to sort on multiple columns)

5. Sorted by Date Added

6. Page 3, 5 items per page


ADDITIONAL ENHANCEMENTS
We can do additional enhancements to the table. We can make search for each column. I will cover this in one of my next blogs. Stay tuned.
DEMO PROJECT
You can download demo project source code from HERE.

CONCLUSION

Once you finish with the demo, run your page and open the source code. You will be amazed of the purity of your code.
Working with pagination in client side can be very useful. One of the benefits is performance, but if you have thousands of rows in your tables, you will get opposite result when talking about performance. Hence, sometimes it is nice idea to make pagination on back-end. So, the compromise between both approaches would be best to combine both of them. I use at most up to 500 rows on client-side and once the user reach the last page, we can trigger ajax postback which can get the next 500 rows using server-side pagination of the same data. I would like to recommend the following blog post http://weblogs.asp.net/gunnarpeipman/archive/2010/09/14/returning-paged-results-from-repositories-using-pagedresult-lt-t-gt.aspx, which will help you understand how to return page results from repository.

WCF - Create, host and consume a WCF Service using the WCF Service Library template in VS 2008

Create, host and consume a WCF Service using the WCF Service Library template in Visual Studio 2008

Create a new project using the WCF Service Library template

  1. In Visual Studio 2008, create a new WCF Service Library project.  For this example I named the project MyWcfServiceLibrary image
  2. The template creates a Class Library project with the following files:
    1. IService1.cs
      1. IService1
        interface that defines a ServiceContract with the following methods (OperationContracts):
        1. string GetData(int value)
        2. CompositeType GetDataUsingDataContract(CompositeType composite)
      2. CompositeType
        Class that defines a DataContract with the following properties (DataMembers):
        1. public bool BoolValue
        2. public string StringValue
    2. Service1.cs
      Implementation of the IService1 interface
    3. App.Config
      contains sample config entries to define the endpoints for Service1
  3. Compile the project.  It should compile without any problems.

Test the WCF Service

  1. Run the project.
  2. The WCF Test Client tool should open
    1. A notification window should pop up telling you that the service is being hosted image
    2. The WCF Test Client should open.image
      1. Take note of the url (http://localhost:8731/Design_Time_Addresses/MyWcfServiceLibrary/Service1/mex)
      2. A config file is generated that contains the configuration settings you can use if you want to host it somewhere else (like IIS, WAS or your own application)
      3. You’ll see the Service available as IService1.  WSHttpBinding_IService1 is the name of the service as defined in the config file
  3. Double click on the GetData() method in the left hand pane.  Enter a value and click on Invoke. View the results.  Rejoice.image

Host the WCF Service in IIS using the Personal Webserver

  1. Create a new ASP.Net Web Application in the same solution and add a reference to the project created above.  For this example I named the project MyASPWcfServiceHost. Remember to set this project as the startup project.
  2. Create the file that will host the service (it’s a svc file)
    1. Add a new item and choose Text file image
    2. Edit the file and add the following:
      <%@ServiceHost language=c# Debug="true" Service="MyWcfServiceLibrary.Service1"%>
      1. Note the namespace (MyWcfServiceLibrary) which corresponds to the namespace of the Class Library we created earlier.
    3. Set this file as the start page.
  3. Update the config file to register the endpoint of the service.  Take a look at the config file generated by the WCF Test Client for some guidance when necessary.  (I used it a lot)
    1. Edit the web.config file and add the following


      binding=”wsHttpBinding”
      contract=”MyWcfServiceLibrary.IService1″ />


Test the hosting

  1. Run the application.  You should see a page like this: image
    1. This means our service is hosted and working.
    2. If you read through the page you’ll notice that metadata sharing is not enabled.  The page is kind enough to tell us how to turn it on (if we want).

Enable metadata sharing and test again

  1. Modifying the web.config file as follows


    binding=”wsHttpBinding”
    contract=”MyWcfServiceLibrary.IService1″ />
    binding=”mexHttpBinding”
    contract=”IMetadataExchange” />










  2. Run the application.  You should now see a page like this:image This page now tells us what to do and how to use the service.  Which is what we are going to do next.

Consume the hosted service

We’ll create a console application that uses our hosted service.  Fun :)   We can follow the advice of the test page shown above, but not now – let’s do it another way.

Create the console application

  1. Create a new console application (MyConsoleClient) in the same solution.  Remember to set it as the startup project.

Create the service proxy

We’ll use Visual Studio to do the work for us instead of running the command line as mentioned in the test page shown above.
  1. Right-click on References and select Add Service Reference.
  2. Click on “Discover”
  3. Choose the MyTestService.svc from the list (note the url) and click on OK.
    image
  4. The proxy class and config file are created and added to the project, as well as additional references.
    image
  5. In the Object Browser we see the following:
    image
    1. We have the IService1 interface, as well as a definition of the CompositeType created in the service.
    2. We also have Service1Client which is what we’ll use to consume the service.

Consume the service

  1. Add a reference to the proxy:
    using MyConsoleClient.ServiceReference1;
  2. Copy the code provided by the test page as a starting point.
  3. Use the service and display the results.
    static void Main(string[] args)
    {
    Service1Client client = new Service1Client();
    int myValue = 7;
    string serviceResponse = client.GetData(myValue);
    Console.WriteLine(serviceResponse);
    Console.ReadLine();
    // Always close the client.
    client.Close();
    }
  4. Run the application and see our output.
    image

Debugging

If you try to debug right now, you might get this message:  Unable to automatically step into the server.  The remote procedure could not be debugged.  This usually indicates that debugging has not been enabled on the server.  See help for more information.
image
  1. The “Server” refers to the hosting server, which is the ASP host.
  2. Modify the web.config file of the MyASPWcfServiceHost project to enable debugging.
    1. Modify the and set it to true.
  3. Run the project in debug mode again and you’ll be able to step into the actual GetData() method.  Pretty cool.

SSAS - Storage options

SSAS - Storage Options
  • ROLAP (Relational Online Analytic Processing)
            The detail data and the preprocessed aggregates are both stored in a relational format.
  • MOLAP (Multidimensional Online Analytic Processing):
          The detail data and the preprocessed aggregates are both stored in a multidimensional format.
  • HOLAP (Hybrid Online Analytic Processing):
           The detail data is stored in a relational format and the aggregates are stored in a multidimensional format.

More Details;

Real-Time ROLAP : All detail data and aggregates are queried directly from the
relational data source.No notification is necessary. No proactive caching is used. This may result in slow query performance, but data is always current.This setting is best for data that is changing frequently, leaving no time for cube processing, but which must always be up-to-date.

Real-Time HOLAP : Detail data remains in the relational data source. Aggregates are
in multidimensional storage. When Analysis Services is notified that the aggregates
are out-of-date, it processes the cube. It does not wait for a silence interval. While the
aggregates are out-of-date or being processed, queries are sent directly to the relational
data source. No proactive cache is used. This provides better performance for queries
when the aggregates are up-to-date, but reverts to slow performance while processing.
This setting is best for data that is also changing frequently, but provides some
intervals for processing.

Low-Latency MOLAP : Detail data and aggregates are in multidimensional storage.
When Analysis Services is notified that the aggregates are out-of-date, it waits for a
silence interval of ten seconds before beginning processing. It uses a silence override
interval of ten minutes. While the cube is processing, queries are sent to a proactive
cache. If processing takes longer than 30 minutes, the proactive cache is dropped and
queries are sent directly to the relational data source. This provides fast query response,
unless processing takes longer than 30 minutes. Maximum latency is 30 minutes.
This setting is best in situations where query performance is important but data must
remain fairly current.

Medium-Latency MOLAP : Detail data and aggregates are in multidimensional
storage. When Analysis Services is notified that the aggregates are out-of-date, it waits
for a silence interval of ten seconds before it starts processing. It uses a silence override
interval of ten minutes. While the cube is processing, queries are sent to a proactive
cache. If processing takes longer than four hours, the proactive cache is dropped and
queries are sent directly to the relational data source. This provides fast query response,
unless processing takes longer than four hours. Maximum latency is four hours.
This setting is best in situations where query performance is important and a bit
more latency can be tolerated.

Automatic MOLAP : Detail data and aggregates are in multidimensional storage.
When Analysis Services is notified that the aggregates are out-of-date, it waits for
a silence interval of ten seconds before it starts processing. It uses a silence override
interval of ten minutes. While the cube is processing, queries are sent to a proactive
cache. The proactive cache is not dropped, no matter how long processing takes. This
provides fast query response at all times, but it can lead to a large latency if processing
is long-running.
This setting is best in situations where query performance is the most important
factor and a potentially large latency can be tolerated.

Scheduled MOLAP: Detail data and aggregates are in multidimensional storage.
Analysis Services does not receive notification of data source changes. Instead, it
processes automatically every 24 hours. While the cube is processing, queries are sent
to a proactive cache. The proactive cache is not dropped, no matter how long processing
takes. This provides fast query response at all times, but it has a maximum latency of
24 hours
, plus the time required for processing.This setting is typically used in situations where a notification mechanism is not available or where data updates occur nightly.

























Friday, 27 April 2012

Data warehousing - OLAP Vs OLTP

OLTP vs. OLAP

(source: http://datawarehouse4u.info/OLTP-vs-OLAP.html)


We can divide IT systems into transactional (OLTP) and analytical (OLAP). In general we can assume that OLTP systems provide source data to data warehouses, whereas OLAP systems help to analyze it.




olap vs oltp

- OLTP (On-line Transaction Processing) is characterized by a large number of short on-line transactions (INSERT, UPDATE, DELETE). The main emphasis for OLTP systems is put on very fast query processing, maintaining data integrity in multi-access environments and an effectiveness measured by number of transactions per second. In OLTP database there is detailed and current data, and schema used to store transactional databases is the entity model (usually 3NF).

- OLAP (On-line Analytical Processing) is characterized by relatively low volume of transactions. Queries are often very complex and involve aggregations. For OLAP systems a response time is an effectiveness measure. OLAP applications are widely used by Data Mining techniques. In OLAP database there is aggregated, historical data, stored in multi-dimensional schemas (usually star schema).


The following table summarizes the major differences between OLTP and OLAP system design.



OLTP System
Online Transaction Processing
(Operational System)

OLAP System
Online Analytical Processing
(Data Warehouse)

Source of data
Operational data; OLTPs are the original source of the data.
Consolidation data; OLAP data comes from the various OLTP Databases
Purpose of data
To control and run fundamental business tasks
To help with planning, problem solving, and decision support
What the data
Reveals a snapshot of ongoing business processes
Multi-dimensional views of various kinds of business activities
Inserts and Updates
Short and fast inserts and updates initiated by end users
Periodic long-running batch jobs refresh the data
Queries
Relatively standardized and simple queries Returning relatively few records
Often complex queries involving aggregations
Processing Speed
Typically very fast
Depends on the amount of data involved; batch data refreshes and complex queries may take many hours; query speed can be improved by creating indexes
Space Requirements
Can be relatively small if historical data is archived
Larger due to the existence of aggregation structures and history data; requires more indexes than OLTP
Highly normalized with many tables
Typically de-normalized with fewer tables; use of star and/or snowflake schemas
Backup and Recovery
Backup religiously; operational data is critical to run the business, data loss is likely to entail significant monetary loss and legal liability
Instead of regular backups, some environments may consider simply reloading the OLTP data as a recovery method

Thursday, 26 April 2012

ASP.NET MVC - Set width to Dropdownlist

How to set the width for the dropdownlist in ASP.NET MVC

when using anonymous objects to pass attributes like width you only need @ if the attribute is a c# reserved word. For example, lets say you want to set the css class you would put

@Html.DropDownListFor(model => model.WidgetName, new SelectList(ViewBag.WidgetsDetail, "WidgetName", "WidgetName"), new { class="ddl })

However, because in c# the word class means define a new C# class (object) the compiler would cause an error and not allow you to compile. The way around this is to use @class, which tells the compiler "I want to name this property class".

For properties like id and style, you do not nead the @ since it's not part of the C# language definition. so this will work:
@Html.DropDownListFor(model => model.WidgetName, new SelectList(ViewBag.WidgetsDetail, "WidgetName", "WidgetName"), new {id="ddWidgets", style="width:500px"})