ContentPresenter vs Content in Silverlight

I often confuse of contentPresenter with styles and controltemplate. Now i found the difference. To understand ContentPresenter we need to be clear on controls classification and how it works in Silverlight, so hold your breath.

There are two choices or types of controls that we can create.
  • Controls which are extended from System.Windows.Controls.Control. There are many controls of this type. These are normal controls which can be templated by ControlTemplate. Eg:- TextBox, DatePicker, DataGrid

  • Controls which are extended from System.Windows.Controls.ContentControl. There are few controls of this type. These are called as content controls & expose a special property by name Content. These are also templated by ControlTemplate. This namespace is a sub namespace of the above namespace Eg:- TextBox, DatePicker, DataGrid.
Both of them can be template by ControlTemplate but the difference in our context is content controls with a Content Property.


Note: UserControl is one exception. Even though it not extended from Contentcontrol name space hierarchy it has Content Property. we cannot controlTemplate the UserControl

Content Property of the control
The main difference we can finally arrive is Content Property. How can we use this property efficiently? Let's define it

        "Content Property expects anything of type's string, object, date time or another control itself".

One interesting this is it can be set with another control content. Controls can be simple a tooltip, button or composite controls like stack panel, Grid or user control. This can be used to change what a Button displays on them like background image or to change what a tooltip displays apart from normal text.


Let's take an example of Button and create button that uses Content and ControlTemplate. The image below contains two Buttons first one using the control template and Second one using Content. First one doesn't look like a button because Control template removes all the default styles like mouse over, click effects, more on how control template behaves is out of context. Lets examine XML of the two buttons to know more differences.

If you see the second button you can set Content property to a composite control without losingbutton default styles. But the first button it loses all the styles. Similarly you can set programmatically

XAML Buttons

<Button Height="200" HorizontalContentAlignment="Left" >


        <Border BorderThickness="1" BorderBrush="Black">

          <StackPanel Orientation="Vertical">

            <Image Source="Mahesh_Email.JPG" />

            <TextBlock Text="Using ControlTemplate Property"/>






<Button Height="200" HorizontalContentAlignment="Left" >
      <StackPanel Orientation="Vertical">
         <Image Source="Mahesh_Email.JPG" />

         <TextBlock Text="Using Content Property" />




Sometimes you need to use the ControlTemplate of a control to change the look and feel of the control. Like change the appearence how a textbox, ToolTip renders. Similarly If the end-user sets the content property value, we might want to render the content with different styles on the control.  This is where ControlPresenter is helpful. There are some rules for usage of it.
  1. You are defining the style of the control.
  2. You want to use the ControlTemplate to re-define the Styles of the control
  3. Control should be a control extended from ContentControl which mean it should have Content Property
The ContentPresenter tag will be used in controltemplate to render the content that is set on the actual control XAML declaration. To demonstrate I have created a sample with two buttons that displays different tooltips that uses the contentpresenter.

  1. Tooltip on the first button is displayed with a default behavior some applied color styles.
  2. Tooltip on the second buttons uses a controltemplate and in it we use contentPresentor to render composite Control which looks like it. I have used check box to render on the control. You can add any controls similarly on the contentcontrol.  

The XML Used

Difference between ASP.NET and ASP.NET MVC

When developers start learning ASP.NET MVC they always compare ASP.NET with ASP.NET MVC. Comparison is always good in evaluating product in difference versions or between the two flavors of products. In this case there are differences, even though ASP.NET MVC is built on top of ASP.NET.
MVC is using ASP.NET runtime framework and some core features and classes but not everything. The programming style is completely different. Using this article I am trying to show you the main differences that are helpful for you two evaluate the two products.

There is lot of differences between them and ASP.NET has more advantages than MVC. This article is not to discourage MVC, it has real advantages, if designed properly and used in right application. The architectural differences are the advantages of the MVC framwork.

You need .NET framework to install ASP.NET.You need .NET framework & ASP.NET to Install MVC.
Supports Code behind page coding & Inline codingSupports both Code behind page coding & Inline coding but, we should not use code behind as a practice because view should not perform any logic.
Pages are called PagesPages are called Views
There is a Life cycle for every page.There is tailored lifecycle of the page. By default you won't see the events when you create the Views but, you can add the Page Load event by in a script server tag. Again its not a good practice
Page supports PostBackView doesn't support Postback
We use Viewstate concept extensively There is no Viewstate for view. There is no state of the controls. But state of the entire page can be maintained by a feature ModelBinders
Every Page is inherited from System.Web.UI.ViewPageEvery Page is inherited from System.Web.Mvc.ViewPage. View page is inherited from System.Web.UI.Page.
You don't have the strongly typed pagesYou can create the Strongly typed Views using generics. It means, you can pass the object (Model) to the view page from the controller.
Has lot of inbuilt Controls that support RAD.We cannot use the ASP.NET controls because they don't support the ViewState and Postback.

We have inbuilt methods called HTML Helper methods. These methods just create the required HTML in the response stream. You can create the user controls.
Has the limited control over the HTML being generated by various controls.Since we have no controls and are writing HTML we have control over the markup.
Logic is not completely modularized in pages.Logic is modularized in methods called Action methods of the controller.
Difficult to test the UI Logic using unit tests. MVC is designed to unit test every part of the application. It strongly supports the TDD approach.
Doesn't support clean or search engine friendly URL's . ASP.NET 4 has the routing module or else
we need to use URL rewrites.
Support clean or search engine friendly URL's
You can design to support the REST based resources in application.
Code behind supports only one aspect of separation of concerns.Mainly designed for Separation of Concerns.
Web requests are reached directly to the intended page. Web users can identify the pages on the server. Web request finally will reach the controller. Requests never reach Views. Web user cannot identify a specific view on the server.
If you rename the web pages the URL is changedYou don't need to change the URL, even if you change the Controller and the View.
URLS are determined by the folder structure of the pagesYou have to define the URL formats which are called Routes. Framework will try to match the URL with all the defined routes in an order.
Framework will hand over the request to the corresponding route Handler.
Query string are used as small inputs to the pagesURLS formats drive the inputs to the requests. You can also have querystrings
Related Pages are separated by folderRelated Views are written under controller. And for each controller we need to create a folder for all its views.
We have ASP.NET AJAX Framework and AJAX server side controls to support AJAX page developmentMVC has some AJAX features but internally it uses the ASP.NET AJAX script libraries. So we have to manually include the libraries in the project. No support of AJAX Server side controls.
File extensions in IIS are mapped to ASP.NET isapi dll and in web.config they are mapped to corresponding file HTTPHandlers.There are no file extensions for MVC. If deployed in IIS7 Internally it will use the MVC UrlRoutingModule to route the request to the MVC framework.
All the Page requests are handled by PageFactory Handler. Each Route has the option to use a default Route handler or custom handler. So all the page requests are handled by Route handles.
It's difficult to modify the internal behavior of the core ASP.NET components.It's designed to modify or replace the internal components. It supports the Plug-in structure

Example: - ASPX Pages are used to render the HTML. You can configure to not to use ASP.NET pages and use different view engines.

There are many view engines available in market or you can create your own view engine.

To learn more on ASP.NET MVC, please go through my other post

ASP.NET MVC Presentaion

When I was learning ASP.NET MVC parllely i have created a Presentation of it. I tried to capture concepts, Features of MVC into one Presentation. It is a Mashup from different ppts available on the internet and including my own content. NerdDinner PDF Tutorial written by scott Guru was very helpful in understanding the new web programming. This has complete concepts of ASP.NET MVC Download . This Powerpoint targets ASP.NET MVC 1.0 and has helped me to train the resources.

One Quick suggestion, Read the tutorial and develop a small sample MVC application in Parallel . MVC development is completely different to what we been working on ASP.NET web fams. ASP.NET and its controls does lot of web functionality but in MVC we have to program every thing what we need.  The programming paradigm is completely changed, this might get you into an immpression that ASP.NET is better than MVC. Yes, its correct but i would suggest not to compare both of them for every application. MVC is not suited for every web application buts its best suited for certain web applications if designed properly like news, ecommere and Blogg site. To more precise it is apt for medium range content related sites. Finally MVC is not going to replace ASP.NET webfarms.

Thanks to Scott Guru & Enjoy the new flavour of web programming :).

ASP.NET MVC Paging Helper Function

As we know ASP.NET MVC is built on top of but it doesn't support the controls. A valid statement about MVC is it don't support postback, viewstate concepts. This is one disadvantage of MVC after we have seen rich controls and its capabilities in ASP.NET. Developers have to write every Piece of code. This has led to write some custom generic methods to generate html which represents a control. In MVC we have some basic methods called HTML Helper functions. This has methods which generates html that corresponds to basic HTML controls. Over the time community has developed their own Html Helper methods.

MVCcontrib is an open source project to enhance the MVC framework by adding the rich features. This has UI helpers for Grid and Its Pagination. These Helpers will work on the Model classes. One disadvantage with them is complete data for the grid should be available beforehand. This is difficult to maintain if the data is more. It's always good to load the data that is required to render on the page.
I want something simple and work as loosely coupled control. I have created an html helper method. This method named PagingHelper is an extension method of HTMLHelper class. I have two versions of this one normal and other supports Ajax requests. The control looks like below images

How to integrate to your Solution
  1. Create a stored procedure with following parameters
    1. Input
      1. Output records criteria, which returns the records
      2. Total number of records to be displayed
      3. Current Page number
    2. output
      1. Total number of pages for the above criteria
      2. Select statement which return the records with the criteria for the sent page number
  2. Create a property in the controller
SetPageIndex proerty

private int SetPageIndex()
int page = 1;

if (Request.QueryString["page"] != null)
  if (Int32.TryParse(Request.QueryString["page"], out page))
     ViewData["IndexPage"] = Request.QueryString["page"];
return page;


  1. Create an action method in a controller
    1. Create a Action Method which handles the grid or paging
    2. ViewData["IndexPage"]=this.SetPageIndex(). Use this value in the view.
  2. Copy the below extension method to you application
    1. Copy the extension methods to a static class
  3. Use the helper method in the View page
    1. Import the namespace of the above static class in the view
    2. Use the blow code to call the view
    <%= Html.PagingHelper("Controllername", "actionMethodname", ViewData["TotalPages"], Convert.ToInt32(ViewData["IndexPage"]))%>
  4. Create Css paging styles
CSS Styles
padding: 3px;

font-weight: bold;

text-decoration: none;


border-style: solid;

border-width: thin;

border-color: black;

padding: 3px;

background-color: #C0C0C0;
text-decoration: none;


  1. URL Format generate
The URL that is generated is in the below format. The paging values goes as query strings because I believe non functional data like paging, sorting should go as querystrings

HtmlHelper Extension Method

public static string PagingHelper(this HtmlHelper hlp, string ActionName, string strControllerName, int intTotalPages, int intSelected, string pagelinkCssClass, string pagelinkCssClassSelected)

StringBuilder str = new StringBuilder();


if (intTotalPages > 1)


int _rlow, _rhi;

int _prev, _next;

int _first = 1;

int _last = intTotalPages;


if (intSelected < 5)

  _rlow = intSelected - (intSelected % 5) + 1;
if (intSelected % 5 == 0)

  _rlow = (intSelected - 5) + 1;

_rlow = intSelected - (intSelected % 5) + 1;

//this is previous

if (intSelected == 1)

_prev = 0; // no need to show prev link
_first = 0; //no need to show first link
else{  if (_rlow == 1){
    _prev = 1;
   _prev = _rlow - 1;
str.Append(hlp.ActionLink("<<", ActionName, strControllerName,
                         new { page = _first }, new { @class = pagelinkCssClass }));

str.Append(hlp.ActionLink("<", ActionName, strControllerName,
                         new { page = _prev }, new { @class = pagelinkCssClass }));


 if (intSelected % 5 == 0)
_rhi = intSelected;

_rhi = intSelected + (5 - (intSelected % 5));

if (_rhi > intTotalPages)

_rhi = intTotalPages;

for (int i = _rlow; i <= _rhi; i++)

object objAttrib = null;

if (i == intSelected)
objAttrib = new { @class = " pagelinkCssClassSelected" };
objAttrib = new { @class = " pagelinkCssClass" };
str.Append(hlp.ActionLink(i.ToString(), ActionName, strControllerName,
                          new { page = i }, objAttrib));str.Append("&nbsp;");

//this is next

if (intSelected == intTotalPages)
{_next = 0; //no need to show the next link
_last = 0; //no need to show the last link

_next = intSelected + 1;
str.Append(hlp.ActionLink(">", ActionName, strControllerName,
                         new { page = _next }, new { @class = pagelinkCssClass }));

str.Append(hlp.ActionLink(">>", ActionName, strControllerName,
                         new { page = _last }, new { @class = pagelinkCssClass }));

return str.ToString();


You can create an AJAX version of the same thing by changing HtmlHelper.ActionLink to AjaxHelper.ActionLink

Other recommendations
  1. Create a Pager HTML Helper by Stephen walther
  2. Add Paging Functionality to your ASP.NET MVC Site


Until ASP.NET MVC 1.0 we have some default folder structure that ASP.NET MVC runtime expects to be. All the controller classes to be in the controller folder and views should be under views\controllerName folder. We really want to group the controllers & views based on the functionality because we don't want to have all under single folder, more over it will become difficult for us to find the functionality. To resolve this problem ASP.NET MVC 2.0 has a very interesting and useful feature named AREAS. Areas are like modules in application software. This has made the developers and architects to work on different modules without disturbing the others. What is this something to ASP.NET MVC?
We have been working on different modules in web farms by creating folder for each piece of functionality in application. This cannot be done in ASP.NET MVC, we don't have the flexibility to create folders as our wish. The reason being, ASP.NET follows convection over configuration.

Separation of Concerns is a solution of the problem, not in terms of technical but in terms of conceptual. Over the time technical geeks has spent time in customizing the MVC 1.0 framework for getting this flexibility. Now this has been given as a feature in Asp.NET MVC 2.0, which is important and widely accepted feature in community.

So how Areas are defined? And how are they are different in terms of URLS? In 1.0 for the entire project we have one folder for controllers and one folder for views. Now in 2.0 the basic rule remains the same but the rule is modified to area. So you can create different areas. In Web project there is folder called Areas which contains different areas folders named by area name.

Namespaces in Areas
There is a strict rule in terms of naming areas.
Every area should be defined in
<Application namespace>.Areas.<Area Name>.
Controllers should be defined in <Application namespace>.Areas.<Area Name>.Controllers

URLS in Areas
Let's go to the actual problem, if the application is big and has may URL Routes, it's difficult to maintain all routes in one location which is global.aspx. Developers have to take an effort to group routes and maintaining this is an issue.
In MVC 2.0 we can define the Area specific routes under the area folder. For every area you have a class file by name <AreaName>AreaRegistration.cs . The class defined in this file is extended from a mvc framework class AreaRegistration. We can define all the routes in below method


Area URL Registrations

public override void RegisterArea(AreaRegistrationContext context)
new { controller = "BAB", action = "SelectInvoices", id = UrlParameter.Optional }

Migration of code from 1.0 to 2.0 Area
There is no migration tool to migrate from 1.0 version to 2.0. When I tried migrating project, I just moved the files from root level folders to area level folders, the process failed to run because runtime expects namespaces to be in the above formats. It tries to load the specific area controller by looking into the URL and namespaces. We have to takecare the namespace issues manually.

Web.Config in Views folder
Pages also called views are available in the views folder. In MVC views are not directly exposed to outside by URLS. All the view requests should go to the controller and it will render the exact view using the inputs from URL. Views are normal web pages, so they can be accessible a URL. To restrict direct accessing of views, we use web.config file in views folder. The web.config has a default handler mapping to blocks all the pages which has extension ASPX. If we want to add restrictions to other types of files we can add a handler mapping for the extension and HttpNotFoundHandler. We need to modify the mappings at two locations for IIS6, IIS7(Classic Pipeline) and IIS7 Integrated Pipeline.

Web.config mappings

//For IIS6, IIS7(Classic Pipeline)
<add path="*" verb="*"type="System.Web.HttpNotFoundHandler"/>

//For IIS7
<validation validateIntegratedModeConfiguration="false"/>
<remove name="BlockViewHandler"/>
<add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode"

Web.Config in Area folder
Similarly for views, there is a web.config file for each area serving the same purpose. This is to restrict access of ASPX files. If we don't want to restrict them at area Level, we can delete this web.Config file.

Application settings in Web.Config
There are many web.config files; can we have application settings of areas in area specific web.config file? The answer is No, we cannot or have or override the appsettings configurations. All the application settings should be defined in the web.config of the root folder
 Authentication & Authorization in AREAS
Sometimes we need to have different security permissions to different areas; this can be achieved by <Location> element in web.config file. This concept is not new in MVC, it has come from There is one difference between Web farms and MVC in terms of path for the location Element.
  1. In Web Farms for path attribute corresponds to folder or page relative path
  2. In MVC since we don't deal with folders, path attribute corresponds to URL. We need to mention the Area Name in path, since all the URLS of an Area starts with the Area name

    <location path="Area1">

Authorization in Web.config

<location path="Area1">
<authentication mode="Windows" />
<allow roles="role1,role2"/>
    <deny users="*"/>

<location path “Area2">
<authentication mode="Forms">
  <forms loginUrl="Logon.aspx" name=".ASPXFORMSAUTH">
  <allow roles=" role3,role4"/>
  <deny users="*"/>

All other things like master page creation, Error handling works same as in MVC 1.0

Please provide your valuable comments.

Try Commerce Server 2009 Evaluation VPC

To promote Microsoft Commerce Server 2009 Solution for Ecommerce platform, Microsoft is providing the Commerce Server 2009 Virtual PC (VPC) which is equipped with full Installation of all required software’s. This helps the users to quickly evaluate the sowftware. Nothing to configure, just use it to evaluate the Software.

You can download the VPC on Microsoft connect site, you need to do special registration for downloading the VPC. Once you register the download is available only after two to three days in the same site. Important thing to remember is there will be no communication on the download and its availability from Microsoft. You can download with MSDN Software downloader. This VPC is recently updated (June 2010) with extended Expiry time.

Please follow the link to register. Register

CS2009 VPC Setup:
  • This VPC is a multi file (4) download zipped with WINRAR tool. Please download all the items to a Folder.  
  • Extract the VPC by clicking the file CS2009VPC-1004.part01.exe. to the folder. 
  • Download the Microsoft Virtual PC software from the Microsoft downloads: Download
  • Create the Virtual machine by selecting the existing Cs2009 VHD settings file extracted above.  
  • Start the Virtual PC. 
  • Login to the server using credentials provided in the extracted VPC readme file.  
  • Explore & Discover CS2009. 

CS2009 is not a straight installation. It’s an update on CS2007 installation. So Installation is scattered in to two different program file folders.

Pre Installed Softwares:

  • Windows server 2008 which expire in limited time.  
  • SharePoint server 2007 
  • SQL Server 2008 
  • Commerce Server 2009
  • Silverlight 3 & its SDK 
  • Microsoft Enterprise Single Sign-on  

Readily configured with:
  • A Sample catalog with categories & products. 
  • A fully functional e-commerce website on SharePoint server, which works with above default catalog. 

Things to evaluate:

Videos on the Commerce server 2009 to get the feel of the various concepts. This works for starters 
  • Few Demo Scripts which are lab manuals to learn & practice few scenarios as per manuals 
  • Documentation for understanding commerce server Business user tools and the domain of the CS2009
    • Catalog manager 
    • Customer & Order Manager 
    • Marketing manager
    • Catalog & Inventory manager
  • Go thru fully configured SharePoint ready to use ecommerce website. This site is made of many Web parts specially designed for CS2009. This is a good starting point to see the changes done on the business user tools
  • Complete Documentation on commerce server covering architecture, Features, configurations & different Programming API for developers to extend CS2009
  • Documentation for Migration of 2002 & 2007 to 2009 version.
  • Pipeline tool to customize various pipelines available in CS2009

Sample Source Code for Extensibility:

 Various components source code is provided with VPC for deeper understanding the extensibility of various systems and components of CS2009. This really helps the developers to quickly jump in to programming and customization. 
  • CS2009 Partner SDK which contains the source code & documentation for Business user tools, we can customize and redistribute the tools as per license agreement.
  • CS2009 SDK which contains samples for customizing various extensibility features of CS2009
  • CS2009 SharePoint Extensibility Kit which contains the source code for webparts, Site Code, Site features, Silverlight code for Inline Product editor
  • CS2007 SDK which contains the source code for adapters, Pipeline registration tool.  


I wrote this article to ease the new audience in understanding the VPC, since I have spent much time in knowing the above information.  To know more on CS2009 functionality please read the article below
Disclaimer: The VPC is to be used only for demonstration and evaluation purposes. Please follow the License agreements of VPC and CS2009 software.

E-Commerce solution using Microsoft Commerce Server 2009

With the increase of trust towards online transactions, online shopping has becoming the best choice of selling &amp; buying products these days. Not every product needs to sell in an outlet. Enterprises started to sell their products through web as one medium.

To start any E-commerce business, at high level everyone needs to concentrate on two things
1. Product offering:
  • This is the most important for the enterprises to provide wide
    variety of products for their customers.
  • Quickly reach out to the dynamically changing markets.
  • Dynamically change their business model to increase the sales
    of the products
  • Concentrate on coming out with new products.
  • Compete with the competitors.
  • Establish the brand value.
2. IT tools to host website and Process the orderes
  • E-Commerce website for selling products
  • Catalog management system for managing products and its information.
  • Order Management System for processing orders placed on websites.
  • Campaign Management System for discounts, coupons, Ads.
  • Customer Management System for customer reach.
  • Integration with other apps
To reach the market quickly, every big and medium sized E-commerce business needs the above mentioned necessary tools to host the solution and concentrate on the growth of the business.

To develop all these systems it takes more in time and cost. They don’t
want to wait until IT tools are being developed. Enterprises have to hit the markets soon and get successful in their branding, sales and revenues. Instead of reinvent the whole wheel everyone need a ready to use Ecommerce Solution for hosting their business.

Microsoft is providing a solution Commerce Server 2009 as a server product, which contains all necessary &amp; extensible tools, infrastructure for hosting solutions. Microsoft is developing &amp; improving product since 2002. The current version is more matured and flexible in terms of making customizations to it. It’s built over .NET. Every internal system is provided with a managed API for accessing the data and displaying the data.

Basic Management Features

Catalog management
  • Maintaining product Hierarchy, categorizing products in
  • Creating temporary catalogs with Virtual catalogs.
  • Catalog &amp; Products creation along with Globalization.
  • Maintaining the data to ease for retrieval and searching.
  • Product Inventory management is part of it.
  • Ability Customizing the information stored on the products, categories by modifying the schema as per the needs.

Campaign Management
  • Easily creation of marketing campaign for marketing team.
  • Creating various types of Discounts.
  • Creation of coupon codes associated with the discounts.
  • Creation of various types ads for external & internal users
  • Collecting &amp; Maintaining of information about Impressions and Clicks
  • Generating standard reports for the marketing teams
  • Publishing of created ads with an approval workflow.
  • CSF(Content Selection framework)
Order management
  • Inbuilt Shopping cart for ecommerce web sites.
  • Applying the discounts on shopping cart items with discounts
  • Collection of credit card details.
  • Creation of orders with prober billing &amp; shipping details.
• Profile management
  • Maintaining customer information including logging credentials.
  • Storing addresses and credit card details.
  • Shipping information.
 New Features
  • SharePoint integration :
    • Ready to use ecommerce Site template for hosting the on to the web.
    • More than 30 inbuilt web parts were given to communicate with information available in Commerce server.
  • New Multi Channel Foundation API
    • Alternate API for the existing API. This is designed for better retrieval with performance.
    • Channel aware API, so that the same API is used for sending data to different sources like mobile, gaming consoles.
  • Better UI Tools
  • Information and navigation is improved.
  • We can install the tools anywhere in your network.
  • Integration to Live ID(optional)
  • Integration with LOB made easy with BizTalk and its Adapters.
  • Report Analytics with Microsoft BI Platform.
  • Better Migration features.
  • Improve Security management with Azmen.
  • Many more.
Many of the successful Ecommerce websites are hosted with Commerce Server platform. It has been designed for better extensibility, so that you can integrate CS2009 to your line of business application.

Microsoft has been encouraging the use of Commerce Server product by providing the Virtual PC with complete installation of all the required software. Please download and evaluate. There are many third party software which offers Ecommerce solutions, But Microsoft as a platform has all the required tools &amp; technologies to support your Ecommerce Solution.