May 2008 - Posts
ASP.NET Client Side State Management - Cookies
In this post I'm going to explain what are cookies and how to use
them as a part of the ASP.NET client side state management.
You can read my previous posts in the state management subject in
the following links:
What are Cookies?
A cookie is a piece of data that is saved in the client web browser.
The cookie is saved either in the memory of the web browser or as a
text file in the file system of the client.
Cookies are used to identify a user, to store state information, preferences
of the user and etc. The ASP.NET use the cookies mechanism to track users
session.
How Does Cookies Mechanism Work?
The mechanism of cookies is simple. When a client request a web page
from a server the first request isn't containing a cookie. The server identify that
the client has no cookie and generate one. Then the server sends the cookie to
the client and from now on the client will send the cookie in every request and the
server will send the cookie in every response.
Cookies Limitations
- Most browsers support cookies of up to 4096 bytes. This limitation makes the
cookies a way to store only small amount of data.
- Browsers have a limit on the amount of cookies a web site can save in the client.
Most browsers allow only 20 cookies per site.
- The user can set the browser to disable cookies and therefore you can't
trust cookies and you always have to check if the browser enables cookies.
A rule of thumb - do not use cookies for critical information.
How To Use Cookies?
Cookies are sent in the HTTP header of the response. To create a
cookie
you need to use the
Response.Cookies property. To read a
cookie value
from the client use the
Request.Cookies property.
The following example
shows how to read a
cookie named "
cookie" and how to write the
cookie:
// it can be different from null only is
// a request was made before
if (Request.Cookies["cookie"] != null)
{
// get the cookie
HttpCookie cookie = Request.Cookies["cookie"];
// get the cookie value
string value = Server.HtmlEncode(cookie.Value);
}
// write the cookie to the response
Response.Cookies["cookie"].Value = "value";
In the
HttpCookie class there is a Expires property. If you don't use it
(like in the example) the
cookie is saved in memory and discarded if the
user closes the browser. If you use the property you must define the amount
of time the
cookie is saved. In order to delete a saved
cookie you need to
use the Expires property and pass a past expiration date. There is no way
to delete a
cookie otherwise.
In the previous example the
cookie saves a single value.
The
cookie can save multiple values like I show in the next example.
Response.Cookies["cookie"]["key1"].Value = "value1";
Response.Cookies["cookie"]["key2"].Value = "value2";
Response.Cookies["cookie"]["key3"].Value = "value3";
Determine If a Browser Accepts Cookies
The clients can disable cookies.
One way to check if cookies are disabled is to write a cookie to the
Response and in the next Request to check if the cookie exists.
If the cookie doesn't exists you need to assume that cookies are disabled.
Summary
To sum up the post, I explained what are cookies and how you can use
them to save state. The cookies technique is one of the backbones of the
ASP.NET session state which will be covered in a later post.
The last client side state management technique - the control state - will be
explained in the next post of this series.
Strategy Pattern
Today I present the strategy pattern.
You can read my previous posts about design patterns here:
Structural patterns
Decorator pattern
Proxy pattern
Facade pattern
Adapter pattern
Composite pattern
Bridge pattern
Flyweight pattern
Creational patterns
Singleton pattern
Abstract Factory pattern
Prototype pattern
Factory Method pattern
Builder pattern
Strategy Pattern Introduction
The strategy pattern is one of my favorite patterns.
For every problem in development there are many solutions. There are times
that one solution is preferable then another. But sometimes the other algorithm is
preferable. The strategy pattern helps us to divide an algorithm from a host class
and then move it to another class. By doing so the client can choose which
algorithm will be performed in runtime from a set of algorithms that were
implemented earlier.
Use Cases for the Strategy Pattern
Use the strategy pattern in the following situations:
- There are many classes that differ only in their behavior.
- There are different algorithms that solve a problem and you
want to give the client a way to choose between them.
- The client has no real influence on the algorithms which makes them
a black box.
UML Diagram
Example in C#
The following code will explain how to use the strategy pattern:
#region Strategy
interface IStrategy
{
int Sum(List<int> list);
}
#endregion
#region Concrete Classes
class ConcreteStrategy1 : IStrategy
{
#region IStrategy Members
/// <summary>
/// Calculate the sum of integers in the
/// given list using LINQ
/// </summary>
/// <param name="list">The given integer list</param>
/// <returns>sum of integers in the list</returns>
public int Sum(List<int> list)
{
return list.Sum();
}
#endregion
}
class ConcreteStrategy2 : IStrategy
{
#region IStrategy Members
/// <summary>
/// Calculate the sum of integers in the
/// given list using standard calculation
/// </summary>
/// <param name="list">The given integer list</param>
/// <returns>sum of integers in the list</returns>
public int Sum(List<int> list)
{
int result = 0;
foreach (int value in list)
{
result += value;
}
return result;
}
#endregion
}
#endregion
#region Context
class Context
{
#region Members
IStrategy _strategy;
#endregion
#region Ctor
/// <summary>
/// Construct a new Context object with
/// the given strategy.
/// </summary>
/// <param name="strategy">The given strategy</param>
public Context(IStrategy strategy)
{
_strategy = strategy;
}
#endregion
#region Methods
public void PerformCalculation(List<int> list)
{
Console.WriteLine(string.Format("The list's sum is {0}",
_strategy.Sum(list)));
}
#endregion
}
#endregion
The example is simple I use an interface to define the wanted strategy.
The algorithm I use calculate the sum of an integer list. I built two concrete
classes. One concrete use LINQ for the calculation and the other use standard
array sum. The Context class gets the strategy in its constructor and use it in the
PerformCalculation method. The Context client is responsible to deliver the
relevant strategy. The example is naive but it shows how to use the pattern.
Summary
The strategy pattern is very useful pattern. I use it a lot when I have to
choose from a set of solutions in runtime. The implementation of the
pattern is simple and the gain from it is high.
The next post will explain in details how to use the iterator pattern.
Enterprise Library And The Authenticode Issue
Two days ago, one of my colleagues came to me with a strange
problem. It seems like one of our production web services has a very
not reasonable startup time (about 20 seconds). Together we tried to
figure out what has changed in the web service. The answer came quickly -
we replaced the data access of the web service to enterprise library data
access application block. After researching the subject we discovered that
the problem is a known Authenticode issue which has a hotfix.
What is Authenticode?
"Authenticode identifies the publisher of signed software and verifies that it
hasn't been tampered with, before users download software to their PCs.
As a result, end users can make a more informed decision as to whether or not
to download code" - taken from Microsoft technet.
For further reading about Authenticode go to this technet link.
The Problem
Enterprise library assemblies are signed with Authenticode.
Because of the Authenticode signature the assemblies try to verify the
Authenticode in every startup of the program. That means they need to
open a connection to the web in order to do the verification.
Environments which aren't opened to the web (like in my case) will suffer
from the verification wait until a timeout will occur.
The Hotfix
The hotfix that Microsoft provided to handle the problem was to add
generatePublisherEvidence configuration setting which by default is
enabled and you can change it to disabled. Disabling the setting will not
verify the Authnticode any more and should be done with a lot of care.
You do it by adding the next code to the <ApplicationName>.exe.config
file:
<configuration>
<runtime>
<generatePublisherEvidence enabled="false"/>
</runtime>
</configuration>
This will do the job but not for web applications. As you can notice
the problem is fixed only for <ApplicationName>.exe.config and not
for web.config.
Solution
We needed a way to solve the loading problem in our web service which
is hosted in a server with no access to the web. We compiled the
source code of enterprise library with our strong name and used the
generated assemblies for the web service. That didn't solved our problem.
The reason was the ObjectBuilder assembly which isn't included in the
enterprise library source code and therefore couldn't be compiled with
the other assemblies (one assembly is enough to perform the Authenticode
check). The next thing to do was to look for the ObjectBuilder source
in the internet. The source of the ObjectBuilder can be fount in CodePlex.
All the sources were compiled with our strong name and that solved the
problem. Another solution that we checked was to migrate to
enterprise library 4.0. The enterprise library 4.0 like its previous
versions is compiled with Authenticode and therefore the same solution of
compiling the assembly sources is relevant to solve the problem in this case
as well.
Summary
As a result of what happened I wish that when the next version of enterprise
library will be released (the Authenticode problem occurs in
enterprise library 4.0 release as well) the P&P team will not use the
Authenticode signature in the assemblies.
I hope this post will help if you encounter this problem.
Behavioral Patterns
Today's discussion is the last group type in the design patterns' world -
the behavioral patterns.
You can read my previous posts about design patterns here:
Structural patterns
Decorator pattern
Proxy pattern
Facade pattern
Adapter pattern
Composite pattern
Bridge pattern
Flyweight pattern
Creational patterns
Singleton pattern
Abstract Factory pattern
Prototype pattern
Factory Method pattern
Builder pattern
Behavioral Patterns
Behavioral patterns describe ways to handle algorithms and ways of
communication between objects. The patterns help to shift the focus from
flow of control to the way objects are interconnected. Behavioral patterns
are divided to two subjects - behavioral class patterns and behavioral object
patterns. The behavioral class patterns use inheritance to implement the
behavior between classes. The behavioral object patterns use object
composition to implement the behavior.
Behavioral Patterns Types
There are eleven behavioral patterns:
- Chain of responsibility - Command objects are handled or passed on to
other objects by logic-containing processing objects.
- Command - Command objects encapsulate an action and its parameters.
- Interpreter - Implement a specialized computer language to rapidly solve a
specific set of problems.
- Iterator - Iterators are used to access the elements of an aggregate object
sequentially without exposing its underlying representation.
- Mediator - Provides a unified interface to a set of interfaces in a subsystem.
- Memento - Provides the ability to restore an object to its previous state (rollback).
- Observer - aka Publish/Subscribe or Event Listener.
Objects register to observe an event which may be raised by another object.
- State - A clean way for an object to partially change its type at runtime.
- Strategy - Algorithms can be selected on the fly.
- Template method - Describes the program skeleton of a program.
- Visitor - A way to separate an algorithm from an object.
A note, all the descriptions for the patterns are taken from Wikipedia.
The template method and the interpreter are behavioral class patterns
and all the other patterns are behavioral object patterns.
Summary
In the next posts I'm going to give a tour in the world of behavioral patterns
starting with the strategy pattern which is one of my favorite patterns.
ASP.NET Client Side State Management - Query Strings
Continuing the tour in the ASP.NET client side state management our
current stop is the query string technique.
You can read my previous posts in the state management subject in
the following links:
What are Query Strings?
Query strings are data that is appended to the end of a page URL.
They are commonly used to hold data like page numbers or search terms
or other data that isn't confidential. Unlike ViewState and hidden fields, the
user can see the values which the query string holds without using special
operations like View Source.
An example of a query string can look like http://www.srl.co.il?a=1;b=2.
Query strings are included in bookmarks and in URLs that you pass in
an e-mail. They are the only way to save a page state when copying
and pasting a URL.
The Query String Structure
As written earlier, query strings are appended to the end of a URL.
First a question mark is appended to the URL's end and then every
parameter that we want to hold in the query string. The parameters
declare the parameter name followed by = symbol which followed by the
data to hold. Every parameter is separated with the ampersand symbol.
You should always use the HttpUtility.UrlEncode method on the data
itself before appending it.
Query String Limitations
You can use query string technique when passing from one page to
another but that is all. If the first page need to pass non secure data to
the other page it can build a URL with a query string and then redirect.
You should always keep in mind that a query string isn't secure and
therefore always validate the data you received.
There are a few browser limitation when using query strings.
For example, there are browsers that impose a length limitation
on the query string. Another limitation is that query strings are passed
only in HTTP GET command.
How To Use Query Strings
When you need to use a query string data you do it in the following way:
string queryStringData = Request.QueryString["data"];
In the example I extract a data query string. The structure of the
URL can look like url?data=somthing. After getting to data parameter
value you should validate it in order not to enable security breaches.
The next example is a code to help inject a query string into a URL:
public string BuildQueryString(string url, NameValueCollection parameters)
{
StringBuilder sb = new StringBuilder(url);
sb.Append("?");
IEnumerator enumerator = parameters.GetEnumerator();
while (enumerator.MoveNext())
{
// get the current query parameter
string key = enumerator.Current.ToString();
// insert the parameter into the url
sb.Append(string.Format("{0}={1}&", key,
HttpUtility.UrlEncode(parameters[key])));
}
// remove the last ampersand
sb.Remove(sb.Length - 1, 1);
return sb.ToString();
}
Summary
To sum up the post,
query string is another
ASP.NET client side state
management technique. It is most helpful for page number state or
search terms. The technique isn't secured so avoid using it with confidential
data. In the next post in this series I'll explain the how to use cookies.
Builder Pattern
Today I'm going to discuss the last creational pattern - the builder pattern.
You can read my previous posts about design patterns here:
Structural patterns
Decorator pattern
Proxy pattern
Facade pattern
Adapter pattern
Composite pattern
Bridge pattern
Flyweight pattern
Creational patterns
Singleton pattern
Abstract Factory pattern
Prototype pattern
Factory Method pattern
What Is The Builder Pattern?
The builder pattern describe a way to separate an object from it's construction.
The same construction method can create different representation of the object.
Use the pattern in the following situations:
- You need to construct a complex object which has different
representation.
- The algorithm for creating the object should be independent of
the way the object's parts is assembled.
For a UML diagram of the pattern go to dofactory site.
C# Example
Lets look at a builder example:
#region Director
/// <summary>
/// The contractor is responsible for the
/// house build.
/// </summary>
class Contractor
{
#region Methods
/// <summary>
/// Construct a new house with the given
/// house builder
/// </summary>
/// <param name="house"></param>
public void Construct(HouseBuilder houseBuilder)
{
houseBuilder.BuildFloor();
houseBuilder.BuildWalls();
houseBuilder.BuildDoors();
houseBuilder.BuildWindows();
}
#endregion
}
#endregion
#region Builder
abstract class HouseBuilder
{
#region Members
protected House _house;
#endregion
#region Properties
public House House
{
get
{
return _house;
}
}
#endregion
#region Build Methods
public abstract void BuildDoors();
public abstract void BuildWindows();
public abstract void BuildWalls();
public abstract void BuildFloor();
#endregion
}
#endregion
#region Builder Product
class HousePart
{
#region Members
private string _strPartName;
#endregion
#region Properties
/// <summary>
/// The part name
/// </summary>
public string PartName
{
get
{
return _strPartName;
}
}
#endregion
#region Ctor
/// <summary>
/// Construct a new house part with the given
/// name.
/// </summary>
/// <param name="name">The given name</param>
public HousePart(string name)
{
_strPartName = name;
}
#endregion
}
class House
{
#region Members
private string _material;
private List<HousePart> _houseParts;
#endregion
#region Property
/// <summary>
/// The building material
/// </summary>
public string Material
{
get
{
return _material;
}
}
#endregion
#region Ctor
/// <summary>
/// Construct a new house with the given
/// material
/// </summary>
/// <param name="material">The given material</param>
public House(string material)
{
_material = material;
_houseParts = new List<HousePart>();
}
#endregion
#region Methods
/// <summary>
/// Adds a part of the house to the house
/// </summary>
/// <param name="part">The part to add</param>
public void AddPart(HousePart part)
{
_houseParts.Add(part);
}
#endregion
}
#endregion
#region Builder Concretes
class GlassHouseBuilder : HouseBuilder
{
#region Methods
public override void BuildFloor()
{
_house = new House("glass");
House.AddPart(new HousePart("stone floor"));
}
public override void BuildWalls()
{
House.AddPart(new HousePart(House.Material +
" walls"));
}
public override void BuildDoors()
{
House.AddPart(new HousePart("wood doors"));
}
public override void BuildWindows()
{
House.AddPart(new HousePart(House.Material +
" windows"));
}
#endregion
}
class WoodHouseBuilder : HouseBuilder
{
#region Methods
public override void BuildFloor()
{
_house = new House("wood");
House.AddPart(new HousePart(House.Material +
" floor"));
}
public override void BuildWalls()
{
House.AddPart(new HousePart(House.Material +
" floor"));
}
public override void BuildDoors()
{
House.AddPart(new HousePart("iron doors"));
}
public override void BuildWindows()
{
House.AddPart(new HousePart("glass floor"));
}
#endregion
}
#endregion
The example is easy to understand. When have a house contractor that is
responsible to build the house in the right order. We have a builder
abstract class that defines the interface for the concrete builders.
Each concrete responsible to implement the abstract methods and
therefore build the parts differently.
Summary
To sum up the post, the builder pattern isn't commonly used.
It resemble the abstract factory in some ways but the difference between
the two patterns is that builder is concerned with how the object is built by
different concretes and abstract factory is concerned about what products
are built. As you could see in the example there is a director that organize
the building parts therefore making the algorithm of construction abstract.
In the next post in this series I'm going to describe the third design patterns
family - the behavioral patterns.
How And Why To Use DefiningQuery Element
In the last post in the entity framework series I introduced the
EDM designer. Today I'm going to show how to do things that
the designer isn't able to perform (for the ADO.NET's team notice).
You should be familiar with the EDM XML schema types and the general
elements before you start to read this post. If you didn't read my post about
the subject you can read it in the following link.
DefiningQuery Element Intoroduction
Today's topic will be the DefiningQuery element.
DefiningQuery elements are defined in the SSDL. These elements are created
when you map a database view in the EDM wizard. These mappings are read
only a projection of data and therefore read only like database views.
By now you probably ask yourself why I'm writing about these elements.
The great thing about DefiningQuery elements are that they can help us
create every projection that we like and with the EDM designer we can then
create entities to handle the created view.
So what is great about what I wrote if the element gives us a read only data?
By connecting the created entity of the CSDL to stored procedures you
can add a write functionality to the defined query.
The drawback of this method is that you need to do it manually in the SSDL.
Also, you don't have intellisense while writing the query so I suggest that you
try it first in the database management studio and then move it to the SSDL file.
You should be very careful when you define queries in the SSDL!
DefiningQuery Element Example
In the next example I'll continue using the database and example from my previous
post. The database schema is shown in the next figure:
The current state of the designer is shown in the next figure:
How to define a DefiningQuery element?
First, write the query for the data projection.
The query I'm going to use will select details from two tables - Employees
and Companies.
SELECT e.EmpolyeeID AS EmpolyeeID,
e.EmployeeFirstName AS EmployeeFirstName,
e.EmployeeLastName AS EmployeeLastName,
c.CompanyName AS CompanyName
FROM Employees AS e INNER JOIN Companies AS c ON (e.CompanyID = c.CompanyID)
Open the edmx file with XML editor and look for the SSDL area.
Insert a new EntitySet to the SSDL with the DefiningQuery element.
In the example I inserted a new entity set with the name of
EmployeeWithCompany:
<EntitySet Name="EmployeeWithCompany" EntityType="TestLINQModel.Store.EmployeeWithCompany">
<DefiningQuery>
SELECT e.EmpolyeeID as EmpolyeeID,
e.EmployeeFirstName AS EmployeeFirstName,
e.EmployeeLastName AS EmployeeLastName,
c.CompanyName AS CompanyName
FROM Employees AS e INNER JOIN Companies AS c ON (e.CompanyID = c.CompanyID)
</DefiningQuery>
</EntitySet>
After you inserted the new EntitySet you need to provide a new
entity type which is called in my example EmployeeWithCompany.
You can see that the entity set reference this type.
The entity type should look like:
<EntityType Name="EmployeeWithCompany">
<Key>
<PropertyRef Name="EmpolyeeID" />
</Key>
<Property Name="EmpolyeeID" Type="int" Nullable="false" StoreGeneratedPattern="Identity" />
<Property Name="CompanyName" Type="nvarchar" MaxLength="100" />
<Property Name="EmployeeFirstName" Type="nvarchar" MaxLength="50" />
<Property Name="EmployeeLastName" Type="nvarchar" MaxLength="50" />
</EntityType>
Pay attention to define the property elements exactly as their definition
in the database (type and constraints). It's done manually and therefore
you can have errors.
After these operations the projection of the data is ready to use in the
CSDL. Open the designer and create a new entity with the
EmployeeWithCompany name. Add four properties to the entity to
match the properties of the entity type that was defined in the SSDL.
Your designer surface should look like the next figure:
After the creation of the entity we need to connect it to the created view
and its properties. You do it by selecting the view name in the Tables column
of the Mapping View and by mapping the relevant entity set properties to
the entity properties.
The result:
Build the solution and you are set to use the new read only entity.
What is Next to Come
In the next post I'll show how you can map the entity to stored procedures
to enable insert, update and delete operations and by that to unleash the power
of DefiningQuery element.
Entity Framework Q&A - John Papa's Article
In the new MSDN magazine there is an article in the data points section by
John Papa which answers few of the common questions raised when
developing with the entity framework.
John Papa answers questions like:
- Why use Entity SQL when I can use LINQ to get to entities?
- What is the role of ObjectContext?
- How do explicit and eager loading work in the Entity Framework?
- How do I see the SQL that will execute?
- What can I do with complex types?
- How do I create a complex type?
I found the article very helpful and I recommend it to everyone who wants to
start developing with the entity framework.
The link to the article.
ASP.NET Client Side State Management - Hidden Fields
In the previous posts in this series I introduced the client side state
management and one of its techniques - the ViewState.
Today I'm going to drill down into the hidden fields technique.
As mentioned in the previous post, the ViewState stores its state in a hidden field.
What are Hidden Fields?
Hidden fields technique is widely used in ASP.NET programing.
Hidden fields are html input control with hidden type that store hidden data in
the html. An example for a hidden field can look like this:
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
In the example above, I chose to show the event target hidden
field in order to indicate that even in postback mechanism hidden fields are
being used. The data stored in a hidden field is available when the form is
processed on the server or when we use javascript.
Hidden Fields Values
Hidden fields store only one value in their value property.
The value is saved as a string and therefore in order to use it for other types
you need to perform casting. Hidden fields' data is submitted to the server
only in HTTP post operation. You can see the stored data easily by using the
View Source operation of the browser. You can see it by clicking the right
mouse button and then choosing View Source from the menu (if the operation
is available). Be aware not to use hidden fields to store confidential data!
The values has page context and therefore when you leave a page the data
stored in the hidden fields is disposed.
Server Control Hidden Fields
There are two types of server control hidden fields -
System.Web.UI.WebControls.HiddenField and
System.Web.UI.HtmlControls.HtmlInputHidden.
Both types has the same primary Value property to hold the value of the
hidden field. You should choose between these types whenever you need
to use a server side hidden field (A note - The difference between
HtmlControls and WebControls isn't in the context of this post).
When you don't use server controls you can use the Request.Form
NameValueCollection to get the hidden field value by providing the client
id of the hidden field. For example the code bellow will return the string
value of the __EVENTTARGET hidden field:
string eventTarget = Request.Form["__EVENTTARGET"];
Hidden Fields Example
I got some requests for an example of how to use the hidden fields
inside web forms. The example is very easy to understand.
I have an html input with type hidden. In the first request I fill the
input with a message value with javascript function. I use a button control
to do a post back to the server and in the post back the value of the hidden
field is inserted into a label control. Pay attention that because I use an html
hidden field that isn’t a server control after a second post back it’s value
will be empty. The only reason that the label will still show a message is because
the label’s default value of the EnableViewState is true.
The web page’s code:
<%@ Page="" Language="C#" AutoEventWireup="true" Codebehind="Default.aspx.cs"
Inherits="AJAXEnabledWebApplication1._Default" EnableSessionState="False" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript">
function PutHtmlHiddenFieldValue(message)
{
var hidden = document.getElementById('HTMLHiddenField');
if (hidden != null)
{
hidden.value = message;
}
}
</script>
</head>
<body dir="ltr">
<form id="form1" runat="server">
<div>
<div>
<asp:Label ID="lblHTMLHiddenField" runat="server"></asp:Label>
<input id="HTMLHiddenField" type="hidden"
name="HTMLHiddenField"/>
</div>
<div>
<asp:Button ID="btnForPostBack" runat="server"
Text="Do Postback" />
</div>
</div>
</form>
</body>
</html>
The code behind:
public partial class _Default : System.Web.UI.Page
{
#region Consts
private const string SCRIPT_KEY = "HtmlHiddenFieldScript";
#endregion
#region Page Events
protected void Page_Load(object sender, EventArgs e)
{
// Insert message to the label of the html control hidden
// field if there is a value in the html hidden field
string message = Request.Form["HTMLHiddenField"];
if (!string.IsNullOrEmpty(message))
{
lblHTMLHiddenField.Text = message;
}
}
protected void Page_PreRender(object sender, EventArgs e)
{
// Register a startup script in order to fill the html
// hidden field with a message value
if (!ClientScript.IsClientScriptBlockRegistered("HtmlHiddenFieldScript") &&
!IsPostBack)
{
ClientScript.RegisterStartupScript(typeof(Page),
SCRIPT_KEY,
"PutHtmlHiddenFieldValue('Html hidden hello world');",
true);
}
}
#endregion
}
Summary
To sum up the post, today I drilled down into the hidden fields technique.
This technique is very popular and is used widely in ASP.NET.
In the next post I'll continue the tour in the client side state management
techniques.
It has been two weeks since I started to learn for a new MCTS
certification - exam 070-431: Microsoft SQL Server 2005.
When I told one of my colleagues that I'm going to do another certification
he asked me if I developed an addiction to certifications.
The answer is no. I'm not going to join the anonymous exam addicted group.
I want to improve my knowledge in SQL in order to give better solutions when
needed. As developers we need not only to know how to develop well but also we
need to know the tools we use and how to handle them. Also, almost every
solution in development will use a database in its backbone so it's a must know
issue.
Why I Chose to Check uCertify PrepEngine
In the previous certifications I used the Microsoft MCTS self-paced training kits only.
In the current certification I decided to check the uCertify PrepEngine application.
The reason I decided to check the PrepEngine is because I found that the test engine
that is installed with the self-paced training kits isn't satisfying my needs.
It lacks the ability to save history of the tests I have done and to review them.
Also, it was not adaptive enough for me.
uCertify PrepEngine Review
The PrepEngine has nice features like interactive quiz's or flash cards to help you
remember key subjects. It also comes with a lot of study notes that help to
memorize relevant subjects. Other features include some articles and how to
tutorials which direct you step by step how to do relevant stuff that you need to
know in the certification. The test engine feature do its job and it has an adaptive
tests feature as promised.
I found the PrepEngine helpful but this is a completing product to the self-paced training
kits. You can't pass a certification based only on a test engine. If uCertify could supply a
book or more materials with their product it could be a whole solution to certification
learning. As a last statement, I can say that I passed the previous certifications
on the first attempt only by hard work and my experience. If I could do it you can
do it too with or without the test engines.
Factory Method Pattern
Today, the factory method one of my favorite patterns will be explained.
You can read my previous posts about design patterns here:
Structural patterns
Decorator pattern
Proxy pattern
Facade pattern
Adapter pattern
Composite pattern
Bridge pattern
Flyweight pattern
Creational patterns
Singleton pattern
Abstract Factory pattern
Prototype Pattern
What is Factory Method
Factory method is a way to delegate the instantiation of a class to subclasses.
The subclass decide which concrete class to instantiate according to its state
or by information supplied by the client.
The pattern helps to connect parallel class hierarchies.
Use the pattern in the following situations:
- A client delegate the responsibilities to its subclasses.
- You need flexible way to create objects.
- There are good reasons to choose one subclass over another.
For a UML diagram of the pattern go to dofactory site.
Example in C#
Lets look at an example of factory method:
#region Helper Enum
public enum eMaterialType
{
Wood,
Iron
}
#endregion
#region Products
public abstract class Chair
{
#region Members
private float _nHeight;
private float _nWidth;
#endregion
#region Properties
/// <summary>
/// The table material
/// </summary>
public abstract eMaterialType Material
{
get;
}
/// <summary>
/// The height of the table
/// </summary>
public float Height
{
get
{
return _nHeight;
}
set
{
_nHeight = value;
}
}
/// <summary>
/// The width of the table
/// </summary>
public float Width
{
get
{
return _nWidth;
}
set
{
_nWidth = value;
}
}
#endregion
}
public class WoodChair : Chair
{
#region Properties
/// <summary>
/// The chair material
/// </summary>
public override eMaterialType Material
{
get
{
return eMaterialType.Wood;
}
}
#endregion
}
public class IronChair : Chair
{
#region Properties
/// <summary>
/// The chair material
/// </summary>
public override eMaterialType Material
{
get
{
return eMaterialType.Iron;
}
}
#endregion
}
#endregion
#region Creator
public class ChairCreator
{
#region Methods
/// <summary>
/// The factory method to create the
/// chairs
/// </summary>
/// <param name="type">The material type</param>
/// <returns>A chair object</returns>
public Chair CreateChair(eMaterialType type)
{
switch (type)
{
case eMaterialType.Iron:
{
return new IronChair();
}
case eMaterialType.Wood:
{
return new WoodChair();
}
default:
{
return null;
}
}
}
#endregion
}
#endregion
As you can see the example is similar to the example I gave in the
abstract factory post. This time I have built a chair product and the factory
method is responsible to build the relevant chair. The chairs are build
by the given state type. The ChairCreator could be a subclass of a Creator
abstract class that delegate a Create method but I chose to make a simpler
example.
Summary
To sum up the post, the factory method is simple to implement. The pattern is very
popular. Probably you used it a lot while developing and didn't even know.
I use the pattern in a lot of situations that I need the concrete classes to be chosen
by a creator class which handle their creation.
In the next post in this series I'm going to write about the last creational
pattern - the builder pattern.
Prototype Pattern
It has been a while since I wrote about design patterns.
In the current post I'm going to explain the prototype pattern.
You can read my previous posts about design patterns here:
Structural patterns
Decorator pattern
Proxy pattern
Facade pattern
Adapter pattern
Composite pattern
Bridge pattern
Flyweight pattern
Creational patterns
Singleton pattern
Abstract Factory pattern
What is Prototype Pattern?
The prototype is built upon the use of object cloning. The prototype creates new
objects by cloning one of its concrete classes. The prototype is used in the
following situations:
- You need to hide the concrete product classes from the client.
- You want to reduce the number of classes to minimum.
- When you use dynamic loading.
- When you want to avoid using the complicated class hierarchy
of factories.
- When your class has a small amount of different state combinations.
The prototype pattern can help to speed up instantiation of objects because
copying objects is faster than constructing objects.
For a UML diagram of the pattern go to dofactory site.
Example in C#
Lets look at an example of prototype usage:
#region The Prototype
public abstract class Prototype<T>
{
#region Methods
public T Clone()
{
// create a shallow copy of the object
return (T)this.MemberwiseClone();
}
#endregion
}
#endregion
#region Prototype Concrete
public class ConcretePrototype :
Prototype<ConcretePrototype>
{
#region Members
private string _strName;
#endregion
#region Properties
/// <summary>
/// The name of the prototype
/// </summary>
public string Name
{
get
{
return _strName;
}
}
#endregion
#region Ctor
/// <summary>
/// Construct a new ConcretePrototype with the
/// given name.
/// </summary>
/// <param name="name">The given name</param>
public ConcretePrototype(string name)
{
_strName = name;
}
#endregion
}
#endregion
In the example I created a Prototype class which use the MemberwiseClone method
as the cloning implementation. You should remember that MemberwiseClone
makes a shallow copy of the object (copies object members). If you want a deep
copy you should implement it by yourself. The ConcretePrototype only adds
properties to the Prototype class.
Building Prototype Manager
You could build a manager to help you hold and handle the prototype concretes but
the manager isn't part of the pattern. An example of such a manager can look like:
#region Prototype Manager
/// <summary>
/// The manager isn't part of the design pattern
/// you can use it to manage concretes as a helper
/// class
/// </summary>
public class PrototypeManager
{
#region Members
private Dictionary<string, ConcretePrototype> concretes =
new Dictionary<string, ConcretePrototype>();
#endregion
#region Properties
/// <summary>
/// Indexer for the concretes which are hold
/// in the PrototypeManager
/// </summary>
public ConcretePrototype this[string name]
{
get
{
return concretes[name];
}
set
{
concretes.Add(name, value);
}
}
#endregion
}
#endregion
Summary
To sum up the post, the prototype pattern uses clone methods to make
application independent of how its products are created, composed
and represented. Prototype is easy to implement in C# because of the
MemberwiseClone method.
A note, the prototype and the abstract factory patterns are competing patterns.
Knowing how to implement design patterns helps to understand the trade off
of using each pattern and to choose the right pattern to use.
The factory method will be the next pattern in the series.
ASP.NET Client Side State Management - ViewState
What is ViewState?
The ASP.NET ViewState is a client side state management technique which
enables web pages to persist their state during postbacks.
In the life cycle of a page, the current state of the page is hashed to a string and is
saved into a hidden field. When opening a page with the View Source operation
you can find the ViewState's hidden field by searching __VIEWSTATE keyword.
An example of a ViewState on a web page can look like that:
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"
value="/wEPDwUBMA9kFgJmD2QWAgIDD2QWBgI" />
How ViewState Works?
To understand how ViewState works you need to understand the concept of
page life cycle. Every time a page is requested it is going through the same
phases of the page life cycle. You can take a look at the events of the page life
cycle in the following figure that is taken from a MSDN article
of Scott Mitchell - Understanding ASP.NET View State:
The two phases which are connected to the ViewState are called LoadViewState
and SaveViewState. In the LoadViewState (occurs only after postbacks) all the
data is retrieved from the ViewState hidden field and the hashed value is converted
back to values that are populated into the control hierarchy of the page.
In the SaveViewState the state that must be maintained during postbacks is collected
from the page's controls by calling SaveViewState of each control. Then, the values
are combined into a string that is being hashed and the result is stored in the
ViewState hidden field.
EnableViewState Property
ViewState is enabled for every control by default. You can disable the ViewState
of a control by putting false value in the EnableViewState property of the control.
This action decrease your page size and also reduce the process time on the server
side. Pay attention that if you need to save your state and you disable ViewState
it is your responsibility to save the state somehow.
When to Disable ViewState?
When you have a read only controls. Also, when you have controls like GridView
that use a lot of records. The drawback is that you will have to bind your controls
in every postback. The gain is a smaller page, less bandwidth usage by your page
and less process time of the server.
Page ViewState Property
ViewState is not only found on controls it's also a property of the Page class.
You can use it to store custom ViewState data. When you have a small value
(can be every serialized object) and you need to track it in every postback, you
can use the ViewState. This is a temporary storage because when the user leaves
the page the ViewState of the page is disposed and a new ViewState is built for
the new page.
How to Use ViewState?
The next example will answer the question.
Be aware! always check first if the ViewState object exists before making a cast.
#region Consts
private const string AGE = "Age";
#endregion
#region Properties
/// <summary>
/// The Property returns an age if the age
/// doesn't exists it returns -1.
/// </summary>
public int Age
{
get
{
if (ViewState[AGE] == null)
{
ViewState[AGE] = -1;
}
return (int)ViewState[AGE];
}
set
{
ViewState[AGE] = value;
}
}
#endregion
In the example I have an Age property that I want to save in the ViewState.
In the get operation I Check if the ViewState contains a value for age and if not
I put a -1 to indicate that there is no age currently.
After the check I'll always have a value for age in the ViewState (because I put
-1 as default value) and therefore I return the value with a cast.
The set operation is simple just put the value in the ViewState.
Summary
Lets sum up the post.
Today I explained the first technique for client side state management - the ViewState.
The technique is commonly used but you should be familiar with the aspects of over
using the technique and the drawbacks of the technique (page size, consume server
process time and so on). In the next post I'll continue to explain the client side state
management.
For further reading about ViewState I recommend the article of Scott Mitchell.
ASP.NET Client Side State Management
In the previous post about state management I wrote that there are two types
of state management - server side and client side. In this post I'm going to introduce
the client side state management and explain when to choose client side or server
side state management.
Client Side State Management Techniques
Client side state management include the following techniques:
- ViewState - ASP.NET track the state of the controls on the pages through
the ViewState. Also, ViewState is used to store small custom values.
Don't hold big custom data object because it will affect the performance of
your web page.
- Hidden fields - hidden fields are html input control with a type of hidden -
<input type="hidden">. They are used to store data in the html without presenting
the data in the browser. The data of hidden field is available when the form is
processed or when using javascript. The ViewState use hidden field to save its
data. You can use the View Source operation (if enabled) to scan the web page's
source and to look for hidden fields.
- Query strings - query string state is stored in the URL that is sent to the browser.
Unlike ViewState and hidden fields, the user can see the values without using
special operations like View Source. The parameters are passed in the URL
separated by the & symbol.
For example, in the following URL the query string is built out of two data
parameters, a and b, which hold the values 1 and 2 - http://www.srl.co.il?a=1;b=2.
- Cookies - the cookies store their values in the user's browser and the browser
send them back to the server every time a request is performed.
Cookies are maintained during the session of a user in the web site and therefore
can be used in multiple web pages of the site.
- Control state - when building custom controls you should use the control state
to save your state if EnableViewState property is set to false.
This is the only reason to use this technique.
How do you know when to choose the client side or server side state management?
When to Choose Client Side State Management
Choose client side for better scalability and support multiple servers.
The client side helps to get better scalability by storing state data in the user's
browser instead of using the web server's memory.
The client side support multiple servers because all the state is located in the browser.
This way when you are redirected to another server you don't need to worry
about your state.
The thing I wrote doesn't means that you can't use server side state management
for the supporting of multiple server. To enable server side state management to be able
to support multiple servers you'll have to use centralized state management
(state server or store state in database) or you'll have to use techniques like sticky
connection for load balancing.
When to Choose Server Side State Management
Choose server side for better security and to reduce bandwidth and web page's size.
Server side state management is more secure. The state is saved on the server
and therefore isn't delivered to the client.
Confidential state data shouldn't be used with client side state management.
Server side reduce the traffic to and from the client because data isn't sent to the browser
and it's saved on the server. You should always remember that using client side state
management sends data to the user's browser and that data is sent back to the server
every time. This situation increases bandwidth usage and therefore your application will be
less responsive and you'll suffer from performance issues.
In the next post I'll drill down into the client side techniques and explain how to use them.
ASP.NET State Management
Introduction to the Post Series
ASP.NET state management is one of the most important mechanisms in the
arsenal of web application developers.
Even though, State management is sometimes underestimated.
When I tutor about ASP.NET I always talk a lot about how to implement
state management. A lot of performance issues or page life cycle issues
are caused by a poorly implemented state management.
One thing to remember, the web environment is stateless. Maintaining state
for users or controls is a must. The way to do it has many faces and in the following
posts I'm going to write about the subject.
What is State Management?
The web as maintained earlier is stateless. Every web application needs to
track its users who visit them. There are a lot of reasons to do this.
For example, in my blog I use FeedBurner to get statistics about pages that
my users visit or from where did they come to my blog. The statistics help me to
understand the things that my users like or dislike.
The FeedBurner application uses the state management mechanism to track the
things that my users are doing in my blog for reporting purpose.
ASP.NET State Mangement Types
ASP.NET provides two types of state management - client and server.
Every type has its techniques to handle state.
The client side techniques are ViewState, control state, hidden fields,
cookies and query string.
The server side techniques are application state and session state.
What is Coming Next
In the next post I'll explain the client side state management in more details.
Meanwhile, good luck to Maccabi Tel Aviv in the European basketball final four.
More Posts
Next page »