All posts by dotte

Introduction to ApplicationHost.config

Introduction

ApplicationHost.config is the root file of the configuration system when you are using IIS 7 and above. It includes definitions of all sites, applications, virtual directories and application pools, as well as global defaults for the web server settings (similar to machine.config and the root web.config for .NET Framework settings).

It is also special in that it is the only IIS configuration file available when the web server is installed (however, users can still add web.config files if they want to). It includes a special section (called configSections) for registering all IIS and Windows Activation System (WAS) sections (machine.config has the same concept for .NET Framework sections). It has definitions for locking-down most IIS sections to the global level, so that by default they cannot be overridden by lower-level web.config files in the hierarchy.

The location of the file is currently in the system32\inetsrv directory, but this is expected to change after beta2 to system32\inetsrv\config. This document walks through all the sections, in the order they appear in the file, and explains them one by one. The most complex section is system.webServer, so it is recommended for the reader to not skip reading the description for that section in particular.

Note the following:

  1. This document specifies the content of each configuration section, as appears in applicationHost.config. By design, many of the sections are empty or not complete (only some of their content appears in the XML). The rest of the values are taken from the schema defaults. This is done to avoid too much information and cluttering of the file, and in order to keep it reasonably readable.

For full schema reference, including default values for all properties in every section, their valid ranges, etc., refer to %windir%\system32\inetsrv\config\schema\IIS_Schema.xml (for IIS settings), or ASPNET_Schema.xml (for ASP.NET settings), or FX_Schema.xml (for other .NET Framework settings).

For convenience, chunks of these files are included in this document in the appropriate sections so the reader can understand which properties are available, what the default values are, etc., for each section. See the additional note below about how to read schema information.

2. Make a backup of the file before making any changes to it.

This document contains:

How to Read Config Schema

As noted above, this document contains snippets of schema information for each section, so the reader can discover what properties are available and what their default values and valid ranges are. The snippets are taken directly from the configuration schema file for IIS settings: %windir%\system32\inetsrv\config\schema\IIS_Schema.xml. This section explains how to read schema information.

The schema for each configuration section is defined in a XML element. There is no schema definition for section groups. The following format is used here to explain how to read the schema:

<attribute-name>="<default-value>"  [<metadata>] [<description>]

<attribute-name> is the name of the configuration attribute, as appears in XML. Every attribute must have a name.

<default-value> is the value used by default, if no other value is specified in the XML for the attribute. Not all attributes have default values (for example, site name). In this case, the syntax will be “”.

<metadata> contains several items:

  • The runtime type of the attribute. This is one of “bool”, “enum”, “flags”, “int”, “int64”, “String”, “timeSpan”. Every attribute must have a type.
  • “bool” is “true” or “false”.
  • “enum” is a set of possible values, where only one of them can be set for the attribute. Every such value has a numerical value and a friendly name. The syntax is using the character “|” as a delimiter between the friendly names: value1|value2|…|valueN.
  • “flags” is similar to “enum”, except that combinations of values are allowed. Therefore the numerical values should be in multiples of 2, so they can be ORed together to form combinations. The syntax is identical to “enum”: value1|value2|…|valueN.
  • “int” is a 32 bit integer.
  • “int64” is a 64 bit integer.
  • “String” is a character string.
  • “timeSpan” is a representation of a time unit, similar to the managed-code type TimeSpan. It can be persisted as a number (representing seconds, or minutes); or as a formatted string in the form of “[dd:]hh:mm:ss”. The “[dd:]” element represents an optional number of days. The other elements represent numbers of hours, minutes and seconds, respectively. The “timeSpanFormat” attribute specifies which format should be used: number of seconds, number of minutes, or a formatted string.
  • Required attributes are marked “Required”. It means that a value for them must be set in the XML. For example, site name is a required attribute (every site must have a name in IIS 7.0 and above).

<description> is a short description of the attribute.

Section Schema

The <sectionSchema> XML element is the base unit of schema information. All other schema information is specified within it. It has one attribute directly in it (“name”), and then the rest of the schema is in sub-elements within it:

<sectionSchema name=””  <!– [String, Required] [XML full path of the section] –> > 
    <!– sub-elements here describing rest of schema; –> 
    <!– their description is right below in the doc. –>  
</sectionSchema>

Attribute Schema

Every attribute is defined in a corresponding <attribute> XML element in the schema. The <attribute> element may be in the <sectionSchema> element directly (if the attribute is in the section scope); or in the element (if the attribute is in a sub-element within the section); or in the <collection> element (if the attribute is in a collection within the section).

An attribute schema must specify a name and a runtime type for the attribute. It may mark the attribute as required. It may mark the attribute as the unique key (if inside a collection), or as part of a collection key (together with other attributes). It may specify a default value for the attribute. It may mark the attribute for automatic encryption on-disk. It may specify if the word “Infinite” is allowed as a value for the attribute (only for numeric types such as int and in64, and for timeSpan). It may specify the timespan format (seconds, minutes or formatted string) for timespan attributes. It may specify validation rules for the attributes (see Attribute Validation section below in this document).

<attribute 
    name=""  [String, Required] [XML name of the attribute] 
    type=""  [bool|enum|flags|int|int64|string|timeSpan, Required][Runtime type] 
    required="false"  [bool] [Indicates if must be set] 
    isUniqueKey="false"    [bool] [Serves as the collection key] 
    isCombinedKey="false"  [bool] [Part of a multi-attribute key] 
    defaultValue=""  [String] [Default value or comma-delimited flags] 
    encrypted="false"  [bool] [Indicates if value persisted encrypted] 
    allowInfinite="false"  [bool] [Indicates if "Infinite" can be set] 
    timeSpanFormat="string" [string|seconds|minutes] [hh:mm:ss or number] 
    validationType=""       [See validation below] 
    validationParameter=""  [See validation below] 
/>

Element Schema

Every element is defined in a corresponding <element> XML element in the schema. Elements can be nested. An element is simply a container for other attributes, or sub-elements. It must have a name and it may serve as a container of default values for collection elements (for example, siteDefaults holds the default values for sites in the <sites> collection).

Collection Schema

Every collection is defined in a corresponding <collection> XML element in the schema. Collections contain multiple elements, which can be added and removed from them individually. Typically the collection directive names are “add”, “remove” and “clear”, but some collections use different names for clarity (for example, the collection is using “site” instead of “add”).

This is done by specifying values for addElement, removeElement and clearElement in the collection schema. If a collection directive is missing from the schema, the collection will not support it. The collection schema may specify the name of a default element that will be used as a container of default values for collection elements (this complements isCollectionDefault in the element schema).

For example, the collection is using siteDefaults as the default element. Most collections append elements as they merge configuration files down the namespace, but some may specify mergeAppend=”false” in the schema to have a prepend behavior. For example, consider two levels of configuration: applicationHost.config and web.config in a site. In applicationHost.config:

<myCollection> 
    <add value=”1″/>  
</myCollection>
In web.config:

<myCollection> 

    <add value="2" />         
</myCollection>

If the collection appends, its merged (effective) configuration at the site level will be:

<myCollection> 

    <add value="1"/> 

    <add value="2"/>     
</myCollection>

However, if it prepends, it will be:

<myCollection> 

    <add value="2"/> 

    <add value="1"/>     
</myCollection>

Some collections may allow duplicate entries by specifying allowDuplicates=”true” in their schema. This is mostly done to support legacy collections in the .NET framework (in machine.config).

Some collections may allow additional attributes in them, beyond those specified in the schema. This is done by specifying allowUnrecognizedAttributes=”true” in their schema. It is mostly done to support provider-based collections in the .NET framework.

 

<collection             
    addElement=””     [String] [Name of Add directive, if supported] 
    removeElement=””  [String] [Name of Remove directive, if supported] 
    clearElement=””   [String] [Name of Clear directive, if supported] 
    defaultElement=”” [applicationDefaults|applicationPoolDefaults|siteDefaults|virtualDirectoryDefaults] [See isCollectionDefault] 
    mergeAppend=”true”  [bool] [Indicates whether or not deepest set values are appended]   
    allowDuplicates=”false”  [bool] [Indicates if multiple elements may have the same keys] 
    allowUnrecognizedAttributes=”false”  [bool] [Indicates if non-schema attributes ok] 
/>

Enum Schema

Every attribute of type “enum” must define its enum values in a corresponding <enum> XML element in the schema. Every value must have a friendly name and a numerical value.

<enum name=””  [String, Required] [Friendly name of the enum] 
    value=”” [int, Required] [Numeric value] 
/>

Flags Schema

Every attribute of type “flags” must define its flag values in a corresponding XML element in the schema. Every flag must have a friendly name and a numerical value that can be ORed together with other values to form combinations; therefore, the value should be in multiples of 2.

<flags             
    name=””  [String, Required] [Friendly name of the flag] 
    value=”” [int in power of 2, Required] [Numeric value] 
/>

Attribute Validation

Attribute validation is done when parsing the XML to get a section from the file, and when calling the configuration API to set values. If validation fails, it fails the desired operation (getting the section or setting the invalid value).

Each attribute may associate one validator for its value. This is done by specifying the appropriate validator name in the validationType, and additional parameters in the validationParameter in the attribute schema.

The system supports these validators:

ApplicationPoolName validator

This validator fails on these characters: |<>&\”validationType=”applicationPoolName” validationParameter=””

IntegerRange validator

This validator fails if value is outside [inside] range, in integers.validationType=”integerRange” 
validationParameter=”<minimum>,<maximum>[,exclude]”

NonEmptyString validator

This validator fails if string value is set.validationType=”nonEmptyString” 
validationParameter=””

SiteName validator

This validator fails on these characters: /\.?validationType=”siteName” 
validationParameter=””

TimeSpanRange validator

This validator fails if value is outside [inside] range, in seconds.validationType=”timeSpanRange” 
validationParameter=”<minimum>,<maximum>,<granularity>[,exclude]”

TrimWhiteSpace validator

This validator fails if white space is set at start or end of value.validationType=”trimWhiteSpaceString” 
validationParameter=””

XML Header

Every configuration file is an XML file and may optionally include the following line as the first line:

<?xml version="1.0" encoding="UTF-8" ?>

In addition, it must include all its content within an XML <configuration> tags:

<configuration> 

   <!-- [All of the context goes here] --> 

</configuration>

ApplicationHost.config includes the above lines in it. The rest of this document walks throughthe rest of the sections in the file.

<configSections> Section

This is the very first section in the file. It contains a list of all other sections in the file. This is the point of registration for the sections (for example, to unregister a section from the system, remove its line from this section – no need to remove its schema file from the config\schema directory).

Note that other configuration files may have a section as well, at the very top of the file. This may be useful to register sections at levels lower than the global level. These sections will be registered for that scope of the namespace only. Web.config files can only add sections to the system; they cannot redefine sections that were registered in parent levels, and they cannot remove (unregister) sections.

The sections are structured by their hierarchy of containing section groups. Each section registration specifies the section name; the managed-code type of the section handler (this has no meaning in this file and will get removed after beta2 – it is used only by System.Configuration, so it will still exist in machine.config and web.config files); the allowDefinition level, if differs from the default; and the overrideModeDefault (this attribute is used to lockdown most IIS sections in this file).

Note: Section is the basic unit of deployment, registration, locking, searching and containment of configuration settings. Every section belongs to one section group (“immediate parent”). Section group is a container of logically-related sections, and is used solely for purposes of structured hierarchy. No operations can be done on section groups. Section groups cannot have configuration settings directly (the settings belong to sections). Section groups may be nested; section cannot.

Schema

<section 
    name=""  [Required, Collection Key] [XML name of the section] 
    allowDefinition="Everywhere" [MachineOnly|MachineToApplication|Everywhere] [Level where it can be set] 
    overrideModeDefault="Allow"  [Allow|Deny] [Default delegation mode] 
/>

Locking

Most IIS sections are locked down by default, using overrideModeDefault=”Deny” in the section. The recommended way to unlock sections is by using tags, as follows:

<location path="Default Web Site" overrideMode="Allow" > 
  <system.webServer> 
    <asp/> 
  </system.webServer>             
</location>

The above location tag unlocks the section for the default web site only. To unlock it for all sites, specify this in applicationHost.config:

<location path="." overrideMode="Allow"> 
    <system.webServer> 
         <asp/> 
    </system.webServer> 
</location>

Note: path=”.” and path=”” have the same effect. They refer to the current level in the hierarchy.

from:http://www.iis.net/learn/get-started/planning-your-iis-architecture/introduction-to-applicationhostconfig

常用RSS地址

<opml version=”1.1″><head><title>Feeds</title></head><body>
<outline text=”654085966″ xmlUrl=”http://hi.baidu.com/654085966/rss” type=”rss”/>
<outline text=”activa’s blog” xmlUrl=”http://blog.activa.be/index.php/feed/” type=”rss”/>
<outline text=”ADO.NET team blog” xmlUrl=”http://blogs.msdn.com/b/adonet/rss.aspx” type=”rss”/>
<outline text=”Alex Gorev’s Weblog” xmlUrl=”http://blogs.msdn.com/b/alexgor/rss.aspx” type=”rss”/>
<outline text=”Alibaba DBA Team” xmlUrl=”http://www.alidba.net/index.php/feed” type=”rss”/>
<outline text=”Android Developers Blog” xmlUrl=”http://feeds.feedburner.com/blogspot/hsDu” type=”rss”/>
<outline text=”Android_Tutor-51CTO技术博客” xmlUrl=”http://weizhulin.blog.51cto.com/rss.php?uid=1556324” type=”rss”/>
<outline text=”Arrange Act Assert” xmlUrl=”http://www.arrangeactassert.com/feed/” type=”rss”/>
<outline text=”ASPAlliance.com – Articles, reviews, and samples for .NET Developers” xmlUrl=”http://aspalliance.com/rss.aspx” type=”rss”/>
<outline text=”ASPNETWorld.com Blog” xmlUrl=”http://www.aspnetworld.com/blog/SyndicationService.asmx/GetRss” type=”rss”/>
<outline text=”bigholy的个人空间” xmlUrl=”http://space.itpub.net/355374/action-rss-type-blog” type=”rss”/>
<outline text=”Blog – Stack Exchange” xmlUrl=”http://blog.stackoverflow.com/feed/” type=”rss”/>
<outline text=”BPMN123″ xmlUrl=”http://www.bpmn123.net/rss.xml” type=”rss”/>
<outline text=”Channel 9″ xmlUrl=”http://channel9.msdn.com/Feeds/RSS” type=”rss”/>
<outline text=”CodeProject Latest Articles” xmlUrl=”http://www.codeproject.com/WebServices/ArticleRSS.aspx?cat=3” type=”rss”/>
<outline text=”Data story” xmlUrl=”http://data.story.lu/feed” type=”rss”/>
<outline text=”DBA@Taobao” xmlUrl=”http://feed.feedsky.com/taobaodba” type=”rss”/>
<outline text=”Developer IT” xmlUrl=”http://feeds.feedburner.com/developer-It” type=”rss”/>
<outline text=”Development With A Dot” xmlUrl=”http://weblogs.asp.net/ricardoperes/rss.aspx” type=”rss”/>
<outline text=”DotNetKicks.com” xmlUrl=”http://feeds.feedburner.com/dotnetkicks” type=”rss”/>
<outline text=”EntLib.net 技术分享平台” xmlUrl=”http://www.entlib.net/?feed=rss2” type=”rss”/>
<outline text=”Geert Bellekens’ blog” xmlUrl=”http://geertbellekens.wordpress.com/feed/” type=”rss”/>
<outline text=”Google 黑板报 – Google (谷歌)中国的博客网志,走近我们的产品、技术和文化” xmlUrl=”http://www.google.com.hk/ggblog/googlechinablog/atom.xml” type=”rss”/>
<outline text=”halilibrahimkalkan.com” xmlUrl=”http://www.halilibrahimkalkan.com/en/syndication.axd” type=”rss”/>
<outline text=”High Scalability” xmlUrl=”http://feeds.feedburner.com/HighScalability” type=”rss”/>
<outline text=”Higher Logics” xmlUrl=”http://higherlogics.blogspot.com/feeds/posts/default” type=”rss”/>
<outline text=”hunkcai的专栏” xmlUrl=”http://blog.csdn.net/hunkcai/rss/list” type=”rss”/>
<outline text=”IBM developerWorks 中国 : 文档库” xmlUrl=”http://www.ibm.com/developerworks/cn/rss/dwcn_dwtp.rss” type=”rss”/>
<outline text=”Inside Windows Live” xmlUrl=”http://windowsteamblog.com/windows_live/b/windowslive/rss.aspx” type=”rss”/>
<outline text=”Instagram Blog” xmlUrl=”http://blog.instagram.com/rss” type=”rss”/>
<outline text=”Joe On ASP.NET” xmlUrl=”http://weblogs.asp.net/joestagner/rss.aspx” type=”rss”/>
<outline text=”Journey to SQLAuthority” xmlUrl=”http://blog.sqlauthority.com/feed/” type=”rss”/>
<outline text=”Latest Blog Posts – LivingForSqlServer – SQLServerCentral” xmlUrl=”http://www.sqlservercentral.com/blogs/livingforsqlserver/feed/” type=”rss”/>
<outline text=”Latest Blog Posts – SQLServerCentral” xmlUrl=”http://www.sqlservercentral.com/blogs/feed/” type=”rss”/>
<outline text=”Latest from developerFusion” xmlUrl=”http://www.developerfusion.com/format/rss/” type=”rss”/>
<outline text=”Marcin On ASP.NET” xmlUrl=”http://blogs.msdn.com/b/marcinon/rss.aspx” type=”rss”/>
<outline text=”Martin Fowler” xmlUrl=”http://martinfowler.com/feed.atom” type=”rss”/>
<outline text=”Mikel” xmlUrl=”http://www.mikel.cn/feed” type=”rss”/>
<outline text=”MySQLOPS 数据库与运维自动化技术分享” xmlUrl=”http://www.mysqlops.com/feed/rss” type=”rss”/>
<outline text=”Nikhil Kothari’s Weblog” xmlUrl=”http://www.nikhilk.net/Rss.ashx” type=”rss”/>
<outline text=”NoSQLfan” xmlUrl=”http://feed.feedsky.com/nosqlfan” type=”rss”/>
<outline text=”N.S.thoughts” xmlUrl=”http://nightsailer.com/feed” type=”rss”/>
<outline text=”Rachel Appel” xmlUrl=”http://feeds.feedburner.com/RachelAppel” type=”rss”/>
<outline text=”Random Ravings of a Red Headed Code Monkey” xmlUrl=”http://feeds.feedburner.com/RandomRavingsOfARedHeadedCodeMonkey” type=”rss”/>
<outline text=”Ron Jacobs” xmlUrl=”http://blogs.msdn.com/b/rjacobs/rss.aspx” type=”rss”/>
<outline text=”ronghao” xmlUrl=”http://ronghao.iteye.com/rss” type=”rss”/>
<outline text=”ScottGu’s Blog ” xmlUrl=”http://weblogs.asp.net/scottgu/rss.aspx” type=”rss”/>
<outline text=”ScottGu博客中文版” xmlUrl=”http://blog.joycode.com/scottgu/feed” type=”rss”/>
<outline text=”Service-Oriented Architecture Blog RSS | ZDNet” xmlUrl=”http://www.zdnet.com/blog/service-oriented/rss?m=50&amp;tag=mantle_skin;content” type=”rss”/>
<outline text=”Simple Talk RSS Feed” xmlUrl=”http://www.simple-talk.com/rss.aspx?ncat” type=”rss”/>
<outline text=”Sky.Jian 朝阳的天空” xmlUrl=”http://feed.feedsky.com/sky000” type=”rss”/>
<outline text=”SQL Server Replication (SSQA.net)” xmlUrl=”http://sqlserver-qa.net/blogs/replication/rss.aspx” type=”rss”/>
<outline text=”SQL Server Training Consulting” xmlUrl=”http://feeds.feedburner.com/Sqlserver-training” type=”rss”/>
<outline text=”SQLPFE.IL” xmlUrl=”http://blogs.technet.com/b/sqlpfeil/rss.aspx” type=”rss”/>
<outline text=”SQLUninterrupted” xmlUrl=”http://sqluninterrupted.com/feed/” type=”rss”/>
<outline text=”SQL中国研发中心” xmlUrl=”http://blogs.msdn.com/b/sqlcrd/rss.aspx” type=”rss”/>
<outline text=”TechBrij” xmlUrl=”http://feeds.techbrij.com/techbrij” type=”rss”/>
<outline text=”TechNet 中文网站: SqlServer 最新原创文章” xmlUrl=”http://www.microsoft.com/China/TechNet/rss/articleshow/sqlserver.xml” type=”rss”/>
<outline text=”The Code Project Latest Articles” xmlUrl=”http://www.codeproject.com/webservices/articlerss.aspx” type=”rss”/>
<outline text=”Tim[后端技术]” xmlUrl=”http://timyang.net/feed/” type=”rss”/>
<outline text=”TT SOA 最新100篇 – TechTarget中国” xmlUrl=”http://www.searchsoa.com.cn/rss.aspx” type=”rss”/>
<outline text=”Visual Studio Report Controls Forum” xmlUrl=”http://social.msdn.microsoft.com/Forums/en-US/vsreportcontrols/threads?outputAs=rss” type=”rss”/>
<outline text=”Westwind Article Archive” xmlUrl=”http://www.west-wind.com/Westwindarticles.rss.xml” type=”rss”/>
<outline text=”Windows Azure  : windows azure, ” xmlUrl=”http://blogs.msdn.com/b/windowsazure/rss.aspx?Tags=windows+azure/” type=”rss”/>
<outline text=”www.k2.com RSS feed” xmlUrl=”http://www.k2.com/zh-CN/rss.aspx” type=”rss”/>
<outline text=”www.leastprivilege.com” xmlUrl=”http://www.leastprivilege.com/SyndicationService.asmx/GetRss” type=”rss”/>
<outline text=”【HongSoft=&amp;gt;老杨】” xmlUrl=”http://feeds.feedsky.com/csdn.net/hongbo781202” type=”rss”/>
<outline text=”【孟宪会之精彩世界】之.NET开发者园地” xmlUrl=”http://dotnet.aspx.cc/Rss.aspx” type=”rss”/>
<outline text=”上不了岸的鱼-51CTO技术博客” xmlUrl=”http://ttzhang.blog.51cto.com/rss.php?uid=1557644” type=”rss”/>
<outline text=”中国开放流程社区– It’s open! It’s social! It’s up to you blogs” xmlUrl=”http://www.opug.org.cn/blog/feed” type=”rss”/>
<outline text=”分享,交流-51CTO技术博客” xmlUrl=”http://kebin.blog.51cto.com/rss.php?uid=2121008” type=”rss”/>
<outline text=”北京动点开发团队 专注WPF Silverlight HTML5 Windows Phone7″ xmlUrl=”http://blog.csdn.net/dotfun/rss/list” type=”rss”/>
<outline text=”博客园-84年的矿泉水-随笔分类-DFS” xmlUrl=”http://www.cnblogs.com/Seapeak/category/246072.html/rss” type=”rss”/>
<outline text=”博客园-EricZhang’s Technology Blog” xmlUrl=”http://www.cnblogs.com/leoo2sk/rss” type=”rss”/>
<outline text=”博客园-lipan” xmlUrl=”http://www.cnblogs.com/lipan/rss” type=”rss”/>
<outline text=”博客园-Richie” xmlUrl=”http://www.cnblogs.com/RicCC/rss” type=”rss”/>
<outline text=”博客园-Taven” xmlUrl=”http://www.cnblogs.com/taven/rss” type=”rss”/>
<outline text=”博客园-webreport” xmlUrl=”http://www.cnblogs.com/webreport/rss” type=”rss”/>
<outline text=”博客园-Windows Workflow Foundation” xmlUrl=”http://www.cnblogs.com/foundation/rss” type=”rss”/>
<outline text=”博客园-” xmlUrl=”http://www.cnblogs.com/artech/rss” type=”rss”/>
<outline text=”博客园-冠军” xmlUrl=”http://www.cnblogs.com/haogj/rss” type=”rss”/>
<outline text=”博客园-生鱼片” xmlUrl=”http://www.cnblogs.com/carysun/rss” type=”rss”/>
<outline text=”博客园-草屋主人的blog” xmlUrl=”http://feed.feedsky.com/sunli1223” type=”rss”/>
<outline text=”博客园-重典的博客” xmlUrl=”http://www.cnblogs.com/chsword/rss” type=”rss”/>
<outline text=”博客园-阿不” xmlUrl=”http://www.cnblogs.com/hjf1223/rss” type=”rss”/>
<outline text=”博客园_Anytao” xmlUrl=”http://www.cnblogs.com/anytao/rss” type=”rss”/>
<outline text=”博客园_CareySon” xmlUrl=”http://www.cnblogs.com/CareySon/rss” type=”rss”/>
<outline text=”博客园_liulun” xmlUrl=”http://www.cnblogs.com/liulun/rss” type=”rss”/>
<outline text=”博客园_lovecindywang  = lovecherry” xmlUrl=”http://www.cnblogs.com/lovecindywang/rss” type=”rss”/>
<outline text=”博客园_love.net” xmlUrl=”http://www.cnblogs.com/wlflovenet/rss” type=”rss”/>
<outline text=”博客园_♂风车车.Net” xmlUrl=”http://www.cnblogs.com/xray2005/rss” type=”rss”/>
<outline text=”博客园_不如来编码-luminji’s web” xmlUrl=”http://www.cnblogs.com/luminji/rss” type=”rss”/>
<outline text=”博客园_移动产品的乌托邦” xmlUrl=”http://www.cnblogs.com/coolcode/rss” type=”rss”/>
<outline text=”博客园_老赵点滴 – 追求编程之美” xmlUrl=”http://www.cnblogs.com/JeffreyZhao/rss” type=”rss”/>
<outline text=”博客园_自由、创新、研究、探索” xmlUrl=”http://www.cnblogs.com/shanyou/rss” type=”rss”/>
<outline text=”博客园_软件设计开发” xmlUrl=”http://www.cnblogs.com/virusswb/rss” type=”rss”/>
<outline text=”博客园_飞洋过海” xmlUrl=”http://www.cnblogs.com/fygh/Rss.aspx” type=”rss”/>
<outline text=”博客园_麒麟” xmlUrl=”http://www.cnblogs.com/zhuqil/rss” type=”rss”/>
<outline text=”博客园_龙腾于海” xmlUrl=”http://www.cnblogs.com/DragonInSea/rss” type=”rss”/>
<outline text=”大CC” xmlUrl=”http://feed.feedsky.com/me115” type=”rss”/>
<outline text=”彦彬 郭的 InfoQ 个性化 RSS Feed” xmlUrl=”http://www.infoq.com/cn/rss/rss.action?token=jTYefU39V9CHXeJuems8H3i3Znk7C8cT” type=”rss”/>
<outline text=”微软云计算: Windows Azure 中文博客” xmlUrl=”http://blogs.msdn.com/b/azchina/rss.aspx” type=”rss”/>
<outline text=”微软亚洲研究院” xmlUrl=”http://blog.sina.com.cn/rss/1286528122.xml” type=”rss”/>
<outline text=”淘宝共享数据平台 tbdata.org” xmlUrl=”http://www.tbdata.org/feed” type=”rss”/>
<outline text=”淘宝核心系统团队博客” xmlUrl=”http://rdc.taobao.com/blog/cs/?feed=rss2” type=”rss”/>
<outline text=”淘宝网通用产品团队博客” xmlUrl=”http://rdc.taobao.com/team/jm/feed” type=”rss”/>
<outline text=”灰灰虫的家” xmlUrl=”http://hi.baidu.com/grayworm/rss” type=”rss”/>
<outline text=”立志做专业IT顾问-51CTO技术博客” xmlUrl=”http://maryafang.blog.51cto.com/rss.php?uid=1082430” type=”rss”/>
<outline text=”竹叶青 的专栏” xmlUrl=”http://blog.csdn.net/azhao_dn/rss/list” type=”rss”/>
<outline text=”结构之法 算法之道” xmlUrl=”http://blog.csdn.net/v_JULY_v/rss/list” type=”rss”/>
<outline text=”结网” xmlUrl=”http://feed.feedsky.com/liuhw” type=”rss”/>
<outline text=”网站策划师” xmlUrl=”http://www.hozin.com/rss/rss.xml” type=”rss”/>
<outline text=”老赵点滴 – 追求编程之美” xmlUrl=”http://blog.zhaojie.me/rss” type=”rss”/>
<outline text=”运维进行时” xmlUrl=”http://blog.liuts.com/feed.php” type=”rss”/>
<outline text=”阳志平的网志” xmlUrl=”http://www.yangzhiping.com/feed” type=”rss”/>
<outline text=”中国的源”><outline text=”MSN 中国 RSS” xmlUrl=”http://go.microsoft.com/fwlink/?LinkId=128474” type=”rss”/>
</outline></body></opml>

 

 

<?xml version=”1.0″?>
<opml version=”1.0″>
<head>
<title>OPML exported from Outlook</title>
<dateCreated>Mon, 12 Oct 2015 09:07:39 +0800</dateCreated>
<dateModified>Mon, 12 Oct 2015 09:07:39 +0800</dateModified>
</head>
<body>
<outline text=”后端技术 by Tim Yang” type=”rss” xmlUrl=”http://timyang.net/feed/”/>
<outline text=”Business Insider: Jay Yarow” type=”rss”
xmlUrl=”http://www.businessinsider.com/author/jay-yarow/rss”/>
<outline text=”博客园_装配中的脑袋” type=”rss”
xmlUrl=”http://feed.cnblogs.com/blog/u/8459/rss”/>
<outline text=”微软云计算: Windows Azure 中文博客” type=”rss”
xmlUrl=”http://blogs.msdn.com/b/azchina/rss.aspx”/>
<outline text=”InfoQ” type=”rss”
xmlUrl=”http://www.infoq.com/cn/rss/rss.action?token=jTYefU39V9CHXeJuems8H3i3Znk7C8cT”/>
<outline text=”微软亚洲研究院” type=”rss”
xmlUrl=”http://blog.sina.com.cn/rss/1286528122.xml”/>
<outline text=”CodeProject Latest Articles” type=”rss”
xmlUrl=”http://www.codeproject.com/webservices/articlerss.aspx”/>
<outline text=”StickNFind Blog” type=”rss”
xmlUrl=”http://blog.sticknfind.com/rss”/>
<outline text=”Advanced Distributed Learning Initiative” type=”rss”
xmlUrl=”http://www.adlnet.gov/feed/”/>
<outline text=”Reality matters” type=”rss”
xmlUrl=”http://blog.estimote.com/rss”/>
<outline text=”Martin Fowler” type=”rss”
xmlUrl=”http://martinfowler.com/feed.atom”/>
<outline text=”EntLib.net 技术分享平台” type=”rss”
xmlUrl=”http://www.entlib.net/?feed=rss2″/>
<outline text=”ScottGu’s Blog ” type=”rss”
xmlUrl=”http://weblogs.asp.net/scottgu/rss.aspx”/>
<outline text=”Mikel” type=”rss” xmlUrl=”http://www.mikel.cn/feed”/>
<outline text=”Linux Voice” type=”rss”
xmlUrl=”http://www.linuxvoice.com/feed/”/>
<outline text=”Gopher beyond El[i]phants” type=”rss”
xmlUrl=”http://mikespook.com/feed/”/>
<outline text=”博客园_汤姆大叔的博客” type=”rss”
xmlUrl=”http://feed.cnblogs.com/blog/u/101461/rss”/>
<outline text=”SQL中国研发中心” type=”rss”
xmlUrl=”http://blogs.msdn.com/b/sqlcrd/rss.aspx”/>
<outline text=”TechBrij” type=”rss”
xmlUrl=”http://feeds.techbrij.com/techbrij”/>
<outline text=”ASPNETWorld.com Blog” type=”rss”
xmlUrl=”http://www.aspnetworld.com/blog/SyndicationService.asmx/GetRss”/>
<outline text=”code(love)” type=”rss” xmlUrl=”http://www.code-love.com/feed/”/>
<outline text=”财富江湖” type=”rss” xmlUrl=”http://caifujianghu.com/rss”/>
<outline text=”Wow! Uncle Joey” type=”rss”
xmlUrl=”http://www.unclejoey.com/feed/”/>
<outline text=”developers.de” type=”rss”
xmlUrl=”http://developers.de/blogs/MainFeed.aspx”/>
<outline text=”Rob Ashton’s blog” type=”rss”
xmlUrl=”http://feed.codeofrob.com/RobAshton”/>
<outline text=”云风的 BLOG” type=”rss”
xmlUrl=”http://blog.codingnow.com/atom.xml”/>
<outline text=”WebShell’S Blog” type=”rss” xmlUrl=”http://feed.webshell.cc/”/>
<outline text=”美团技术团队 ” type=”rss” xmlUrl=”http://tech.meituan.com/atom.xml”/>
<outline text=”Data story” type=”rss” xmlUrl=”http://data.story.lu/feed”/>
<outline text=”NoSQLFan” type=”rss” xmlUrl=”http://feed.feedsky.com/nosqlfan”/>
<outline text=”阮一峰的网络日志” type=”rss”
xmlUrl=”http://www.ruanyifeng.com/blog/atom.xml”/>
<outline text=”外刊IT评论” type=”rss” xmlUrl=”http://rss.aqee.net/”/>
<outline text=”博客园_大熊君{{bb}}” type=”rss”
xmlUrl=”http://feed.cnblogs.com/blog/u/208572/rss”/>
<outline text=”Matrix67: The Aha Moments” type=”rss”
xmlUrl=”http://www.matrix67.com/blog/rss”/>
<outline text=”刘未鹏 | Mind Hacks” type=”rss” xmlUrl=”http://mindhacks.cn/feed/”/>
<outline text=”酷 壳 – CoolShell.cn” type=”rss”
xmlUrl=”http://coolshell.cn/feed”/>
<outline text=”Type is Beautiful” type=”rss”
xmlUrl=”http://www.typeisbeautiful.com/feed/”/>
<outline text=”C++博客-λ-calculus(惊愕到手了欧耶,GetBlogPostIds.aspx)” type=”rss”
xmlUrl=”http://www.cppblog.com/vczh/Rss.aspx”/>
<outline text=”Wait But Why” type=”rss” xmlUrl=”http://waitbutwhy.com/feed”/>
<outline text=”IBM developerWorks 中国 : 文档库” type=”rss”
xmlUrl=”http://www.ibm.com/developerworks/cn/views/global/rss/libraryview.jsp?end=25″/>
<outline text=”The npm Blog” type=”rss” xmlUrl=”http://blog.npmjs.org/rss”/>
<outline text=”Jason’s Blog” type=”rss”
xmlUrl=”http://www.jasongj.com/atom.xml”/>
<outline text=”Neural Interaction Lab” type=”rss”
xmlUrl=”http://coleman.ucsd.edu/feed/”/>
<outline text=”博客园_Apocalypsa” type=”rss”
xmlUrl=”http://feed.cnblogs.com/blog/u/42441/rss”/>
<outline text=”DBA Notes” type=”rss” xmlUrl=”http://dbanotes.net/feed”/>
<outline text=”程序员在囧途” type=”rss” xmlUrl=”http://www.shenyisyn.org/feed”/>
<outline text=”科学松鼠会 » 计算机科学” type=”rss”
xmlUrl=”http://songshuhui.net/archives/category/major/cs/feed”/>
</body>
</opml>

Understanding Basics of UI Design Pattern MVC, MVP and MVVM

Introduction

This is my first article and I hope you will like it. After reading this article, you will have a good understanding about “Why we need UI design pattern for our application?” and “What are basic differences between different UI patterns (MVC, MVP, MVVP)?”.

In traditional UI development – developer used to create a View using window or usercontrol or page and then write all logical code (Event handling, initialization and data model, etc.) in code behind and hence they were basically making code as a part of view definition class itself. This approach increased the size of my view class and created a very strong dependency between my UI and data binding logic and business operations. In this situation, no two developers can work simultaneously on the same view and also one developer’s changes might break the other code. So everything is in one place is always a bad idea for maintainability, extendibility and testability prospective. So if you look at the big picture, you can feel that all these problems exist because there is a very tight coupling between the following items.

  1. View (UI)
  2. Model (Data displayed in UI)
  3. Glue code (Event handling, binding, business logic)

Definition of Glue code is different in each pattern. Although view and model is used with the same definition in all patterns.

In case of MVC it is controller. In case of MVP it is presenter. In case of MVVM it is view model.

If you look at the first two characters in all the above patterns, it remain same i.e. stands for model and view. All these patterns are different but have a common objective that is “Separation of Duties”

In order to understand the entire article, I request readers to first understand the above entity. A fair idea about these will help you to understand this article. If you ever worked on UI module, you can easily relate these entities with your application.

MVC (model view controller), MVP (model view presenter) and MVVM (model view view model) patterns allow us to develop applications with loss coupling and separation of concern which in turn improve testability, maintainability and extendibility with minimum effort.

MVVM pattern is a one of the best solutions to handle such problems for WPF and Silverlight application. During this article, I will compare MVC, MVP and MVVM at the definition level.

MVP & MVC

Before we dig into MVVM, let’s start with some history: There were already many popular design patterns available to make UI development easy and fast. For example, MVP (model view presenter) pattern is one of the very popular patterns among other design patterns available in the market. MVP is a variation of MVC pattern which is being used for so many decades. Simple definition of MVP is that it contains three components: Model, View and presenter. So view is nothing but a UI which displays on the screen for user, the data it displays is the model, and the Presenter hooks the two together (View and model).

The view relies on a Presenter to populate it with model data, react to user input, and provide input validation. For example, if user clicks on save button, corresponding handling is not in code behind, it’s now in presenter. If you wanted to study it in detail, here is the MSDN link.

In the MVC, the Controller is responsible for determining which View is displayed in response to any action including when the application loads. This differs from MVP where actions route through the View to the Presenter. In MVC, every action in the View basically calls to a Controller along with an action. In web application, each action is a call to a URL and for each such call there is a controller available in the application who respond to such call. Once that Controller has completed its processing, it will return the correct View.

In case of MVP, view binds to the Model directly through data binding. In this case, it’s the Presenter’s job to pass off the Model to the View so that it can bind to it. The Presenter will also contain logic for gestures like pressing a button, navigation. It means while implementing this pattern, we have to write some code in code behind of view in order delegate (register) to the presenter. However, in case of MVC, a view does not directly bind to the Model. The view simply renders, and is completely stateless. In implementations of MVC, the View usually will not have any logic in the code behind. Since controller itself returns view while responding to URL action, there is no need to write any code in view code behind file.

MVC Steps

Step 1: Incoming request directed to Controller.

Step 2: Controller processes request and forms a data Model.

Step 3: Model is passed to View.

Step 4: View transforms Model into appropriate output format.

Step 5: Response is rendered.

So now you have basic understanding of MVC and MVP. Let’s move to MVVM.

MVVM (Model View ViewModel)

The MVVM pattern includes three key parts:

  1. Model (Business rule, data access, model classes)
  2. View (User interface (XAML))
  3. ViewModel (Agent or middle man between view and model)

Model and View work just like MVC and “ViewModel” is the model of the View.

  • ViewModel acts as an interface between model and View.
  • ViewModel provides data binding between View and model data.
  • ViewModel handles all UI actions by using command.

In MVVM, ViewModel does not need a reference to a view. The view binds its control value to properties on a ViewModel, which, in turn, exposes data contained in model objects. In simple words, TextBox text property is bound with name property in ViewModel.

In View:

Collapse | Copy Code
<TextBlock Text="{Binding Name}"/>

In ViewModel:

Collapse | Copy Code
public string Name
        {
            get
            {
                return this.name;
            }
            set
            {
                this.name = value;
                this.OnPropertyChanged("Name");
            }
        }

ViewModel reference is set to a DataContext of View in order to set view data binding (glue between view and ViewModel model).

Code behind code of View:

Collapse | Copy Code
public IViewModel Model
        {
            get
            {
                return this.DataContext as IViewModel;
            }
            set
            {
                this.DataContext = value;
            }
        }

If property values in the ViewModel change, those new values automatically propagate to the view via data binding and via notification. When the user performs some action in the view for example clicking on save button, a command on the ViewModel executes to perform the requested action. In this process, it’s the ViewModel which modifies model data, View never modifies it. The view classes have no idea that the model classes exist, while the ViewModel and model are unaware of the view. In fact, the model doesn’t have any idea about ViewModel and view exists.

Where to Use What in the .NET World

  • Model-View-Controller (MVC) pattern
    • ASP.NET MVC 4 Link
    • Disconnected Web Based Applications
  • Model-View-Presenter (MVP) pattern
    • Web Forms/SharePoint, Windows Forms
  • Model-View-ViewModel (MVVM) pattern
    • Silverlight, WPF Link
    • Data binding

Sources and References

History

  • 18th July, 2011: Initial version
  • 19th July, 2011: Modified content in MVVM section

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

from:http://www.codeproject.com/Articles/228214/Understanding-Basics-of-UI-Design-Pattern-MVC-MVP

(Model view controller)MVC Interview questions and answers

Disclaimer
What is MVC(Model view controller)?
Can you explain the complete flow of MVC?
Is MVC suitable for both windows and web application?
What are the benefits of using MVC?
Is MVC different from a 3 layered architecture?
What is the latest version of MVC?
What is the difference between each version of MVC?
What are routing in MVC?
Where is the route mapping code written?
Can we map multiple URL’s to the same action?
How can we navigate from one view to other view using hyperlink?
How can we restrict MVC actions to be invoked only by GET or POST?
How can we maintain session in MVC?
What is the difference between tempdata,viewdata and viewbag?
What are partial views in MVC?
How did you create partial view and consume the same?
How can we do validations in MVC?
Can we display all errors in one go?
How can we enable data annotation validation on client side?
What is razor in MVC?
Why razor when we already had ASPX?
So which is a better fit Razor or ASPX?
How can you do authentication and authorization in MVC?
How to implement windows authentication for MVC?
How do you implement forms authentication in MVC?
How to implement Ajax in MVC?
What kind of events can be tracked in AJAX?
What is the difference between “ActionResult” and “ViewResult”?
What are the different types of results in MVC?
What are “ActionFilters”in MVC?
Can we create our custom view engine using MVC?
How to send result back in JSON format in MVC?
What is “WebAPI”?
But WCF SOAP also does the same thing, so how does “WebAPI” differ?
With WCF also you can implement REST,So why “WebAPI”?

Disclaimer

By reading these MVC interview question it does not mean you will go and clear MVC interviews. The whole purpose of this article is to quickly brush up your MVC knowledge before you for the MVC interviews.

This article does not teach MVC, it’s a last minute revision sheet before going for MVC interviews.

In case you want to learn MVC from scratch start by reading Learn MVC ( Model view controller) step by step 7 days or you can also start with my step by step MVC ( Model view controller) video series from youtube.

What is MVC(Model view controller)?

MVC is architectural pattern which separates the representation and the user interaction. It’s divided in three broader sections, “Model”, “View” and “Controller”. Below is how each one of them handles the task.

  • The “View” is responsible for look and feel.
  • “Model” represents the real world object and provides data to the “View”.
  • The “Controller” is responsible to take the end user request and load the appropriate “Model” and “View”.

 

Figure: – MVC (Model view controller)

Can you explain the complete flow of MVC?

Below are the steps how control flows in MVC (Model, view and controller) architecture:-

  • All end user requests are first sent to the controller.
  • The controller depending on the request decides which model to load. The controller loads the model and attaches the model with the appropriate view.
  • The final view is then attached with the model data and sent as a response to the end user on the browser.

Is MVC suitable for both windows and web application?

MVC architecture is suited for web application than windows. For window application MVP i.e. “Model view presenter” is more applicable.IfyouareusingWPFandSLMVVMismoresuitableduetobindings.

What are the benefits of using MVC?

There are two big benefits of MVC:-

Separation of concerns is achieved as we are moving the code behind to a separate class file. By moving the binding code to a separate class file we can reuse the code to a great extent.

Automated UI testing is possible because now the behind code (UI interaction code) has moved to a simple.NET class. This gives us opportunity to write unit tests and automate manual testing.

Is MVC different from a 3 layered architecture?

MVC is an evolution of a 3 layered traditional architecture. Many components of 3 layered architecture are part of MVC.  So below is how the mapping goes.

Functionality 3 layered / tiered architecture Model view controller architecture
Look and Feel User interface. View.
UI logic User interface. Controller
Business logic /validations Middle layer Model.
Request is first sent to User interface Controller.
Accessing data Data access layer. Data access layer.

Figure: – 3 layered architecture

What is the latest version of MVC?

When this note was written, four versions where released of MVC. MVC 1 , MVC 2, MVC 3 and MVC 4. So the latest is MVC 4.

What is the difference between each version of MVC?

Below is a detail table of differences. But during interview it’s difficult to talk about all of them due to time limitation. So I have highlighted important differences which you can run through before the interviewer.

MVC 2 MVC 3 MVC 4
Client-Side Validation Templated Helpers Areas Asynchronous Controllers Html.ValidationSummary Helper Method DefaultValueAttribute in Action-Method Parameters Binding Binary Data with Model Binders DataAnnotations Attributes Model-Validator Providers New RequireHttpsAttribute Action Filter Templated Helpers Display Model-Level Errors RazorReadymade project templatesHTML 5 enabled templatesSupport for Multiple View EnginesJavaScript and AjaxModel Validation Improvements ASP.NET Web APIRefreshed and modernized default project templatesNew mobile project templateMany new features to support mobile apps Enhanced support for asynchronous methods

What are routing in MVC?

Routing helps you to define a URL structure and map the URL with the controller.

For instance let’s say we want that when any user types “http://localhost/View/ViewCustomer/”,  it goes to the  “Customer” Controller  and invokes “DisplayCustomer” action.  This is defined by adding an entry in to the “routes” collection using the “maproute” function. Below is the under lined code which shows how the URL structure and mapping with controller and action is defined.

Collapse | Copy Code
routes.MapRoute(
               "View", // Route name
               "View/ViewCustomer/{id}", // URL with parameters
               new { controller = "Customer", action = "DisplayCustomer",
id = UrlParameter.Optional }); // Parameter defaults

Where is the route mapping code written?

The route mapping code is written in the “global.asax” file.

Can we map multiple URL’s to the same action?

Yes , you can , you just need to make two entries with different key names and specify the same controller and action.

How can we navigate from one view to other view using hyperlink?

By using “ActionLink” method as shown in the below code. The below code will create a simple URL which help to navigate to the “Home” controller and invoke the “GotoHome” action.

Collapse | Copy Code
<%= Html.ActionLink("Home","Gotohome") %>

How can we restrict MVC actions to be invoked only by GET or POST?

We can decorate the MVC action by “HttpGet” or “HttpPost” attribute to restrict the type of HTTP calls. For instance you can see in the below code snippet the “DisplayCustomer” action can only be invoked by “HttpGet”. If we try to make Http post on “DisplayCustomer” it will throw an error.

Collapse | Copy Code
[HttpGet]
        public ViewResult DisplayCustomer(int id)
        {
            Customer objCustomer = Customers[id];
            return View("DisplayCustomer",objCustomer);
        }

How can we maintain session in MVC?

Sessions can be maintained in MVC by 3 ways tempdata ,viewdata and viewbag.

What is the difference between tempdata ,viewdata and viewbag?

 

Figure:- difference between tempdata , viewdata and viewbag

Temp data: –Helps to maintain data when you move from one controller to other controller or from one action to other action. In other words when you redirect,“tempdata” helps to maintain data between those redirects. It internally uses session variables.

View data: – Helps to maintain data when you move from controller to view.

View Bag: – It’s a dynamic wrapper around view data. When you use “Viewbag” type casting is not required. It uses the dynamic keyword internally.

Figure:-dynamic keyword

Session variables: – By using session variables we can maintain data from any entity to any entity.

Hidden fields and HTML controls: – Helps to maintain data from UI to controller only. So you can send data from HTML controls or hidden fields to the controller using POST or GET HTTP methods.

Below is a summary table which shows different mechanism of persistence.

Maintains data between ViewData/ViewBag TempData Hidden fields Session
Controller to Controller No Yes No Yes
Controller to View Yes No No Yes
View to Controller No No Yes Yes

What are partial views in MVC?

Partial view is a reusable view (like a user control) which can be embedded inside other view. For example let’s say all your pages of your site have a standard structure with left menu, header and footer as shown in the image below.

Figure:- partial views in MVC

For every page you would like to reuse the left menu, header and footer controls. So you can go and create partial views for each of these items and then you call that partial view in  the  main view.

How did you create partial view and consume the same?

When you add a view to your project you need to check the “Create partial view” check box.

Figure:-createpartialview

Once the partial view is created you can then call the partial view in the main view using “Html.RenderPartial” method as shown in the below code snippet.

Collapse | Copy Code
<body>
<div>
<% Html.RenderPartial("MyView"); %>
</div>
</body>

How can we do validations in MVC?

One of the easy ways of doing validation in MVC is by using data annotations. Data annotations are nothing but attributes which you can be applied on the model properties. For example in the below code snippet we have a simple “customer” class with a property “customercode”.

This”CustomerCode” property is tagged with a “Required” data annotation attribute. In other words if this model is not provided customer code it will not accept the same.

Collapse | Copy Code
public class Customer
{
        [Required(ErrorMessage="Customer code is required")]
        public string CustomerCode
        {
            set;
            get;
        }
}

In order to display the validation error message we need to use “ValidateMessageFor” method which belongs to the “Html” helper class.

Collapse | Copy Code
<% using (Html.BeginForm("PostCustomer", "Home", FormMethod.Post))
{ %>
<%=Html.TextBoxFor(m => m.CustomerCode)%>
<%=Html.ValidationMessageFor(m => m.CustomerCode)%>
<input type="submit" value="Submit customer data" />
<%}%>

Later in the controller we can check if the model is proper or not by using “ModelState.IsValid” property and accordingly we can take actions.

 

Collapse | Copy Code
public ActionResult PostCustomer(Customer obj)
{
if (ModelState.IsValid)
{
                obj.Save();
                return View("Thanks");
}
else
{
                return View("Customer");
}
}

 

Below is a simple view of how the error message is displayed on the view.

Figure:- validations in MVC

Can we display all errors in one go?

Yes we can, use “ValidationSummary” method from HTML helper class.

Collapse | Copy Code
<%= Html.ValidationSummary() %>

What are the other data annotation attributes for validation in MVC?

If you want to check string length, you can use “StringLength”.

Collapse | Copy Code
[StringLength(160)]
public string FirstName { get; set; }

In case you want to use regular expression, you can use “RegularExpression” attribute.

Collapse | Copy Code
[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")]public string Email { get; set; }

If you want to check whether the numbers are in range, you can use the “Range” attribute.

Collapse | Copy Code
[Range(10,25)]public int Age { get; set; }

Some time you would like to compare value of one field with other field, we can use the “Compare” attribute.

Collapse | Copy Code
public string Password { get; set; }[Compare("Password")]public string ConfirmPass { get; set; }

In case you want to get a particular error message , you can use the “Errors” collection.

Collapse | Copy Code
var ErrMessage = ModelState["Email"].Errors[0].ErrorMessage;

If you have created the model object yourself you can explicitly call “TryUpdateModel” in your controller to check if the object is valid or not.

Collapse | Copy Code
TryUpdateModel(NewCustomer);

In case you want add errors in the controller you can use “AddModelError” function.

Collapse | Copy Code
ModelState.AddModelError("FirstName", "This is my server-side error.");

How can we enable data annotation validation on client side?

It’s a two-step process first reference the necessary jquery files.

Collapse | Copy Code
<script src="<%= Url.Content("~/Scripts/jquery-1.5.1.js") %>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/jquery.validate.js") %>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/jquery.validate.unobtrusive.js") %>" type="text/javascript"></script>

Second step is to call “EnableClientValidation” method.

Collapse | Copy Code
<% Html.EnableClientValidation(); %>

What is razor in MVC?

It’s a light weight view engine. Till MVC we had only one view type i.e.ASPX, Razor was introduced in MVC 3.

Why razor when we already had ASPX?

Razor is clean, lightweight and syntaxes are easy as compared to ASPX. For example in ASPX to display simple time we need to write.

Collapse | Copy Code
<%=DateTime.Now%>

In Razor it’s just one line of code.

Collapse | Copy Code
@DateTime.Now

So which is a better fit Razor or ASPX?

As per Microsoft razor is more preferred because it’s light weight and has simple syntaxes.

How can you do authentication and authorization in MVC?

You can use windows or forms authentication for MVC.

How to implement windows authentication for MVC?

For windows authentication you need to go and modify the “web.config” file and set authentication mode to windows.

Collapse | Copy Code
<authentication mode="Windows"/>
<authorization>
<deny users="?"/>
</authorization>

Then in the controller or on the action you can use the “Authorize” attribute which specifies which users have access to these controllers and actions. Below is the code snippet for the same. Now only  the users specified in the controller and action can access the same.

Collapse | Copy Code
[Authorize(Users= @"WIN-3LI600MWLQN\Administrator")]
    public class StartController : Controller
    {
        //
        // GET: /Start/
        [Authorize(Users = @"WIN-3LI600MWLQN\Administrator")]
        public ActionResult Index()
        {
            return View("MyView");
        }
    }

How do you implement forms authentication in MVC?

Forms authentication is implemented the same way as we do in ASP.NET. So the first step is to set authentication mode equal to forms. The “loginUrl” points to a controller here rather than page.

Collapse | Copy Code
<authentication mode="Forms">
<forms loginUrl="~/Home/Login"  timeout="2880"/>
</authentication>

We also need to create a controller where we will check the user is proper or not. If the user is proper we will set the cookie value.

Collapse | Copy Code
public ActionResult Login()
{
if ((Request.Form["txtUserName"] == "Shiv") && (Request.Form["txtPassword"] == "Shiv@123"))
{
            FormsAuthentication.SetAuthCookie("Shiv",true);
            return View("About");
}
else
{
            return View("Index");
}
}

All the other actions need to be attributed with “Authorize” attribute so that any unauthorized user if he makes a call to these controllers it will redirect to the controller ( in this case the controller is “Login”) which will do authentication.

Collapse | Copy Code
[Authorize]
PublicActionResult Default()
{
return View();
}
[Authorize]
publicActionResult About()
{
return View();
}

How to implement Ajax in MVC?

You can implement Ajax in two ways in MVC: –

  • Ajax libraries
  • Jquery

Below is a simple sample of how to implement Ajax by using “Ajax” helper library. In the below code you can see we have a simple form which is created by using “Ajax.BeginForm” syntax. This form calls a controller action called as “getCustomer”. So now the submit action click will be an asynchronous ajax call.

Collapse | Copy Code
<script language="javascript">
function OnSuccess(data1)
{
// Do something here
}
</script>
<div>
<%
        var AjaxOpt = new AjaxOptions{OnSuccess="OnSuccess"};
    %>
<% using (Ajax.BeginForm("getCustomer","MyAjax",AjaxOpt)) { %>
<input id="txtCustomerCode" type="text" /><br />
<input id="txtCustomerName" type="text" /><br />
<input id="Submit2" type="submit" value="submit"/></div>
<%} %>

In case you want to make ajax calls on hyperlink clicks you can use “Ajax.ActionLink” function as shown in the below code.

Figure:- implement Ajax in MVC

So if you want to create Ajax asynchronous   hyperlink by name “GetDate” which calls the “GetDate” function on the controller , below is the code for the same.  Once the controller responds this data is displayed in the HTML DIV tag by name “DateDiv”.

Collapse | Copy Code
<span id="DateDiv" />
<%:
Ajax.ActionLink("Get Date","GetDate",
new AjaxOptions {UpdateTargetId = "DateDiv" })
%>

Below is the controller code. You can see how “GetDate” function has a pause of 10 seconds.

Collapse | Copy Code
public class Default1Controller : Controller
{
       public string GetDate()
       {
           Thread.Sleep(10000);
           return DateTime.Now.ToString();
       }
}

The second way of making Ajax call in MVC is by using Jquery. In the below code you can see we are making an ajax POST call to a URL “/MyAjax/getCustomer”. This is done by using “$.post”. All this logic is put in to a function called as “GetData” and you can make a call to the “GetData” function on a button or a hyper link click event as you want.

Collapse | Copy Code
function GetData()
    {
        var url = "/MyAjax/getCustomer";
        $.post(url, function (data)
        {
            $("#txtCustomerCode").val(data.CustomerCode);
            $("#txtCustomerName").val(data.CustomerName);
        }
        )
    }

What kind of events can be tracked in AJAX?

Figure:- tracked in AJAX

What is the difference between “ActionResult” and “ViewResult”?

“ActionResult” is an abstract class while “ViewResult” derives from “ActionResult” class. “ActionResult” has several derived classes like “ViewResult” ,”JsonResult” , “FileStreamResult” and so on.

“ActionResult” can be used to exploit polymorphism and dynamism. So if you are returning different types of view dynamically “ActionResult” is the best thing. For example in the below code snippet you can see we have a simple action called as “DynamicView”. Depending on the flag (“IsHtmlView”) it will either return “ViewResult” or “JsonResult”.

Collapse | Copy Code
public ActionResult DynamicView()
{
   if (IsHtmlView)
     return View(); // returns simple ViewResult
   else
     return Json(); // returns JsonResult view
}

What are the different types of results in MVC?

Collapse | Copy Code
Note: -It’s difficult to remember all the 12 types. But some important ones you can remember for the interview are “ActionResult”, “ViewResult” and “JsonResult”. Below is a detailed list for your interest.

There 12 kinds of results in MVC, at the top is “ActionResult”class which is a base class that canhave11subtypes’sas listed below: –

  1. ViewResult – Renders a specified view to the response stream
  2. PartialViewResult – Renders a specified partial view to the response stream
  3. EmptyResult – An empty response is returned
  4. RedirectResult – Performs an HTTP redirection to a specified URL
  5. RedirectToRouteResult – Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data
  6. JsonResult – Serializes a given ViewData object to JSON format
  7. JavaScriptResult – Returns a piece of JavaScript code that can be executed on the client
  8. ContentResult – Writes content to the response stream without requiring a view
  9. FileContentResult – Returns a file to the client
  10. FileStreamResult – Returns a file to the client, which is provided by a Stream
  11. FilePathResult – Returns a file to the client

What are “ActionFilters”in MVC?

“ActionFilters” helps you to perform logic while MVC action is executing or after a MVC action has executed.

Figure:- “ActionFilters”in MVC

Action filters are useful in the following scenarios:-

  1. Implement post-processinglogicbeforethe action happens.
  2. Cancel a current execution.
  3. Inspect the returned value.
  4. Provide extra data to the action.

You can create action filters by two ways:-

  • Inline action filter.
  • Creating an “ActionFilter” attribute.

To create a inline action attribute we need to implement “IActionFilter” interface.The “IActionFilter” interface has two methods “OnActionExecuted” and “OnActionExecuting”. We can implement pre-processing logic or cancellation logic in these methods.

Collapse | Copy Code
public class Default1Controller : Controller , IActionFilter
    {
        public ActionResult Index(Customer obj)
        {
            return View(obj);
        }
        void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
        {
            Trace.WriteLine("Action Executed");
        }
        void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
        {
            Trace.WriteLine("Action is executing");
        }
    }

The problem with inline action attribute is that it cannot be reused across controllers. So we can convert the inline action filter to an action filter attribute. To create an action filter attribute we need to inherit from “ActionFilterAttribute” and implement “IActionFilter” interface as shown in the below code.

Collapse | Copy Code
public class MyActionAttribute : ActionFilterAttribute , IActionFilter
{
void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
{
     Trace.WriteLine("Action Executed");
}
void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
{
      Trace.WriteLine("Action executing");
}
}

Later we can decorate the controllers on which we want the action attribute to execute. You can see in the below code I have decorated the “Default1Controller” with “MyActionAttribute” class which was created in the previous code.

Collapse | Copy Code
[MyActionAttribute]
public class Default1Controller : Controller
{
 public ActionResult Index(Customer obj)
 {
 return View(obj);
 }
}

Can we create our custom view engine using MVC?

Yes, we can create our own custom view engine in MVC. To create our own custom view engine we need to follow 3 steps:-

Let’ say we want to create a custom view engine where in the user can type a command like “<DateTime>” and it should display the current date and time.

Step 1:- We need to create a class which implements “IView” interface. In this class we should write the logic of how the view will be rendered in the “render” function. Below is a simple code snippet for the same.

 

Collapse | Copy Code
public class MyCustomView : IView
    {
        private string _FolderPath; // Define where  our views are stored
        public string FolderPath
        {
            get { return _FolderPath; }
            set { _FolderPath = value; }
        }

        public void Render(ViewContext viewContext, System.IO.TextWriter writer)
        {
           // Parsing logic <dateTime>
            // read the view file
            string strFileData = File.ReadAllText(_FolderPath);
            // we need to and replace <datetime> datetime.now value
            string strFinal = strFileData.Replace("<DateTime>", DateTime.Now.ToString());
            // this replaced data has to sent for display
            writer.Write(strFinal);
        }
    }

 

Step 2 :-We need to create a class which inherits from “VirtualPathProviderViewEngine” and in this class we need to provide the folder path and the extension of the view name. For instance for razor the extension is “cshtml” , for aspx the view extension is “.aspx” , so in the same way for our custom view we need to provide an extension. Below is how the code looks like. You can see the “ViewLocationFormats” is set to the “Views” folder and the extension is “.myview”.

Collapse | Copy Code
public class MyViewEngineProvider : VirtualPathProviderViewEngine
    {
        // We will create the object of Mycustome view
        public MyViewEngineProvider() // constructor
        {
            // Define the location of the View file
            this.ViewLocationFormats = new string[] { "~/Views/{1}/{0}.myview", "~/Views/Shared/{0}.myview" }; //location and extension of our views
        }
        protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
        {
            var physicalpath = controllerContext.HttpContext.Server.MapPath(viewPath);
            MyCustomView obj = new MyCustomView(); // Custom view engine class
            obj.FolderPath = physicalpath; // set the path where the views will be stored
            return obj; // returned this view paresing logic so that it can be registered in the view engine collection
        }
        protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
        {
            var physicalpath = controllerContext.HttpContext.Server.MapPath(partialPath);
            MyCustomView obj = new MyCustomView(); // Custom view engine class
            obj.FolderPath = physicalpath; // set the path where the views will be stored
            return obj; // returned this view paresing logic so that it can be registered in the view engine collection
        }
    }

Step 3:- We need to register the view in the custom view collection. The best place to register the custom view engine in the “ViewEngines” collection is the “global.asax” file. Below is the code snippet for the same.

Collapse | Copy Code
protected void Application_Start()
 {
            // Step3 :-  register this object in the view engine collection
            ViewEngines.Engines.Add(new MyViewEngineProvider());
<span class="Apple-tab-span" style="white-space: pre; ">	</span>…..
}

Below is a simple output of the custom view written using the commands defined at the top.

Figure:-customviewengineusingMVC

If you invoke this view you should see the following output.

How to send result back in JSON format in MVC?

In MVC we have “JsonResult” class by which we can return back data in JSON format. Below is a simple sample code which returns back “Customer” object in JSON format using “JsonResult”.

Collapse | Copy Code
public JsonResult getCustomer()
{
Customer obj = new Customer();
obj.CustomerCode = "1001";
obj.CustomerName = "Shiv";
 return Json(obj,JsonRequestBehavior.AllowGet);
}

Below is the JSON output of the above code if you invoke the action via the browser.

What is “WebAPI”?

HTTP is the most used protocol.For past many years browser was the most preferred client by which we can consume data exposed over HTTP. But as years passed by client variety started spreading out. We had demand to consume data on HTTP from clients like mobile,javascripts,windows  application etc.

For satisfying the broad range of client “REST” was the proposed approach. You can read more about “REST” from WCF chapter.

“WebAPI” is the technology by which you can expose data over HTTP following REST principles.

But WCF SOAP also does the same thing, so how does “WebAPI” differ?

SOAP WEB API
Size Heavy weight because of complicated WSDL structure. Light weight, only the necessary information is transferred.
Protocol Independent of protocols. Only  for HTTP protocol
Formats To parse SOAP message, the client needs to understand WSDL format. Writing custom code for parsing WSDL is a heavy duty task. If your client is smart enough to create proxy objects like how we have in .NET (add reference) then SOAP is easier to consume and call. Output of “WebAPI” are simple string message,JSON,Simple XML format etc. So writing parsing logic for the same in very easy.
Principles SOAP follows WS-* specification. WEB API follows REST principles. (Please refer about REST in WCF chapter).

With WCF also you can implement REST,So why “WebAPI”?

WCF was brought in to implement SOA, never the intention was to implement REST.”WebAPI'” is built from scratch and the only goal is to create HTTP services using REST. Due to the one point focus for creating “REST” service “WebAPI” is more preferred.

How to implement “WebAPI” in MVC?

Below are the steps to implement “webAPI” :-

Step1:-Create the project using the “WebAPI” template.

Figure:- implement “WebAPI” in MVC

Step 2:- Once you have created the project you will notice that the controller now inherits from “ApiController” and you can now implement “post”,”get”,”put” and “delete” methods of HTTP protocol.

Collapse | Copy Code
public class ValuesController : ApiController
    {
        // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }
        // GET api/values/5
        public string Get(int id)
        {
            return "value";
        }
        // POST api/values
        public void Post([FromBody]string value)
        {
        }
        // PUT api/values/5
        public void Put(int id, [FromBody]string value)
        {
        }
        // DELETE api/values/5
        public void Delete(int id)
        {
        }
    }

Step 3:-If you make a HTTP GET call you should get the below results.

Figure:- HTTP

Finally do not forget to visit my video site which covers lots of C# interview questions and answers: –www.questpond.com

from:http://www.codeproject.com/Articles/556995/Model-view-controller-MVC-Interview-questions-and

GUI Architectures

There have been many different ways to organize the code for a rich client system. Here I discuss a selection of those that I feel have been the most influential and introduce how they relate to the patterns.

Last significant update: 18 Jul 06


Graphical user interfaces have become a familiar part of our software landscape, both as users and as developers. Looking at it from a design perspective they represent a particular set of problems in system design – problems that have led to a number of different but similar solutions.

My interest is identifying common and useful patterns for application developers to use in rich-client development. I’ve seen various designs in project reviews and also various designs that have been written in a more permanent way. Inside these designs are the useful patterns, but describing them is often not easy. Take Model-View-Controller as an example. It’s often referred to as a pattern, but I don’t find it terribly useful to think of it as a pattern because it contains quite a few different ideas. Different people reading about MVC in different places take different ideas from it and describe these as ‘MVC’. If this doesn’t cause enough confusion you then get the effect of misunderstandings of MVC that develop through a system of Chinese whispers.

In this essay I want to explore a number of interesting architectures and describe my interpretation of their most interesting features. My hope is that this will provide a context for understanding the patterns that I describe.

To some extent you can see this essay as a kind of intellectual history that traces ideas in UI design through multiple architectures over the years. However I must issue a caution about this. Understanding architectures isn’t easy, especially when many of them change and die. Tracing the spread of ideas is even harder, because people read different things from the same architecture. In particular I have not done an exhaustive examination of the architectures I describe. What I have done is referred to common descriptions of the designs. If those descriptions miss things out, I’m utterly ignorant of that. So don’t take my descriptions as an authoritative description of the architectures I describe. Furthermore there things I’ve left out or simplified if I didn’t think they were particularly relevant. Remember my primary interest is the underlying patterns, not in the history of these designs.

(There is something of an exception here, in that I did have access to a running Smalltalk-80 to examine MVC. Again I wouldn’t describe my examination of it as exhaustive, but it did reveal things that common descriptions of it failed to – which even further makes me cautious about descriptions of other architectures that I have here. If you are familiar with one of these architectures and you see I have something important that is incorrect and missing I’d like to know about it. I also thing that a more exhaustive survey of this territory would be a good object of academic study.)


Forms and Controls

I shall begin this exploration with an architecture that is both simple and familiar. It doesn’t have a common name, so for the purposes of this essay I shall call it “Forms and Controls”. It’s a familiar architecture because it was the one encouraged by client-server development environments in the 90’s – tools like Visual Basic, Delphi, and Powerbuilder. It continues to be commonly used, although also often vilified by design geeks like me.

To explore it, and indeed the other architectures, I’ll use a common example. In New England, where I live, there is a government program that monitors the amount of ice-cream particulate in the atmosphere. If the concentration is too low, this indicates that we aren’t eating enough ice-cream – which poses a serious risk to our economy and public order. (I like to use examples that are no less realistic as you usually find in books like this.)

To monitor our ice-cream health, the government has set up monitoring stations all over the New England states. Using complex atmospheric modeling the department sets a target for each monitoring station. Every so often staffers go out on an assessment where they go to various stations and note the actual ice-cream particulate concentrations. This UI allows them to select a station, and enter the date and actual value. The system then calculates and displays the variance from the target. Furthermore if the actual is more than 10% below the target, the variance is highlighted in red, if above by more than 5% it’s highlighted in green.

Figure 1: The UI I’ll use as an example.

As we look at this screen we can see there is an important division as we put it together. The form is specific to our application, but it uses controls that are generic. Most GUI environments come with a hefty bunch of common controls that we can just use in our application. We can build new controls ourselves, and often it’s a good idea to do so, but there is still a distinction between generic reusable controls and specific forms. Even specially written controls can be reused across multiple forms.

The form contains two main responsibilities:

  • Screen layout: defining the arrangement of the controls on the screen, together with their hierarchic structure with other.
  • Form Logic: behavior that cannot be easily programmed into the controls themselves.

Most GUI development environments allow the developer to define screen layout with a graphical editor that allows you to drag and drop the controls onto a space for the form. This pretty much handles the form layout. This way it’s easy to setup a pleasing layout of controls on the form (although it isn’t always the best way to do it – we’ll come to that later.)

The controls display data – in this case about the reading. This data will pretty much always come from somewhere else, in this case let’s assume a SQL database as that’s the environment that most of these client server tools assume. In most situations there are three copies of the data involved:

  • One copy of data lies in the database itself. This copy is the lasting record of the data, so I call it the record state. The record state is usually shared and visible to multiple people via various mechanisms.
  • A further copy lies inside in-memory Record Sets within the application. Most client-server environments provided tools which made this easy to do. This data was only relevant for one particular session between the application and the database, so I call it session state. Essentially this provides a temporary local version of the data that the user works on until they save, or commit it, back to the database – at which point it merges with the record state. I won’t worry about the issues around coordinating record state and session state here: I did go into various techniques in [P of EAA].
  • The final copy lies inside the GUI components themselves. This, strictly, is the data they see on the screen, hence I call it the screen state. It is important to the UI how screen state and session state are kept synchronized.

Keeping screen state and session state synchronized is an important task. A tool that helped make this easier was Data Binding. The idea was that any change to either the control data, or the underlying record set was immediately propagated to the other. So if I alter the actual reading on the screen, the text field control effectively updates the correct column in the underlying record set.

In general data binding gets tricky because if you have to avoid cycles where a change to the control, changes the record set, which updates the control, which updates the record set…. The flow of usage helps avoid these – we load from the session state to the screen when the screen is opened, after that any changes to the screen state propagate back to the session state. It’s unusual for the session state to be updated directly once the screen is up. As a result data binding might not be entirely bi-directional – just confined to initial upload and then propagating changes from the controls to the session state.

Data Binding handles much of the functionality of a client sever application pretty nicely. If I change the actual value the column is updated, even changing the selected station alters the currently selected row in the record set, which causes the other controls to refresh.

Much of this behavior is built in by the framework builders, who look at common needs and make it easy to satisfy them. In particular this is done by setting values, usually called properties, on the controls. The control binds to a particular column in a record set by having its column name set through a simple property editor.

Using data binding, with the right kind of parameterization, can take you a long way. However it can’t take you all the way – there’s almost always some logic that won’t fit with the parameterization options. In this case calculating the variance is an example of something that doesn’t fit in this built in behavior – since it’s application specific it usually lies in the form.

In order for this to work the form needs to be alerted whenever the value of the actual field changes, which requires the generic text field to call some specific behavior on the form. This is a bit more involved than taking a class library and using it through calling it as Inversion of Control is involved.

There are various ways of getting this kind of thing to work – the common one for client-server tool-kits was the notion of events. Each control had a list of events it could raise. Any external object could tell a control that it was interested in an event – in which case the control would call that external object when the event was raised. Essentially this is just a rephrasing of the Observer pattern where the form is observing the control. The framework usually provided some mechanism where the developer of the form could write code in a subroutine that would be invoked when the event occurred. Exactly how the link was made between event and routine varied between platform and is unimportant for this discussion – the point is that some mechanism existed to make it happen.

Once the routine in the form has control, it can then do whatever it needed. It can carry out the specific behavior and then modify the controls as necessary, relying on data binding to propagate any of these changes back to the session state.

This is also necessary because data binding isn’t always present. There is a large market for windows controls, not all of them do data binding. If data binding isn’t present then it’s up to the form to carry out the synchronization. This could work by pulling data out of the record set into the widgets initially, and copying the changed data back to the record set when the save button was pressed.

Let’s examine our editing of the actual value, assuming that data binding is present. The form object holds direct references to the generic controls. There’ll be one for each control on the screen, but I’m just interested in the actual, variance, and target fields here.

Figure 2: Class diagram for forms and controls

The text field declares an event for text changed, when the form assembles the screen during initialization it subscribes itself to that event, binding it a method on itself – here actual_textChanged.

Figure 3: Sequence diagram for changing a genre with forms and controls.

When the user changes the actual value, the text field control raises its event and through the magic of framework binding the actual_textChanged is run. This method gets the text from the actual and target text fields, does the subtraction, and puts the value into the variance field. It also figures out what color the value should be displayed with and adjusts the text color appropriately.

We can summarize the architecture with a few soundbites:

  • Developers write application specific forms that use generic controls.
  • The form describes the layout of controls on it.
  • The form observes the controls and has handler methods to react to interesting events raised by the controls.
  • Simple data edits are handled through data binding.
  • Complex changes are done in the form’s event handling methods.

Model View Controller

Probably the widest quoted pattern in UI development is Model View Controller (MVC) – it’s also the most misquoted. I’ve lost count of the times I’ve seen something described as MVC which turned out to be nothing like it. Frankly a lot of the reason for this is that parts of classic MVC don’t really make sense for rich clients these days. But for the moment we’ll take a look at its origins.

As we look at MVC it’s important to remember that this was one of the first attempts to do serious UI work on any kind of scale. Graphical User Interfaces were not exactly common in the 70’s. The Forms and Controls model I’ve just described came after MVC – I’ve described it first because it’s simpler, not always in a good way. Again I’ll discuss Smalltalk 80’s MVC using the assessment example – but be aware that I am taking a few liberties with the actual details of Smalltalk 80 to do this – for start it was monochrome system.

At the heart of MVC, and the idea that was the most influential to later frameworks, is what I call Separated Presentation. The idea behind Separated Presentation is to make a clear division between domain objects that model our perception of the real world, and presentation objects that are the GUI elements we see on the screen. Domain objects should be completely self contained and work without reference to the presentation, they should also be able to support multiple presentations, possibly simultaneously. This approach was also an important part of the Unix culture, and continues today allowing many applications to be manipulated through both a graphical and command-line interface.

In MVC, the domain element is referred to as the model. Model objects are completely ignorant of the UI. To begin discussing our assessment UI example we’ll take the model as a reading, with fields for all the interesting data upon it. (As we’ll see in a moment the presence of the list box makes this question of what is the model rather more complex, but we’ll ignore that list box for a little bit.)

In MVC I’m assuming a Domain Model of regular objects, rather than the Record Set notion that I had in Forms and Controls. This reflects the general assumption behind the design. Forms and Controls assumed that most people wanted to easily manipulate data from a relational database, MVC assumes we are manipulating regular Smalltalk objects.

The presentation part of MVC is made of the two remaining elements: view and controller. The controller’s job is to take the user’s input and figure out what to do with it.

At this point I should stress that there’s not just one view and controller, you have a view-controller pair for each element of the screen, each of the controls and the screen as a whole. So the first part of reacting to the user’s input is the various controllers collaborating to see who got edited. In the case that’s it’s the actuals text field so that text field controller would now handle what happens next.

Figure 4: Essential dependencies between model, view, and controller. (I call this essential because in fact the view and controller do link to each other directly, but developers mostly don’t use this fact.)

Like later environments, Smalltalk figured out that you wanted generic UI components that could be reused. In this case the component would be the view-controller pair. Both were generic classes, so needed to be plugged into the application specific behavior. There would be an assessment view that would represent the whole screen and define the layout of the lower level controls, in that sense similar to a form in Forms and Controllers. Unlike the form, however, MVC has no event handlers on the assessment controller for the lower level components.

Figure 5: Classes for an MVC version of an ice-cream monitor display

The configuration of the text field comes from giving it a link to its model, the reading, and telling it what what method to invoke when the text changes. This is set to ‘#actual:’ when the screen is initialized (a leading ‘#’ indicates a symbol, or interned string, in Smalltalk). The text field controller then makes a reflective invocation of that method on the reading to make the change. Essentially this is the same mechanism as occurs for Data Binding, the control is linked to the underlying object (row) and told which method (column) it manipulates.

Figure 6: Changing the actual value for MVC.

So there is no overall object observing low level widgets, instead the low level widgets observe the model, which itself handles many of the decision that would be made by the form. In this case, when it comes to figuring out the variance, the reading object itself is the natural place to do that.

Observers do occur in MVC, indeed it’s one of the ideas credited to MVC. In this case all the views and controllers observe the model. When the model changes, the views react. In this case the actual text field view is notified that the reading object has changed, and invokes the method defined as the aspect for that text field – in this case #actual – and sets its value to the result. (It does something similar for the color, but this raises its own specters that I’ll get to in a moment.)

You’ll notice that the text field controller didn’t set the value in the view itself, it updated the model and then just let the observer mechanism take care of the updates. This is quite different to the forms and controls approach where the form updates the control and relies on data binding to update the underlying record-set. These two styles I describe as patterns: Flow Synchronization and Observer Synchronization. These two patterns describe alternative ways of handling the triggering of synchronization between screen state and session state. Forms and Controls do it through the flow of the application manipulating the various controls that need to be updated directly. MVC does it by making updates on the model and then relying of the observer relationship to update the views that are observing that model.

Flow Synchronization is even more apparent when data binding isn’t present. If the application needs to do synchronization itself, then it was typically done at important point in the application flow – such as when opening a screen or hitting the save button.

One of the consequences of Observer Synchronization is that the controller is very ignorant of what other widgets need to change when the user manipulates a particular widget. While the form needs to keep tabs on things and make sure the overall screen state is consistent on a change, which can get pretty involved with complex screens, the controller in Observer Synchronization can ignore all this.

This useful ignorance becomes particularly handy if there are multiple screens open viewing the same model objects. The classic MVC example was a spreadsheet like screen of data with a couple of different graphs of that data in separate windows. The spreadsheet window didn’t need to be aware of what other windows were open, it just changed the model and Observer Synchronization took care of the rest. With Flow Synchronization it would need some way of knowing which other windows were open so it tell them to refresh.

While Observer Synchronization is nice it does have a downside. The problem with Observer Synchronization is the core problem of the observer pattern itself – you can’t tell what is happening by reading the code. I was reminded of this very forcefully when trying to figure out how some Smalltalk 80 screens worked. I could get so far by reading the code, but once the observer mechanism kicked in the only way I could see what was going on was via a debugger and trace statements. Observer behavior is hard to understand and debug because it’s implicit behavior.

While the different approaches to synchronization are particularly noticeable from looking at the sequence diagram, the most important, and most influential, difference is MVC’s use of Separated Presentation. Calculating the variance between actual and target is domain behavior, it is nothing to do with the UI. As a result following Separated Presentation says we should place this in the domain layer of the system – which is exactly what the reading object represents. When we look at the reading object, the variance feature makes complete sense without any notion of the user interface.

At this point, however, we can begin to look at some complications. There’s two areas where I’ve skipped over some awkward points that get in the way of MVC theory. The first problem area is to deal with setting the color of the variance. This shouldn’t really fit into a domain object, as the color by which we display a value isn’t part of the domain. The first step in dealing with this is to realize that part of the logic is domain logic. What we are doing here is making a qualitative statement about the variance, which we could term as good (over by more than 5%), bad (under by more than 10%), and normal (the rest). Making that assessment is certainly domain language, mapping that to colors and altering the variance field is view logic. The problem lies in where we put this view logic – it’s not part of our standard text field.

This kind of problem was faced by early smalltalkers and they came up with some solutions. The solution I’ve shown above is the dirty one – compromise some of the purity of the domain in order to make things work. I’ll admit to the occasional impure act – but I try not to make a habit of it.

We could do pretty much what Forms and Controls does – have the assessment screen view observe the variance field view, when the variance field changes the assessment screen could react and set the variance field’s text color. Problems here include yet more use of the observer mechanism – which gets exponentially more complicated the more you use it – and extra coupling between the various views.

A way I would prefer is to build a new type of the UI control. Essentially what we need is a UI control that asks the domain for a qualitative value, compares it to some internal table of values and colors, and sets the font color accordingly. Both the table and message to ask the domain object would be set by the assessment view as it’s assembling itself, just as it sets the aspect for the field to monitor. This approach could work very well if I can easily subclass text field to just add the extra behavior. This obvious depends on how well the components are designed to enable sub-classing – Smalltalk made it very easy – other environments can make it more difficult.

Figure 7: Using a special subclass of text field that can be configured to determine the color.

The final route is to make a new kind of model object, one that’s oriented around around the screen, but is still independent of the widgets. It would be the model for the screen. Methods that were the same as those on the reading object would just be delegated to the reading, but it would add methods that supported behavior relevant only to the UI, such as the text color.

Figure 8: Using an intermediate Presentation Model to handle view logic.

This last option works well for a number of cases and, as we’ll see, became a common route for Smalltalkers to follow – I call this a Presentation Model because it’s a model that is really designed for and thus part of the presentation layer.

The Presentation Model works well also for another presentation logic problem – presentation state. The basic MVC notion assumes that all the state of the view can be derived from the state of the model. In this case how do we figure out which station is selected in the list box? The Presentation Model solves this for us by giving us a place to put this kind of state. A similar problem occurs if we have save buttons that are only enabled if data has changed – again that’s state about our interaction with the model, not the model itself.

So now I think it’s time for some soundbites on MVC.

  • Make a strong separation between presentation (view & controller) and domain (model) – Separated Presentation.
  • Divide GUI widgets into a controller (for reacting to user stimulus) and view (for displaying the state of the model). Controller and view should (mostly) not communicate directly but through the model.
  • Have views (and controllers) observe the model to allow multiple widgets to update without needed to communicate directly – Observer Synchronization.

VisualWorks Application Model

As I’ve discussed above, Smalltalk 80’s MVC was very influential and had some excellent features, but also some faults. As Smalltalk developed in the 80’s and 90’s this led to some significant variations on the classic MVC model. Indeed one could almost say that MVC disappeared, if you consider the view/controller separation to be an essential part of MVC – which the name does imply.

The things that clearly worked from MVC were Separated Presentation and Observer Synchronization. So these stayed as Smalltalk developed – indeed for many people they were the key element of MVC.

Smalltalk also fragmented in these years. The basic ideas of Smalltalk, including the (minimal) language definition remained the same, but we saw multiple Smalltalks develop with different libraries. From a UI perspective this became important as several libraries started using native widgets, the controls used by the Forms and Controls style.

Smalltalk was originally developed by Xerox Parc labs and they span off a separate company, ParcPlace, to market and develop Smalltalk. ParcPlace Smalltalk was called VisualWorks and made a point of being a cross-platform system. Long before Java you could take a Smalltalk program written in Windows and run it right away on Solaris. As a result VisualWorks didn’t use native widgets and kept the GUI completely within Smalltalk.

In my discussion of MVC I finished with some problems of MVC – particularly how to deal with view logic and view state. VisualWorks refined its framework to deal with this by coming up with a construct called the Application Model – a construct that moves towards Presentation Model. The idea of using something like a Presentation Model wasn’t new to VisualWorks – the original Smalltalk 80 code browser was very similar, but the VisualWorks Application Model baked it fully into the framework.

A key element of this kind of smalltalk was the idea of turning properties into objects. In our usual notion of objects with properties we think of a Person object having properties for name and address. These properties may be fields, but could be something else. There is usually a standard convention for accessing the properties: in Java we would see temp = aPerson.getName() and aPerson.setName("martin"), in C# it would temp = aPerson.name and aPerson.name = "martin".

A Property Object changes this by having the property return an object that wraps the actual value. So in VisualWorks when we ask for a name we get back a wrapping object. We then get the actual value by asking the wrapping object for its value. So accessing a person’s name would use temp = aPerson name value and aPerson name value: 'martin'

Property objects make the mapping between widgets and model a little easier. We just have to tell the widget what message to send to get the corresponding property, and the widget knows to access the proper value using value and value:. VisualWorks’s property objects also allow you to set up observers with the message onChangeSend: aMessage to: anObserver.

You won’t actually find a class called property object in Visual Works. Instead there were a number of classes that followed the value/value:/onChangeSend: protocol. The simplest is the ValueHolder – which just contains its value. More relevant to this discussion is the AspectAdaptor. The AspectAdaptor allowed a property object to wrap a property of another object completely. This way you could define a property object on a PersonUI class that wrapped a property on a Person object by code like

adaptor := AspectAdaptor subject: person
adaptor forAspect: #name
adaptor onChangeSend: #redisplay to: self

So let’s see how the application model fits into our running example.

Figure 9: Class diagram for visual works application model on the running example

The main difference between using an application model and classic MVC is that we now have an intermediate class between the domain model class (Reader) and the widget – this is the application model class. The widgets don’t access the domain objects directly – their model is the application model. Widgets are still broken down into views and controllers, but unless you’re building new widgets that distinction isn’t important.

When you assemble the UI you do so in a UI painter, while in that painter you set the aspect for each widget. The aspect corresponds to a method on the application model that returns a property object.

Figure 10: Sequence diagram showing how updating the actual value updates the variance text.

Figure 10 shows how the basic update sequence works. When I change a value in text field, that field then updates the value in the property object inside the application model. That update follows through to the underlying domain object, updating its actual value.

At this point the observer relationships kick in. We need to set things up so that updating the actual value causes the reading to indicate that it has changed. We do this by putting a call in the modifier for actual to indicate that the reading object has changed – in particular that the variance aspect has changed. When setting up the aspect adaptor for variance it’s easy to tell it to observe the reader, so it picks up the update message which it then forwards to its text field. The text field then initiates getting a new value, again through the aspect adaptor.

Using the application model and property objects like this helps us wire up the updates without having to write much code. It also supports fine-grained synchronization (which I don’t think is a good thing).

Application models allow us to separate behavior and state that’s particular to the UI from real domain logic. So one of the problems I mentioned earlier, holding the currently selected item in a list, can be solved by using a particular kind of aspect adaptor that wraps the domain model’s list and also stores the currently selected item.

The limitation of all this, however, is that for more complex behavior you need to construct special widgets and property objects. As an example the provided set of objects don’t provide a way to link the text color of the variance to the degree of variance. Separating the application and domain models does allow us to separate the decision making in the right way, but then to use widgets observing aspect adapters we need to make some new classes. Often this was seen as too much work, so we could make this kind of thing easier by allowing the application model to access the widgets directly, as in Figure 11.

Figure 11: Application Model updates colors by manipulating widgets directly.

Directly updating the widgets like this is not part of Presentation Model, which is why the visual works application model isn’t truly a Presentation Model. This need to manipulate the widgets directly was seen by many as a bit of dirty work-around and helped develop the Model-View-Presenter approach.

So now the soundbites on Application Model

  • Followed MVC in using Separated Presentation and Observer Synchronization.
  • Introduced an intermediate application model as a home for presentation logic and state – a partial development of Presentation Model.
  • Widgets do not observe domain objects directly, instead they observe the application model.
  • Made extensive use of Property Objects to help connect the various layers and to support the fine grained synchronization using observers.
  • It wasn’t the default behavior for the application model to manipulate widgets, but it was commonly done for complicated cases.

Model-View-Presenter (MVP)

MVP is an architecture that first appeared in IBM and more visibly at Taligent the 1990’s. It’s most commonly referred via the Potel paper. The idea was further popularized and described by the developers of Dolphin Smalltalk. As we’ll see the two descriptions don’t entirely mesh but the basic idea underneath it has become popular.

To approach MVP I find it helpful to think about a significant mismatch between two strands of UI thinking. On the one hand is the Forms and Controller architecture which was mainstream approach to UI design, on the other is MVC and its derivatives. The Forms and Controls model provides a design that is easy to understand and makes a good separation between reusable widgets and application specific code. What it lacks, and MVC has so strongly, is Separated Presentation and indeed the context of programming using a Domain Model. I see MVP as a step towards uniting these streams, trying to take the best from each.

The first element of Potel is to treat the view as structure of widgets, widgets that correspond to the controls of the Forms and Controls model and remove any view/controller separation. The view of MVP is a structure of these widgets. It doesn’t contain any behavior that describes how the widgets react to user interaction.

The active reaction to user acts lives in a separate presenter object. The fundamental handlers for user gestures still exist in the widgets, but these handlers merely pass control to the presenter.

The presenter then decides how to react to the event. Potel discusses this interaction primarily in terms of actions on the model, which it does by a system of commands and selections. A useful thing to highlight here is the approach of packaging all the edits to the model in a command – this provides a good foundation for providing undo/redo behavior.

As the Presenter updates the model, the view is updated through the same Observer Synchronization approach that MVC uses.

The Dolphin description is similar. Again the main similarity is the presence of the presenter. In the Dolphin description there isn’t the structure of the presenter acting on the model through commands and selections. There is also explicit discussion of the presenter manipulating the view directly. Potel doesn’t talk about whether presenters should do this or not, but for Dolphin this ability was essential to overcoming the kind of flaw in Application Model that made it awkward for me to color the text in the variation field.

One of the variations in thinking about MVP is the degree to which the presenter controls the widgets in the view. On one hand there is the case where all view logic is left in the view and the presenter doesn’t get involved in deciding how to render the model. This style is the one implied by Potel. The direction behind Bower and McGlashan was what I’m calling Supervising Controller, where the view handles a good deal of the view logic that can be describe declaratively and the presenter then comes in to handle more complex cases.

You can also move all the way to having the presenter do all the manipulation of the widgets. This style, which I call Passive View isn’t part of the original descriptions of MVP but got developed as people explored testability issues. I’m going to talk about that style later, but that style is one of the flavors of MVP.

Before I contrast MVP with what I’ve discussed before I should mention that both MVP papers here do this too – but not quite with the same interpretation I have. Potel implies that MVC controllers were overall coordinators – which isn’t how I see them. Dolphin talks a lot about issues in MVC, but by MVC they mean the VisualWorks Application Model design rather than classic MVC that I’ve described (I don’t blame them for that – trying to get information on classic MVC isn’t easy now let alone then.)

So now it’s time for some contrasts:

  • Forms and Controls: MVP has a model and the presenter is expected to manipulate this model with Observer Synchronizationthen updating the view. Although direct access to the widgets is allowed, this should be in addition to using the model not the first choice.
  • MVC: MVP uses a Supervising Controller to manipulate the model. Widgets hand off user gestures to the Supervising Controller. Widgets aren’t separated into views and controllers. You can think of presenters as being like controllers but without the initial handling of the user gesture. However it’s also important to note that presenters are typically at the form level, rather than the widget level – this is perhaps an even bigger difference.
  • Application Model: Views hand off events to the presenter as they do to the application model. However the view may update itself directly from the domain model, the presenter doesn’t act as a Presentation Model. Furthermore the presenter is welcome to directly access widgets for behaviors that don’t fit into the Observer Synchronization.

There are obvious similarities between MVP presenters and MVC controllers, and presenters are a loose form of MVC controller. As a result a lot of designs will follow the MVP style but use ‘controller’ as a synonym for presenter. There’s a reasonable argument for using controller generally when we are talking about handling user input.

Figure 12: Sequence diagram of the actual reading update in MVP.

Let’s look at an MVP (Supervising Controller) version of the ice-cream monitor ( Figure 12). It starts much the same as the Forms and Controls version – the actual text field raises an event when its text is changed, the presenter listens to this event and gets the new value of the field. At this point the presenter updates the reading domain object, which the variance field observes and updates its text with. The last part is the setting of the color for the variance field, which is done by the presenter. It gets the category from the reading and then updates the color of the variance field.

Here are the MVP soundbites:

  • User gestures are handed off by the widgets to a Supervising Controller.
  • The presenter coordinates changes in a domain model.
  • Different variants of MVP handle view updates differently. These vary from using Observer Synchronization to having the presenter doing all the updates with a lot of ground in-between.

Humble View

In the past few years there’s been a strong fashion for writing self-testing code. Despite being the last person to ask about fashion sense, this is a movement that I’m thoroughly immersed in. Many of my colleagues are big fans of xUnit frameworks, automated regression tests, Test-Driven Development, Continuous Integration and similar buzzwords.

When people talk about self-testing code user-interfaces quickly raise their head as a problem. Many people find that testing GUIs to be somewhere between tough and impossible. This is largely because UIs are tightly coupled into the overall UI environment and difficult to tease apart and test in pieces.

Sometimes this test difficulty is over-stated. You can often get surprisingly far by creating widgets and manipulating them in test code. But there are occasions where this is impossible, you miss important interactions, there are threading issues, and the tests are too slow to run.

As a result there’s been a steady movement to design UIs in such a way that minimizes the behavior in objects that are awkward to test. Michael Feathers crisply summed up this approach in The Humble Dialog Box. Gerard Meszaros generalized this notion to idea of a Humble Object – any object that is difficult to test should have minimal behavior. That way if we are unable to include it in our test suites we minimize the chances of an undetected failure.

The Humble Dialog Box paper uses a presenter, but in a much deeper way than the original MVP. Not just does the presenter decide how to react to user events, it also handles the population of data in the UI widgets themselves. As a result the widgets no longer have, nor need, visibility to the model; they form a Passive View, manipulated by the presenter.

This isn’t the only way to make the UI humble. Another approach is to use Presentation Model, although then you do need a bit more behavior in the widgets, enough for the widgets to know how to map themselves to the Presentation Model.

The key to both approaches is that by testing the presenter or by testing the presentation model, you test most of the risk of the UI without having to touch the hard-to-test widgets.

With Presentation Model you do this by having all the actual decision making made by the Presentation Model. All user events and display logic is routed to the Presentation Model, so that all the widgets have to do is map themselves to properties of the Presentation Model. You can then test most of the behavior of the Presentation Model without any widgets being present – the only remaining risk lies in the widget mapping. Provided that this is simple you can live with not testing it. In this case the screen isn’t quite as humble as with the Passive View approach, but the difference is small.

Since Passive View makes the widgets entirely humble, without even a mapping present, Passive View eliminates even the small risk present with Presentation Model. The cost however is that you need a Test Double to mimic the screen during your test runs – which is extra machinery you need to build.

A similar trade-off exists with Supervising Controller. Having the view do simple mappings introduces some risk but with the benefit (as with Presentation Model) of being able to specify simple mapping declaratively. Mappings will tend to be smaller for Supervising Controller than for Presentation Model as even complex updates will be determined by the Presentation Model and mapped, while a Supervising Controller will manipulate the widgets for complex cases without any mapping involved.



Further Reading

For recent articles that develop these ideas further, take a look at my bliki.


Acknowledgements

Vassili Bykov generously let me have a copy of Hobbes – his implementation of Smalltalk-80 version 2 (from the early 1980’s)which runs in modern VisualWorks. This provided me with a live example of Model-View-Controller which was extremely helpful in answering detailed questions of how it worked and how it was used in the default image. Many people in those days considered it impractical to use a virtual machine. I wonder what our prior selves would have thought to see me running Smalltalk 80 in a virtual machine written in VisualWorks running in the VisualWorks virtual machine on Windows XP running in a VMware virtual machine running on Ubuntu.

from:http://www.martinfowler.com/eaaDev/uiArchs.html