Monday, December 31, 2007

ASP.Net Page Designing Strategy

ASP.Net 2.0 brought in an important concept about building a web page, the master page. In fact, master page is an overall concept, it includes master page and nested master page(s) ( can be multi-layer). In this artical, I will examine the elements that build up a multi-layer page structure and the inter-accessability among them. A multi-layer page structure is broadly used in creating a consistent web site.

[1] Define a master page

To define a master page, first we need to add a Master directive to a .master file at it's first line. .Net recognizes a master page by the file name extention and the directive declaration so as to find the bebind code of the MasterPage class. See the code snippet bellow.

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="RootMaster.master.cs" Inherits="RootMaster" %>

Next, we create the behind code for the master page. It is nothing but a class derived from System.Web.UI.MasterPage.

// the RootMaster.master.cs
public partial class RootMaster : System.Web.UI.MasterPage
{
}


Once these are done, we start to design the master page layout and define placeholder(s). All design elements outside the placeholder(s) are shared among pages that derives from this master page.

<!--
master page defines content placeholder(s) which are going to be filled in nested master pages or pages.
-->
<asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
</asp:contentplaceholder>
<asp:contentplaceholder id="ContentPlaceHolder2" runat="server">
</asp:contentplaceholder>

Note, the HTML page specific elemtents such as <head>, <title>, <body>, <form> and so forth are only showing in master page. Nested master pages and pages are just defining content for filling the placeHolders. From this sense, only master page is a page, while nested master page and page are just page assemblies.


[2] Nested master page
The great thing of nested master page is that it bring the flexibility to create multi-level of sharing page element. Concretely, it define page contents filling the place holders in master page, at the mean time, it defines new place holder in a new level of specifics.

Like defining master page, nested master page has .master file name extention. In this file, we need to set it's master page attributes by writing Master dirctive at the first top line. see bellow.

<%@ Master ClassName="NestedMaster" Language="C#" MasterPageFile="~/RootMaster.master" AutoEventWireup="false" CodeFile="NestedMaster.master.cs" Inherits="NestedMaster" %>

Compareing with that in the master page, We noticed that this declaration has a new attribute of MasterPageFile which has the value refering to the parent master page.

At this point, we may wonder how the code behind defines the NestedMaster class. the following code snippets shows just that.

public partial class NestedMaster : RootMaster
{
}

Here we noticed that nested master page class inherits the parent master page class rather than System.Web.UI.MasterPage.


Next, let's look at how nested master page fill place holders defined in parent master page and define new place holder(s)

<asp:content ContentPlaceholderID="plcHolderMain" id="MainContent" runat="server">
<DIV class="clsSectionHeader"></DIV>
<asp:contentplaceholder id="plcHolderSearch" runat="server">
</asp:contentplaceholder>

<DIV class="clsSubSectionHeader">SEARCH RESULTS <asp:Label Runat="server" ID="lblSrchFilter"></asp:Label>
</DIV>

<asp:contentplaceholder id="plcHolderResults" runat="server">
</asp:contentplaceholder>
</asp:content>

The code snippet above defines content filling the place holder of "plcholderMain" and defines two new smaller place holders "plcholderSearch" and "plcHolderResult".

[3] Multi-layer nested master page
Theoratically, nested master page has unlimited levels. It gives fine grain control when developing complex-layout web page.

Defining a lower level of nested master page is no different as defining a first level nested master page aforementioned except that the declarive in .master file has MasterPageFile set to the parent nested master page instead of the root master page; the bebind code class inherits parent master class rather rather than the RootMaster class.

<%@ Master ClassName="SubNestedMaster" Language="C#" MasterPageFile="~/NestedMaster.master" AutoEventWireup="false" CodeFile="SubNestedMaster.master.cs" Inherits="SubNestedMaster" %>

public partial class SubNestedMaster : NestedMaster
{
}


[4] Define pages inherited from master/nested master page
There are no difference between defining a page with master page of master and a page with master page nested master. what we need to do is set the MasterPagerFile property of Page directive to right .master file. In the following directive, the page set it's master to RootMaster.master which is a master page

<%@ Page Language="C#" MasterPageFile="~/RootMaster.master" AutoEventWireup="true" CodeFile="ModelPage.aspx.cs" Inherits="ModelPage" Title="Untitled Page" %>

In code behind file, we only need define our page class that inherited from System.Web.UI.Page.

public partial class ModelPage : System.Web.UI.Page
{
}

[5] The interaccessability
Because master page, nested master page and page end up rendering one physical page, it is essential to ensure that controls, which may distributed in different type of "pages", can communicate with each other.

However, It makes sense that we only examine elements in lower level "page" accessing elements in higher level "page". Not the reverse.

[5.1] Access master page and nested master page from a page
As shown in the following code adopted from ModelPage's code behind, we casts the page's Master object to RootMaster
type and then access a user custom control defined in that master page.

((UserControls_ModelUserControl1)((RootMaster)Master).UC1).CustomName = "Click Me";


The Master property of a page refers to the MasterPage object the page declared. Even this.Master represent an object of System.Web.UI.MasterPage, it actually is our extended and customized MasterPage object.


But, by default a control in a master page or nested master page is "protected", how come we can access it in a page? In fact we exposed the controls that supposed to be accessed from outside of the page. As shows in the following code.


public UserControls_ModelUserControl1 UC1
{
get { return this.ModelUserControl1_1; }
}

Another way to access a control is using FindControl method of the MasterPage class. .Net's Control class has the method. See the following code.

((UserControls_ModelUserControl1)(Master).FindControl("ModelUserControl1_1")).CustomName = "found Click me";

If we don't want to cast the default MasterPage object to our custom master page, like ((RootMaster)Master) mentioned before, we can use MasterType page directive indicating the compiler the specific master page so that not use the default master page type.


<%@ MasterType TypeName ="RootMaster" %>

then the accessing code will be

((UserControls_ModelUserControl1)(Master).UC1).CustomName = "Click Me";



[5.2] Access master page and nested master page from a nested master page

Due to a nested master page extends a master page or a parent nested master page, so the access should be straight forward through "this".

Regarding page accessability, what we examined above is actually a static model. A question left in my mind is that what about dynamically loaded controls in master page or nested master page? I will look at it in detail in another artical.


In this artical, I discussed one essential aspect of ASP.Net's web page designing model, the master page strategy. As we can see, multi-layer nested master page implements the real nature of element sharing in a web application and brings power to building consistent web site.

WPF Fundamentals

1. Introduction
Window Presentation Foundation, also named Avalon, is Microsoft's flagship for next generation application UX(user experience) development. It's UI model eliminates the difference of UI elements used in Web page rendering, Windows applications and smart devices. In addition, 3D graphics and animation features are incorporated in this framework so as to create rich user experience for Windows Vista. Also, vector graphics rendering ensures quality for different image size and resolution equipments.


2. XAML
Up front of WPF is XAML - Extensible Application Markup Language, a new markup language standard brought in along with WFP by Microsoft used to describe and define UIs.

Like Asp.net web page, XAML not only has the power for designing layout, it also supports themes and skins to build application-wide consistent pages. Themes and skins are defined as styles.

A XAML document usually refers to two namespaces (see the following code snippet), where XAML schemas are defined. The XAML compiler uses this schema to validate and parse XAML documents.

<Page x:Class="WPFProject.Page1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Page1">
...
</Page>


3. The WPF Stack
Like most other frameworks, WFP runs on a layered manner. The topmost layer, called Presentation Framework layer, runs on top of Presentation Core layer. These two layers have all the classes of managed code that are controlled by the next layer, the CLR. Under CLR are milcore, User32, and DirectX. They call OS kernel and provide the system support for the top levels

4. WPF Application
The System.Windows.Application class is a framework for defining a WPF application. It exposed programming handlers to customize all aspects accross your application's lifecycle.

... the handlers

System.Windows.Application's StartupUri property is where we can specify the start UI page to run. The following snippet specifies the starting page in XAML tag and with code.

<Application x:Class="WPFProject.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="whatever.xaml"
>
</Application>

or in behind code:

this.StartupUri = "whatever.xmal";


A WPF application instance can he hosted in a standalone commandline application or in XBAP(XAML Browser Application), a IE embeded application

Visual Studio 2005 provides a choice for a WPF project to be compiled to a console application, Windows applicaiton or a class library.


5. New Programming Features
5.1 Dependency Property
5.2 Attached Property
5.3 Routed Events
5.4 Animation coding

The details of these topics are exmined in another artical.

6. Questions
What is Site of Origin?
How to define and use Resources
A WPF application can be compiled into a class library, in which circumstance and how to access and incorporate the XAML pages?
What is provided by milcore(see 3: The WPF stack)?
How to use databinding in XAML?

Friday, December 28, 2007

WCF Notes

WCF Security

Microsoft WCF is designated to develop Service Oriented Architecture (SOA) application. Under SOA, modules of an application are services, that most likely are deployed in different hosts. The major type of communication within the system are communications between service providers and service consumers, and security is one of the most concerning aspects.

There are two type of plot to ensure securityc ommunication, message based security and transport layer based security. Both can be implemented with configuration settings, i.e., it is transparent to service provider and service consumer, developers don't need to write any code for implementing security. .Net implements them bebind the scene.

In order to indicate .Net what security messure to use, you need to customize the service binding entries in application's configuration file. Note that the configuration file can be web.config, app.config or theApplicationName.config based on the type of application.

The following snippet shows an example of a service configuration.

<services>
<service type="DerivativesCalculator.DerivativesCalculatorServiceType,DerivativesCalculatorService">
<endpoint
address=""
binding="basicHttpBinding"
contract="DerivativesCalculator.IDerivativesCalculator,DerivativesCalculatorService" />
</service>
</services>

By setting the value of binding attribute to "basicHttpBinding", it indicates .Net to uses WS-I Basic Profile 1.1 protocol for communication. This protocol, dominately used in web service, defines the HTTP elements and the XMLInfoSet message encoding features. By default, it doesn't have security messures applied.


The following snippet changes the default value of bindingConfiguration attribute of the system default binding object. The value of "SecureBasicHttpBinding", which refers to the binding entry with security mode set to "Transport". This will let .Net implement encryption on network transportation layer.

<service type="DerivativesCalculatorService.DerivativesCalculatorServiceType,DerivativesCalculatorService">
<endpoint contract="DerivativesCalculatorService.IDerivativesCalculator,DerivativesCalculatorService=" binding="basicHttpBinding" address="" bindingconfiguration="SecureBasicHttpBinding">
</service>

<bindings>
<basichttpbinding>
<binding name="SecureBasicHttpBinding">
<security mode="Transport">
<transport clientcredentialtype="None">
</security>
</binding>
</basichttpbinding>
</bindings>

Because it uses transport layer security, we need to configure IIS (the service host) to support SSL/TLS - Secure Socket Layer/ Transport Layer Security. Also, on the service consumer end, the address attribute of the endpoint entry should use "HTTPS:" scheme instead of "HTTP:", thereby redirecting the request and response through SSL/TSL socket.

Another way to ensure security is through message based encryption scheme - WS-Security. It is done just by making a bit change in the configure file. Notice the following configuration snippet:

<service type="DerivativesCalculator.DerivativesCalculatorServiceType,DerivativesCalculatorService">
<endpoint contract="DerivativesCalculator.IDerivativesCalculator,DerivativesCalculatorService" binding="wsHttpBinding" address="Calculator">
</service>

On the client side:

<client>
<endpoint name="IISHostedEndpoint" contract="IDerivativesCalculator" binding="wsHttpBinding" address="http://localhost:8000/Derivatives/Calculator">
</client>

Noticablly, what really changed is the value of binding attribute from "basicHttpBinding" to "wsHttpBinding", which indicates .Net using WS-Security scheme for the communication.

Message Logging
WCF comes with message logging facilities. It paves an easy way for tracing and administration. The facilities generate messages and output a stream, so we need also to configure a trace listener, a reguler feature in System.Diagnositics namespace, to receive it. Fortunately, what we need to do for all these is to customize the configuration file.

<system.diagnostics>
<sources>
<source name="System.ServiceModel.MessageLogging" switchvalue="Verbose">
<listeners>
<add type="System.Diagnostics.XmlWriterTraceListener" name="xml" initializedata="c:\logs\message.log">
</listeners>
</source>
</sources>
<trace autoflush="true">
</system.diagnostics>

Above is a .Net recognizable configuration section of "system.diagostics". The TCF message logging facility, defined as a source, has one listener of XmlWriterTraceListener. The listener writes received messages to the specified file.

The following snippet shows the System.serviceModel configuration section, where WCF message logging feature is turned on and customized.

<system.servicemodel>
<diagnostics>
<messagelogging logentiremessage="true" maxmessagestolog="300" logmessagesatservicelevel="false" logmalformedmessages="true" logmessagesattransportlevel="true">
</diagnostics>
</system.servicemodel>

Generate WCF client
No matter how WCF service is hosted, to consume the service, the consumer needs to have a proxy class to access the functions exposed by the service. In addition, we need to configure client side with the right endpoint settings, which includes address, binding and contract information.

There are three ways for creating the proxy. First, use the commandline tool svcutil, which is coming with WCF. The following shows how to use it.

svcutil http://localhost:8000/Derivatives/ /out:Client.cs /config:app.config

Note, svcutil doesn't check the address, it just use the parameter to generate the proxy. So developer needs to make sure the address information is correct.

Once executed, this command
will generate the proxy class (Client.cs) and configuration entries (in app.config). Of course we can change the names of the proxy class and the config file.


The second way is to write the proxy class manually. See snippet bellow.

public partial class DerivativesCalculatorProxy :
ClientBase, IDerivativesCalculator
{
public decimal CalculateDerivative(string[] symbols,
decimal[] parameters,
string[] functions)
{
return base.InnerProxy.CalculateDerivative(symbols,
parameters,
functions);
}
}

Obviously, the proxy class is nothing but a class derives from ClientBase, and implements the service contract interface. In the body of interface implementation, It just passes the call to base class's InnerProxy.

There is still another way to create a client. Instead of creating a proxy class, it directly creates a proxy instance with ChannelFactory class. To consume the service, just make request to the proxy instance. Bellow shows how it is like.

IDerivativesCalculator proxy =
new ChannelFactory(“EndpointName”).
CreateChannel();

.svc extention
.Net descriminates different type of request by file extentions. For example, requesting a .asmx file is recognized as a web service request. However this mapping between file extention and handler class can be customized.


This feature brings benefits in the circumstance that we need to switch a web service to WCF service, for example, what we need to do is just change the mapped handler to WCF service handler for .asmx file extention.

In the .Net installation folder, Config subfolder, there is a web.config file, that is where the mapping is stored. The following snippet shows an adoption of the full mapping list.

<buildproviders>
<add type="System.Web.Compilation.PageBuildProvider" extension=".aspx">
<add type="System.Web.Compilation.UserControlBuildProvider" extension=".ascx">
<add type="System.Web.Compilation.MasterPageBuildProvider" extension=".master">
<add type="System.Web.Compilation.WebServiceBuildProvider" extension=".asmx">
<add type="System.Web.Compilation.ForceCopyBuildProvider" extension=".js">
<add type="System.ServiceModel.Activation.ServiceBuildProvider, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" extension=".svc">
</buildproviders>

In addition to builderProviders, there is an expressionBuilder section, see bellow,

<expressionbuilders>
<add type="System.Web.Compilation.ResourceExpressionBuilder" expressionprefix="Resources">
<add type="System.Web.Compilation.ConnectionStringsExpressionBuilder" expressionprefix="ConnectionStrings">
<add type="System.Web.Compilation.AppSettingsExpressionBuilder" expressionprefix="AppSettings">
</expressionbuilders>

It helps to understand that a lot of .Net features are actually customizable, which is great.

Monday, December 24, 2007

Module, Multifile Assembly

Module is a concept of component that composes an assembly.
it has a file name extention of "netmodule".

Generate a module:

csc /t:module Stringer.cs

/t: indicates the compiler to generate a module rather than an assembly. Stringer.netmodule is produced. A module can be added to an assembly.

Create references between modules

the following line creates a module with reference to another module:

csc /addmodule:Stringer.netmodule /t:module Client.cs


Create multifile assembly

The following line create a two file assmbly:

csc /out:Client.exe Client.cs /out:Stringer.netmodule Stringer.cs

In addition to modules, an assembly has manifest information (meta data).

Assembly Linker (al.exe) is used to create a assembly from a collection of modules
al Client.netmodule, Stringer.netmodule /main:TheClassName.Main /out:MyAssembly.exe /target:exe

Aside from "exe", the target can be "win" and "lib"

MSIL Disassembler
.Net tool ildasm.exe (MSIL Disassembler) can examine the content and recognize a module or an assembly.


Reflecting module info with reflection code
(source:
http://msdn2.microsoft.com/en-us/library/system.reflection.module.aspx)

using System.Reflection;
using System;
public class Program {

public static void Main() {
Class1 c1 = new Class1();
// Show the current module.
Module m = c1.GetType().Module;
Console.WriteLine("The current module is {0}.", m.Name);

// List all modules in the assembly.
Assembly curAssembly = Assembly.GetExecutingAssembly();
Console.WriteLine("The current executing assembly is {0}.", curAssembly);

Module[] mods = curAssembly.GetModules();
foreach (Module md in mods) {
Console.WriteLine("This assembly contains the {0} module", md.Name);
}
Console.ReadLine();
}
}
class Class1 {
}

Wednesday, December 19, 2007

Link Blogs

There are so many smart guys out there, why not link their blogs and get some experience from them


http://davidhayden.com/blog/dave/archive/2006/02/15/2802.aspx

Tuesday, December 18, 2007

Development with XAML

There is a lot of buzz around the word "XAML" since Microsoft
release WPF.
Microsoft's goal is to provide a platform to integrate Window
Application UI with Web Application UI development.
To let developers start with Xaml, Microsoft provides a tool called
XAMLPad. XAMLPad is a WYSWYG editor. the following link is an
artical demonstrating how to work with it:

To get XAMLPad, you need to download the SDK(Windows Software
Development Kit for Windows Vista and .Net FrameWork 3.0 Runtime
Components), following is the link:
http://www.microsoft.com/downloads/details.aspx?familyid=7614FE22-
8A64-4DFB-AA0C-DB53035F40A0&displaylang=en

The following links will get you started with XAMLPad:
http://www.code-magazine.com/articleprint.aspx?
quickid=0601091&printmode=true
http://msdn2.microsoft.com/en-us/library/ms742398(VS.90).aspx

Friday, December 14, 2007

The "connection reset" problem

The Symptom:

I encountered a problem of "the connection between IE and the server was reset." The application couldn't download a file of dynamically generated data(without saving it the the disk) after about 20 seconds delay when user needs to locate a folder to save the file. It works fine if user saves the file immediately.


Similar Symptom:
"I am trying to download a file. When the file starts running I am getting the
following message:
IE unable to continue...The connection with the server was reset."
"I have seen this problem before and fixed it by reducing the RWin setting. This
means delving into the registry or getting a tweak utility to do it. Exactly how to
proceed depends on your OS."

Definition of RWIN:

(Receive WINdow) A TCP/IP setting that defines the size of the buffer that holds
incoming packets. In Windows, RWIN is set in the Registry.

Steps to modify RWIN with Window XP

I've found that Windows XP is largely self-tuning. Currently I'm running XP Pro and I get 600K download speeds box stock. So you might not wish to modify the RWIN size if your speed is acceptable.
However, If you do want to change your RWIN setting, I have found that the best starting modification to make is to add an entry in the registry that creates a receive window size of 64240.
To install this modification, Right-Click on this file WindowsNT2000XP-64240 RWIN.reg and select 'Open'.
Select 'Open' again and you will be asked if your are sure you want to install this information in the registry. Select 'Yes' and than re-boot your system at your convenience.
This file adds the TcpWindowSize entry to the registry and sets a value of 64240. It also adds the Tcp1323Opts entry and sets it to 0. Neither of these entries exist in the unmodified operating system.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\TcpWindowSize\64240
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\Tcpip\Parameters\Tcp1323Opts=0 To return your Windows XP computer back to the original settings Save This File to your desktop and than right-click on it and select install. This will remove both of the entries and it will be as if you never changed it - once you've re-booted your machine.
More on this:http://www.asksomeone.net/winxp.html

Enterprise Library Contrib

Enterprise Library

EntLib Contrib is just the newest release (released in September 2007) .
http://www.codeplex.com/entlib

The idea of Enterprise Library is to build reusable software blocks
to make .Net application more consistent, robust and to simplify
the development.

EntLib is built on top of .Net Framework. It is composed of a number
of blocks. Some blocks are depreciated in faver of the functionality of new .Net Framework version. The Security block, for example, is
depreciated in favor of the Membership in .Net 2.0.


The blocks include:

  • Caching
  • Data Access (now called Repositary Factory)
  • Logging
  • Exception Handling
  • Cryptography
These blocks are built on top the following three core components:



  • Config Helpers Design
  • Object Builder
  • Instrumentation
Videos
Tom Hollander' blog provided three videos about Enterprise
Libraryhttp://blogs.msdn.com/tomholl/archive/2007/04/10/enterprise-library-the-videos.aspx

Introduction of Repository Factory

As part of Patterns and Practices, Repository Factory is a new
version of Data Access Guidance Factory. It was part of the Web
Service Factory and the team makes it a seperate package so that
it can be used generally.

Repository Factory is a package that automates the coding to map
database repository to entity classes. It is designated to
automate the domain model which most applications have.
However, Reporsitory Factory is not intended to be a full-
fledged ORM solution, but rather a light weight code generator
for most hand-coding effort in building domain model objects
and persist them to a database.
The following links to Microsoft Repository Factory Demo - MSN
Videohttp://video.msn.com/video.aspx/?mkt=en-us&vid=61ed607a-fd42-
48cb-bf8f-14cbf921a26f&wa=wsignin1.0

Exception HandlingA "Exception Policy" maps a type of exception to an action.
e.g.Type ApplicationException should be loggedSqlClientException should be caught and wrapped into
DataLayerException and rethrownSecurityException should be replaced with AccessDeniedException
and re-thrown

The actions inlude:LoggingWrappingReplacingand other custom actions
the code is like:
try{
// some code}catch(Exception ex){if(ExceptionPolicy.HandleException(ex, "DataLayer")){throw;} }

Thursday, December 13, 2007

Using design patterns in .Net coding

Using patterns deliberately in coding is always a good practise and an important skill, no matter what language you use. That is because the nature of pattern concept and idea. Patterns are designated to solve common problems and proved effective in solving different kind of problems without tieing with a specific language, instead it is more related with a problem of conceptual circumstance.

Learning Tree International is a leading educator for technology and management professionals. From the following page, I can follow their footsteps to sniff what's new and what's important in practice

http://www.learningtree.com/courses/511.htm

Friday, December 7, 2007

Getting started using WPF

Provided by MSDN, this walkthrough-style tutorial shows the integration of core elements of WPF: controls, layout, databinding and style. no hesitation, come on start now!

http://msdn2.microsoft.com/en-us/library/ms752299.aspx

Dependency Properties Overview
http://msdn2.microsoft.com/en-us/library/ms752914.aspx

Thursday, December 6, 2007

MCF Links

WCF at MSDN
WCF Articals

WCF Community

Service Software Factory - MS Patterns and Practices
Resources for constructing WCF and web service applictions in a quick and consistent manner with adhering to well known architecture and design patterns
http://www.codeplex.com/servicefactory

Design Pattern in c# - Gang of Four
Design patterns are useful guides about real world software design problems that are countered again and again. It is really about objects and their interactions.
Gang of Four design patterns are generally considered to be the foundation of other design patterns. It has 23 patterns in three categories
http://www.dofactory.com/Patterns/Patterns.aspx

Wednesday, November 28, 2007

Blog Field

I really want to write something, for myself and friends. Blog is a great way to share information and keep ideas. Better yet, it help comb my thought about .Net technology. Anyway, I hope this blog become a piece of field where crops yield in the autumn.