August 2008 - Posts
How To Perform CRUD Operations in ADO.NET Data Services With Custom Provider
After we learned how to consume an
ADO.NET data service with a .Net
client in the previous post, the next
thing to learn is how to do CRUD
(Create, Update and Delete) operations
with the client we built. This post will
explain how to use these operations.
The IUpdatable Interface
In order to enable a a custom provider to do CRUD operations the data
context object need to implement the IUpdatable interface. That interface can be
found in the System.Data.Services namespace. The interface include a variety of
methods to implement and in the example I will show only a couple of those methods.
Returning to the example of the last post, I changed a bit the CoursesDataContext
to implement the IUpdatable interface and also to hold a static Course list which will
be the object that the data service will use.
The Data Context Example
public class CoursesDataContext : IUpdatable
{
#region Members
private static List<Course> _courses;
#endregion
#region Properties
/// <summary>
/// Return the courses in a IQueryable format
/// </summary>
public IQueryable<Course> Courses
{
get
{
return _courses.AsQueryable();
}
}
#endregion
#region Ctor
/// <summary>
/// Construct a new CoursesDataContext object
/// </summary>
static CoursesDataContext()
{
_courses = Course.GetCourses();
}
#endregion
#region IUpdatable Members
public object CreateResource(string containerName,
string fullTypeName)
{
// create the object using reflection
var objType = Type.GetType(fullTypeName);
var resourceToAdd = Activator.CreateInstance(objType);
// add the course to the courses in-memory list
_courses.Add((Course)resourceToAdd);
return resourceToAdd;
}
public void DeleteResource(object targetResource)
{
// remove the course form the courses list
_courses.Remove((Course)targetResource);
}
public object GetResource(IQueryable query, string fullTypeName)
{
object result = null;
var enumerator = query.GetEnumerator();
while (enumerator.MoveNext())
{
if (enumerator.Current != null)
{
result = enumerator.Current;
break;
}
}
if (fullTypeName != null &&
!fullTypeName.Equals(result.GetType().FullName))
{
throw new DataServiceException();
}
return result;
}
public object GetValue(object targetResource, string propertyName)
{
// get the property info using reflection
var targetType = targetResource.GetType();
var targetProperty = targetType.GetProperty(propertyName);
// retrun the value of the property
return targetProperty.GetValue(targetResource, null);
}
public void SetValue(object targetResource,
string propertyName, object propertyValue)
{
// get the property info using reflection
Type targetType = targetResource.GetType();
PropertyInfo property = targetType.GetProperty(propertyName);
// set the property value
property.SetValue(targetResource, propertyValue, null);
}
public object ResolveResource(object resource)
{
// nothing to do just return the resource
return resource;
}
public void SaveChanges()
{
// object in memory - do nothing
}
public void SetReference(object targetResource,
string propertyName, object propertyValue)
{
throw new NotImplementedException();
}
public object ResetResource(object resource)
{
throw new NotImplementedException();
}
public void ClearChanges()
{
throw new NotImplementedException();
}
public void AddReferenceToCollection(object targetResource,
string propertyName, object resourceToBeAdded)
{
throw new NotImplementedException();
}
public void RemoveReferenceFromCollection(object targetResource,
string propertyName, object resourceToBeRemoved)
{
throw new NotImplementedException();
}
#endregion
}
I didn’t implemented the following methods – RemoveReferenceFromCollection,
AddReferenceToCollection, ClearChanges, ResetResource and SetReference.
The reason is that in my example I don’t use them.
The Calling Method Example
class Program
{
static void Main(string[] args)
{
// build the proxy
var proxy = new CoursesDataContext(
new Uri("http://localhost:4205/CoursesService.svc/"));
proxy.MergeOption = MergeOption.AppendOnly;
var CGCourse = new Course
{
CourseID = 4,
Creadit = 5,
Days = 3,
Title = "Computer Graphics"
};
proxy.AddToCourses(CGCourse);
proxy.SaveChanges();
PrintCoursesToConsule(proxy);
CGCourse.Creadit = 3;
proxy.UpdateObject(CGCourse);
proxy.SaveChanges();
PrintCoursesToConsule(proxy);
proxy.DeleteObject(CGCourse);
proxy.SaveChanges();
PrintCoursesToConsule(proxy);
Console.Read();
}
private static void PrintCoursesToConsule(CoursesDataContext proxy)
{
var courses = from course in proxy.Courses
select course;
foreach (Course course in courses)
{
Console.WriteLine(
"Course name: {0}, Course duration: {1}, Course credit: {2}",
course.Title,
course.Days,
course.Creadit
);
}
Console.WriteLine();
}
}
Example Revealed
- Create - when I want to add a new course I use the method AddToCourses of
the proxy or AddObject method (which I need to supply the name of the
resource which the object will the added to). After the call for one of these
method, a call to SaveChanges method will create the object on the
data service’s side. The following methods will be called on the data context in
the order I use - CreateResource, SetValue (for every property), SaveChanges
and ResolveResource. In the CreateResource method I use the fullTypeName
parameter to create the type with reflection, add it to the courses list and
return it as the created object. The SetValue method will be called for every
property of the object and set all them also using reflection. SaveChanges is an
empty method which do nothing because we are using an in-memory object.
ResolveResource return the object it get because we don’t need to resolve
anything. - Update – when we want to update an existing object we call the UpdateObject
method of the proxy class. After that call the call to SaveChanges will pass the
request to the data context. The methods that will be called on the data context
will be – GetResource, SetValue, SaveChanges and ResolveResource.
The GetResource gets a IQueryable query which holds the data to update. I extract
the resource to update and return it. The other methods where explained in the
create bullet. - Delete – in order to the delete an object I use the DeleteObject method followed
by the SaveChanges method. The chain of method that will be called on the data
context will be – GetResource, DeleteResource, SaveChanges and
ResolveResource. The only method that concerns us (all the other where explain
earlier) is the DeleteResource method that only removes the object it gets from
the courses list.
Summary
Lets sum up the post, in order to use CRUD operations in a custom provider
of a data service you need to implement the IUpdatable interface. I provided
an example of how to implement a simple data context and I hope it will help
you to build your own. In the next post in the ADO.NET data services I’ll
write about how to perform batch operations.
Improving Performance By Using ASP.NET Caching - Output Cache
What is ASP.NET caching mechanism?
When to use caching? and how can I
use it in order to improve my site
performance? are the questions this
post series is going to answer.
In today’s post I’ll introduce
the output cache. You can
read the previous posts in the subject:
What is Output Cache?
Output cache is a mechanism that keep a copy of a rendered ASP.NET web page
in memory. This behavior helps to improve performance by returning a response
of the cached web page instantly and by reducing the need to render the page
in every client request. If a page takes a lot of time to render using output cache
can significantly improve the performance.
Even though, the output cache has a very big drawback. If your site needs to
enable customization for users or needs to show dynamic information you don’t
want your users to have the same version of the page. ASP.NET supports
configuration options to avoid this drawback with the output cache making it
very flexible and powerful.
Configure Output Cache for a Single Page in Declarative Way
You can control the output cache’s behavior in a declarative way by using the
@OutputCache page directive. The only required parameter for the output
cache is the Duration all the other parameters can be used if you want to.
Lets describe some of the parameters:
- Duration – the duration in seconds for the web page to be cached.
- Location – the location to save the cached object. You can save the
cached object on the server, client, both or all the other options
in the OutputCacheLocation enum. - VaryBy* (where * is in the set of [Param/Header/Custom/Control]) -
The most useful parameters in the parameters list is the VaryBy
parameters. With these parameters you indicate semicolon-separated
list of strings to vary the output cache. These strings can be parameters
of query string (Param), ID property values of ASP.NET server controls that
where declared in a user contorl (Control) and etc. These parameters are
used to vary caching of page/control by the given parameters therefore
enabling the caching of the same page/control with different behaviors. - SqlDependency – a string value that identifies a set of database and table name
pairs that the page or control’s output cache depends on. Every update of items
in the table will result in the removal of the items from the cache when using
table based polling.
Lets look at an example of the declarative way:
<%@ OutputCache Duration="30" Location="Client"
VaryByParam="PageNumber;Count" %>
In the example the output cache will last for 30 seconds, will be saved on the client
side and will vary the the PageNumber and Count query string parameters.
Configure Output Cache for a Single Page in Runtime
We can use the declarative way but sometimes we want to use caching in runtime.
The output cache can be configured in runtime using the Response.Cache property.
In the programmatic way there are few methods to use than in the declarative way.
The available methods are:
- SetExpires – indicates the number of seconds that the page will be cached.
- SetCacheability – uses an enum to indicate where the cache will be stored.
- SetValidUntilExpires – if the method get true as parameter the cache ignores
invalidation headers.
Invalidating Cached Pages
There are a lot of reasons to invalidate a cached page such as items that where
inserted or updated in a database, file changes which the page use or etc. When
we need to invalidate a cached page there are some ways to do it. Lets explore
the ways:
Determine whether to use a cached page – in order to determine whether
to use a cached page you need to respond to the ValidateCacheOutput event.
An example of how to do it can be:
protected void ValidateCacheOutput(HttpContext context,
object data, ref HttpValidationStatus status)
{
string pageNumber =
context.Request.QueryString["PageNumber"];
if (string.IsNullOrEmpty(pageNumber))
{
status = HttpValidationStatus.Valid;
}
else
{
status = HttpValidationStatus.Invalid;
}
}
protected void Page_Load(object sender, EventArgs e)
{
Response.Cache.AddValidationCallback(
new HttpCacheValidateHandler(ValidateCacheOutput),
null);
}
What you see in the example is the use of a AddValidationCallback which
is a part of the Response’s Cache object. ASP.NET uses this callback
method to determine whether to use the cached version of the page or not
according to the HttpValidationStatus enum. In the example I provided if
there is no pageNumber in the query string the cache is valid else the cache
isn’t valid. This example is very simple and I won’t recommend you to use it
but it shows the concept of how to use the ValidatecacheOutput callback.
Pay attention to register the AddValidationCallback in the Page_Load event
and not after it.
Create output dependency for cache – in the Response there are methods
that help to create a cache page output dependency. These methods are
AddCacheDependency, AddCacheItemDependency, AddCacheItemDependencies,
AddFileDependency and AddFileDependencies.
Configuring Caching in Web Configuration File
In the previous section I described how to use output cache programmatically
but sometimes you want to use configurations. In the configuration file we
create cache profiles that the pages of the application can use with the
@OutputCache page directive. This can be done by using the caching element under
the system.web element of the web.config file. In the caching element we add
cache profiles which can be used in the application easily.
The next example shows how to build a cache profile:
<system.web>
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name="profile" duration="30"
enabled="true" varyByParam="pageNumber"/>
</outputCacheProfiles>
</outputCacheSettings>
</caching>
</system.web>
We use the profile like this in the page:
<%@ OutputCache Duration="30" CacheProfile="profile" %>
Other things that you can configure are: sqlCacheDependency, outputCache for
the entire appliaction and cache policy for the entire application.
Summary
Lets sum up the post, in the post I showed ways to use the output cache
which is very powerful tool to improve performance. As you could see in the
post there are a lot of ways to use the output cache either programmatically or
declarative. The use of the output cache is easy but you should use it very
carefully. There will be no mercy from the application users if the pages of the
web application will become static because you used the output cache poorly.
I suggest to learn output cache and it’s consequences very well before using it.
This is the last post in the series of how to use ASP.NET caching.
The Benefits of Code Review
Two days ago, I reviewed a code
of one of SRL’s employees as a part
of his ASP.NET training. The
employee got a training ASP.NET
tutorial that I wrote for SRL and
implemented a solution. The tutorial
gives high level details of what the
trainee need to implement and the
trainee need to implement all the
solution parts by himself/herself.
So, why to bother and review a
trainee’s code? why to bother to
review code at all? In this post I’ll
try to answer these questions.
Code Review
Code review is a process where one member of a team reviews other
member of the team’s code. I wrote “one member of the team” because
every experienced team member can and should review code and not only
the team leader or higher positions. The number of reviewers in code review
can be one or more (if you can afford it…). There are no strict guidelines to
code review but there are some that you should follow:
- Defect free solutions.
- The code meets the requirement.
- The code follows industrial coding standards or your company’s standards.
The Benefits of Code Review
After we understand what is code review lets talk about what is its benefits:
- Enforcing coding standards – by reviewing other developers code you can
enforce industrial or company’s coding standards. Doing so will make the code
more readable by the other developers in the team. In that way developers
can work on code that someone else wrote and the code will be easier for them
to read. - Mentoring tool – as I wrote in the example in the post’s start I perform code
review as a way to help trainees to boost their development skills. The use
of code review also can contribute to experience developers to see and learn
other ways to develop (if you review other experienced developer’s code). - Better quality code – when you use code review process you can identify
defects early in the development process. In that way the benefit is the cost
that you save to identify these errors when your application is in production
or in late development step. - Wider project view – the developer that perform the code review can review
places in the system that he/she never seen before. Sometimes, in big projects
you build only one part of the solution. The code review can give the developers
a wider sight on the project they participate in. - Better structured code – when a developer knows that someone will review
his/her code, the code that he/she write will be more documented and easier
to read.
Probably there are more benefits and you can use the comments to add things that I
didn’t write.
Summary
The code review that I wrote about took almost one hour. In that hour I showed
the trainee where were his errors and suggested how to correct them. Also, I
pointed the places where he should improve his code. Things like documentation,
regions, error proof code, standards and more where part of my conclusions where
the trainee could improve. This example shows some of the benefits of code review
that include enforcing coding standards, finding defects and more. I think that
code review process is one of the building blocks of better software solutions and
should be integrated in every faze of the development process.
Why Data as a Service isn't a Bad Idea
Early this week I encountered
the post "Why the Database as a
Service is a Bad Idea" written by
Arnon Rotem-Gal-Oz in DZone.
The title caught my eye and I read
the post. I must say that there are a lot
of things that I agree with the author and
there are some things that I think should be considered again and will be explained
in this post.
Why Not to Use Database as a Service?
As the author wrote the exposing of a database internals through a service is not a
good idea at all. Services are meant to be an operational contract between the
service consumer and the service provider. Also, the use of database as a service
encourages bypassing real services and going straight to their data.
Why to Use Data as a Service?
Even so, I must disagree about the potential of ADO.NET data services when it's
understood. I think that with the examples that Microsoft (or others) gave to the
use of the technology they shot themselves in the leg and I'll explain why. To expose
data through a service isn't such a bad idea. To expose database through a service is
a bad idea. Microsoft's operation regarding data services can be metaphoric to walking
on very slippery rocks. The examples that were showed by Microsoft people of how
to expose an entire database with full CRUD operations through data services made
them slip. Such a thing is not a good practice at all even with the security data services
provide. On the other hand using a custom LINQ provider to expose data is a more
reasonable thing to do. The provider will help to expose relevant data (doesn’t necessarily
have to be database) which the application need. You can look at an example of
using a custom LINQ provider in a previous post I wrote. Using the provider way doesn’t
expose your database to the world and helps you expose and consume the entities
that you need in your application.
The Potential of ADO.NET Data Services
So what is the potential of ADO.NET data services?
In a RIA applications or data driven application it can help to provide a cleaner solution.
The ability of data services to return responses in JSON or in URI makes
them flexible and usable by Ajax or Silverlight. Also, if the data service is consumed by
a .Net client you can use the LINQ to data service feature. The data services come
with other features like concurrency, batch operations over HTTP, full query operation
support and more. These features, when used right, can help to provide good solutions
for a data driven application.
Conclusion
Lets sum up the post, first I must indicate that I’m not a Microsoft employee and the
opinion written here is my own. I think that some things that were written by
Arnon in his post are right but even so the technology has a very good potential which
was explored earlier.
The thing about a new technology is what to do with it.
What you are going to do with ADO.NET data services will determine it's future.
I really don't think that you should use it to expose your entire database.
I really do think that you should use it to expose data as a service.
Building a .Net Client for ADO.NET Data Service
In the previous post about
ADO.NET data services I
introduced the data services
topic and showed a simple
example of how to build a data service.
In today’s post I’m going to explain how to consume the built data service by
a .NET client.
Revisiting The Previous Post Example
In the previous post I gave an example of course class and course data context.
In the previous example I used the preview version of ADO.NET data service
and since then the VS2008 SP1 was released. The example of the data service
needed to be changed to the new release and the service will look like:
public class CoursesService : DataService<CoursesDataContext>
{
// This method is called only once to initialize service-wide policies.
public static void InitializeService(IDataServiceConfiguration config)
{
config.SetEntitySetAccessRule("*", EntitySetRights.All);
}
}
You can see that the only change are the set method and the enum names
which now sets access rules for an entity.
Consume a Data Service With a .Net Client
To consume a data service was made easy in the new SP1 release.
In the previous betas you needed to use the datasvcutil.exe command line
tool in order to generate a proxy for the data service. In the new release
you can use the Add Service Reference like you use it for every other service.
In order to use Add Service Reference you only need to pass the URL of the
data service’s metadata or use the Discover option to discover the service’s
metadata if it’s in your solution.
One thing to remember, if you want to consume the service you need to make
it available by deploying it to IIS or by using the Visual Studio Development Server
with a specific port.
In order to use Visual Studio Development Server you need to go to the
data service project’s properties window and in the Web tab to check the
Specific Port radio button:
Adding Data Service .Net Client to Project
Using the same example from the previous post, I added a new console application
to the solution. In the console application I added a service reference with the
Add Service Reference:
After adding the service in the main method of the console application
I wrote the following code to get all the courses with a 5 credit:
static void Main(string[] args)
{
// build the proxy
var proxy = new CoursesDataContext(
new Uri("http://localhost:4205/CoursesService.svc/"));
var courses = from course in proxy.Courses
where course.Creadit == 5
select course;
foreach (Course course in courses)
{
Console.WriteLine(
"Course name: {0}, Course duration: {1}",
course.Title,
course.Days);
}
Console.Read();
}
As can be seen in the example I need to give the Uri of the data service
as a parameter to the generated proxy class. Also, as can be seen in the example
data service’s proxy comes with full LINQ capabilities (LINQ to data services)
which enhance the use of data services in a .Net client.
Summary
To sum up the post, it’s very easy to consume a data service from a .Net client.
All you need to do is to use the Add Service Reference feature of VS2008 which
will generate a proxy class for you. After you have the proxy in your hands you
can use it to query the data service using LINQ. Other options that you can do
with the proxy are CRUD operations which will be discussed in another post in
the near future.
Improving Performance By Using ASP.NET Caching - Application Caching
What is ASP.NET caching mechanism?
When to use caching? and how can I
use it in order to improve my site
performance? are the questions this
post series is going to answer.
In today’s post I’ll introduce
the application caching. You can
read the previous post in the subject here.
What is Application Caching?
As indicated from its name the application cache is a caching mechanism that is
constructed for every ASP.NET application when the application starts. Like the
Application and Session objects the Cache object is a singleton key value
collection. This singleton representation enables the cached items to be shared
between user sessions and requests. Unlike the Application and Session mechanisms,
the Cache has more capabilities, it is more powerful and it doesn’t store the data
for the entire life of the Session or Application.
Cache Scavenging
One thing you need to know about the cache is that its storage is in memory and
is limited (because the memory of a server is limited). As such a limited storage the
cache uses an automatic scavenging behavior in order to remove objects. The
removing is based on object priorities which is one of the parameters that you can
configure for an inserted cache object. Also, the cache remove items when they
have not been accessed for a period of time. Whenever the memory is starting to
be full the scavenging starts. You can’t control which object will be remove
(you control only the priorities) and therefore you can’t trust the availability of
a cached object and should always check if the object is available or not.
There are things you can do about object availability which will be described in the
next section (priorities, callback and etc).
Caching Objects
As written earlier in the post, the application cache is a collection and in order to
insert objects to the cache all I have to do is insert it by a key like this:
Now you should ask yourself things like that’s it? or why the hell did I bother to read
the post until now?
But… the power of the application cache comes with the Add and Insert methods
and not by the use of the cache indexer.
Lets explore the Add and Insert functionality.
The Add method gets a full bunch of parameters. If you don’t need to use all these
parameters you should use the Insert method with one of its overloaded
methods. The type of parameters that you can use to insert an object to the
cache are:
- Key – which will be the key of the stored object.
- The object to store in cache.
- Dependency – a CacheDependency object that watch a key or a file and
when they change triggers the removal of the cached object. - Absolute expiration – the time at which the object will be removed from the
cache whether it was accessed recently or needed. - Sliding expiration – the time span after which the object will be removed
from the cache if it hasn’t been accessed. - Priority – a priority value that can determine which objects will be removed
first when the scavenging mechanism starts. - OnRemoveCallback – an event handler that is called whenever the object is
removed from the cache. You can use this ability to restore object back to
the cache whenever they expired.
Lets look at an example:
public partial class _Default : Page
{
#region Members
private const string KEY = "Key";
#endregion
#region Page Events
protected void Page_Load(object sender,
EventArgs e)
{
if (Cache[KEY] == null)
{
CacheItemRemovedCallback callback =
new CacheItemRemovedCallback(
OnRemove);
Cache.Add(KEY,
"Value",
new CacheDependency(Server.MapPath(
"file.txt")),
DateTime.Now.AddDays(1),
new TimeSpan(1000),
CacheItemPriority.Normal,
callback);
}
string value = Cache[KEY].ToString();
}
#endregion
#region Methods
private void OnRemove(string key, object val,
CacheItemRemovedReason reason)
{
// do something
}
#endregion
}
The example is very simple to understand and shows all the parameters I
wrote about in action.
Summary
Lets sum up the post, today I explained the concept of application cache.
The application cache is very helpful and powerful singleton collection that can
be used to cache application data in memory for a faster retrieval.
It can be configured very easily by the Add or Insert method parameters.
The next post will continue the tour of caching and will explain the output
cache.
WebResource Embedded Resource Files Caching
Yesterday, I got a mission to
check why some web forms in
my current project have poor
performance. After some research
with the Fiddler tool I found that
the WebResource.axd files are
reloaded in every page request.
These files are used for script callbacks by the Ajax extensions. The thing about
those files are that they are very big and therefore consume a lot of bandwidth
and make the page load very slow. Checking the issue further I noticed that the
files were sent with the Cache-Control: private header therefore they were never
cached. The issue happens because when an assembly is compiled in debug mode
the caching is made private which means that no caching will happen. To solve the
problem just compile the assembly in release mode which will result in a public
Cache-Control header. Because I’m currently not a member in the team that update
the production version I went to check whether the system is compiled in release mode
before it goes to production. Guess what was the answer…
Yep, no release compilation and a penalty of performance to our system.
The issue is currently been checked and hopefully the next version will be in release
mode.
For further reading in the subject I recommend Rick Strahl’s post.
ADO.NET Data Services Introduction
Introduction
From the early ages of development, the separation
of presentation and data was very necessary and was
considered (and is considered) a good practice. As you
all know, the current trend in the web development
world is building Rich Internet Applications (RIA) and
buzz words like Ajax and Silverlight are very popular today. The RIA technologies
(Ajax, Silverlight and etc) are built on the concept of separation between the
presentation and data in order to build more interactive and responsiveness web
applications. Another trend that is very popular today is building RESTful systems.
REST, Representational State Transfer, “is a style of software architecture for
distributed hypermedia systems such as the World Wide Web” (taken from Wikipedia).
REST isn’t the issue of the post and you can read about the it here if you like.
These trends were the starting point of project Astoria which in days became the
ADO.NET data services project.
ADO.NET Data Services – Project Astoria
”The ADO.NET Data Services framework consists of a combination of patterns and
libraries that enable the creation and consumption of data services for the web” -
(taken from the ADO.NET data services site). The services use URIs to be consumed by
their clients. The data is represented as Atom/APP (Atom Publishing Protocol) or
JSON (JavaScript Object Notation) and the representation is built by the requests
header. For example, if the application sends a JSON request the response will be built
in JSON notation. The default representation is Atom and it uses a fixed mapping of
entities to XML elements in Atom.
The data service results are built in REST style resource collection
of data that can be address by their URIs. The clients can interact with this data
using HTTP commands such as GET and POST which make the interaction very simple.
The ADO.NET data services will be shipped with VS2008 SP1.
ADO.NET Data Services Framework Architecture
The next figure shows the ADO.NET data services framework architecture:
The thing to notice is that in order to build a data service over a source it needs
to be IQueryable. All the interaction between a client and a data service is
made in HTTP protocol to the service host. The request is sent to the service
and the service respond with the requested data.
Environment Prerequisites
In order to develop ADO.NET data services you need to have VS2008
installed on your computer. Also, you need to have the VS2008 SP1 beta
installed on your computer. If you don’t have SP1 beta you can download it
here.
ADO.NET Data Services First Example
Lets build our first data service.
In VS2008 open a new web site or web application project.
First we will build a data source for the data service. I could use the EDM wizard to
build a new EDM of a database and integrate it very fast into the data service
but I chose to build a simple custom LINQ provider instead.
I’m building two classes. The first is a simple data structure to hold a Course:
public class Course
{
#region Properties
/// <summary>
/// The course ID
/// </summary>
[DataWebKey]
public int CourseID { get; set; }
/// <summary>
/// The course title
/// </summary>
public string Title { get; set; }
/// <summary>
/// The duration in days of the course
/// </summary>
public int Days { get; set; }
/// <summary>
/// The course academic credit
/// </summary>
public int Creadit { get; set; }
#endregion
#region Methods
/// <summary>
/// Return a fixed list of courses
/// </summary>
/// <returns>A list of courses</returns>
public static List<Course> GetCourses()
{
return new List<Course>() {
new Course() { CourseID = 1, Creadit = 3, Days = 3 , Title = "Algorithms"},
new Course() { CourseID = 2, Creadit = 5, Days = 5 , Title = "Data Structures"},
new Course() { CourseID = 3, Creadit = 5, Days = 5 , Title = "Databases"}
};
}
#endregion
}
The only interesting thing about the class is the DataWebKey attribute
that indicate that the key of the class is the CourseID. As you can see I
made a static GetCourses method that returns a fixed and static course list.
The next thing to do is to build a class that will be the data context for the
data service. You have to remember that the data context have to return a
IQueryable response in order to use it in data service. The
CoursesDataContext class code:
public class CoursesDataContext
{
#region Properties
/// <summary>
/// Return the courses in a IQueryable format
/// </summary>
public IQueryable<Course> Courses
{
get
{
return Course.GetCourses().AsQueryable();
}
}
#endregion
}
There is an extension method of IEnumerable called AsQueryable that help
us to return a IQueryable data structure from the list of courses.
The last thing is to build the data service.
From Add New Item menu choose ADO.NET data service and add a new data
service to the project:
After adding the service copy and paste the following service code:
public class CoursesService : WebDataService<CoursesDataContext>
{
// This method is called once during service initialization to allow
// service-specific policies to be set
public static void InitializeService(IWebDataServiceConfiguration config)
{
config.SetResourceContainerAccessRule("*", ResourceContainerRights.All);
}
}
A note – the line of configuration in the InitializeService method gives the user of
the data service all right (edit, delete) and can make a security treat. I used it only
for the demonstration.
After that all you have to do is view the service in the browser and the result
should look like:
You can navigate to the courses by writing a URL like:
http://localhost:4205/CoursesService.svc/Courses.
Summary
The post gave the background for a post series about ADO.NET data services.
Also, I gave a small data service introduction example.
In the next posts I’ll try to answer questions about how to use data services.
Improving Performance By Using ASP.NET Caching
What is ASP.NET caching mechanism?
When to use caching? and
how can I use it in
order to improve my site performance? are the
questions this post series is going to answer.
Introduction
The caching mechanism is one of the most powerful feature shipped with ASP.NET.
Even so, most developers don’t understand its power and misuse it. I had the
opportunity to see and to hear about a lot of developer mistakes in the area of bad
caching implementation or in the other hand not using caching mechanism when
appropriate.
What is ASP.NET Caching?
The caching mechanism was made to store frequently accessed data in memory for a
fast retrieval latter. When the data is stored in memory it can be retrieved faster then
in all other storage mechanisms and therefore can boost performance. For example if
I have an XML file that holds application relevant data I can read it once and cache
the data. When I cache the data I won’t need to use another I/O operations of reading
the file in order to use the data again. The data will be available in memory and will be
retrieved faster. This is one example of how to use cache but the thing you need to
ask yourself now is what if I make an update to the file? how the cache mechanism will
know that? these questions are good but the ASP.NET caching can handle those things
and what you need to understand is how to tell it to do so.
ASP.NET Caching Types
ASP.NET provide two types of caching:
- Application caching – A key value collection that stores the objects in memory
and manage the objects lifetime in memory automatically. - Page output cache – A mechanism to cache whole pages or part of them in order
to save time and resources in rendering them again in future requests.
Summary
The post introduced the ASP.NET caching concept and described the types of caching in
general. The following posts in the series will get into more details about how and
what to do in order improve performance by using caching.
Farewell Design Patterns Series
Today I finished my series in the subject of
design patterns.
It was an intensive and satisfying writing and I hope that you will find the series
helpful and use it.
You can read all the series in the following links:
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
Strategy pattern Iterator pattern Template method pattern Command pattern Chain of responsibility pattern Mediator pattern Memento pattern State pattern Visitor pattern Observer pattern Interpreter pattern
I’m thinking of publishing all the series in a printable document like word
or pdf. Please tell me what do you think about this idea.
would you download such a document?
Farewell design patterns series it was a pleasant to create you and now I’m
moving ahead to other series and other challenges.
Interpreter Pattern
This post is the last post in the series of design patterns.
the post will describe why and how to use the interpreter design pattern and will
have a C# example of how to implement the 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
Behavioral Patterns
Strategy pattern
Iterator pattern
Template method pattern
Command pattern
Chain of responsibility pattern
Mediator pattern
Memento pattern
State pattern
Visitor pattern
Observer pattern
Interpreter Pattern
The interpreter design pattern enables the reading and interpreting
of instruction that are written in a specific purpose language or notation.
The interpreter uses the representation of the grammar of the language
in order to interpret the language instructions.
Using the pattern can cause a performance issue.
Use Cases for the Interpreter Pattern
You should use the pattern in the following cases:
- You have a grammar for a language that isn’t large and complicated.
- Performance isn’t an issue in the application.
- You have a way to parse the grammar in an efficient way.
UML Diagram
Example in C#
The following code is an example of how to implement the pattern:
#region Context
public class InterpreterContext
{
}
#endregion
#region Expression
public abstract class AbstractTerm
{
#region Methods
public abstract void Interpret(InterpreterContext context);
#endregion
}
#endregion
#region Concrete Expressions
public class TerminalTerm : AbstractTerm
{
#region Methods
public override void Interpret(InterpreterContext context)
{
Console.WriteLine("Terminal");
}
#endregion
}
public class NonterminalTerm : AbstractTerm
{
#region Methods
public override void Interpret(InterpreterContext context)
{
Console.WriteLine("Nonterminal");
}
#endregion
}
#endregion
The example is very simple and follows the instructions of the UML shown above.
The following code is an example scenario of how to run the pattern in
console application:
InterpreterContext context = new InterpreterContext();
List<AbstractTerm> terms = new List<AbstractTerm>();
// Build the terms tree
terms.Add(new TerminalTerm());
terms.Add(new NonterminalTerm());
terms.Add(new TerminalTerm());
// Interpret the tree
foreach (AbstractTerm term in terms)
{
term.Interpret(context);
}
Console.Read();
Summary
To sum up the post, I explained the interpreter design pattern in the post.
The pattern is rarely used and implies performance issues in the application.
I hope that you enjoyed the journey in the world of design patterns and that
the posts where helpful.
See you in the next posts in other development subjects.
Observer Pattern
The post will describe why and how to use the observer design pattern and will
have a C# example of how to implement the 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
Behavioral Patterns
Strategy pattern
Iterator pattern
Template method pattern
Command pattern
Chain of responsibility pattern
Mediator pattern
Memento pattern
State pattern
Visitor pattern
Observer Pattern
The observer design pattern defines a one to many dependency between
an object and its dependents. The dependency is created in order to inform
the dependents that the object changed its state and therefore the dependents
can react to the change. A very good example of such behavior is the blogging
systems were subscribers are notified whenever a blogger published a new post.
Another real world example can be the MVC architecture pattern which uses the
pattern.
Use Cases for the Observer Pattern
You should use the pattern in the following cases:
- You have a publisher/subscriber model.
- Objects need to be notified of a change in another objects.
- You need that the object that notify its state change would not
know about its subscribers.
UML Diagram
Example in C#
The following code is an example of how to implement the pattern:
#region Subject
public abstract class Subject
{
#region Members
private List<IObserver> _observers;
#endregion
#region Ctor
/// <summary>
/// Construct a new subject object
/// </summary>
public Subject()
{
_observers = new List<IObserver>();
}
#endregion
#region Methods
/// <summary>
/// Attaches a new observer to the subject
/// </summary>
/// <param name="observer">The observer to attach</param>
public void Attach(IObserver observer)
{
_observers.Add(observer);
}
/// <summary>
/// Detaches an observer from the subject
/// </summary>
/// <param name="observer">The observer to detach</param>
public void Detach(IObserver observer)
{
_observers.Remove(observer);
}
/// <summary>
/// Notify all the observers about the change in the
/// subject's state
/// </summary>
public void Notify()
{
foreach (IObserver observer in _observers)
{
observer.Update();
}
}
#endregion
}
#endregion
#region Concrete Subject
public class ConcreteSubject<T> : Subject
{
#region Properties
/// <summary>
/// The state of the subject
/// </summary>
public T SubjectState { get; set; }
#endregion
}
#endregion
#region Observer
public interface IObserver
{
void Update();
}
#endregion
#region Concrete Observer
public class ConcreteObserver<T> : IObserver
{
#region Properties
/// <summary>
/// The subject the observer holds
/// </summary>
public ConcreteSubject<T> Subject { get; set; }
private T _observerState;
#endregion
#region Ctor
/// <summary>
/// Construct a new concrete observer with the given
/// subject
/// </summary>
/// <param name="subject">The given subject</param>
public ConcreteObserver(ConcreteSubject<T> subject)
{
Subject = subject;
}
#endregion
#region IObserver Members
/// <summary>
/// Make an update to the observer state whenever the
/// method is callled
/// </summary>
public void Update()
{
_observerState = Subject.SubjectState;
Console.WriteLine("The new state of the observer:{0}",
_observerState.ToString());
}
#endregion
}
#endregion
The example is simple to follow. We have an IObserver interface and a
Subject abstract class. The observers are registered in the subject with the
Attach method and also can be detached. The subject implement the Notify
method that notifies every observer when the subject state was changed.
When the state changes the observer make an update which is the main
method of the IObserver interface.
The following code is an example scenario of how to run the pattern in
console application:
ConcreteSubject<string> subject =
new ConcreteSubject<string>();
subject.Attach(new ConcreteObserver<string>(subject));
subject.Attach(new ConcreteObserver<string>(subject));
subject.SubjectState = "Hello World";
subject.Notify();
Console.Read();
Summary
To sum up the post, the observer pattern is widely used and it is very helpful.
You can see the uses of the pattern in the MVC framework for example or even
here in Israel Microsoft blogs when you subscribe to a blog in order to be notified
of new blogger posts.
The next post in the design patterns series will be the last pattern post and
it will include the interpreter pattern.
Visitor Pattern
The post will describe why and how to use the visitor design pattern and will
have a C# example of how to implement the 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
Behavioral Patterns
Strategy pattern
Iterator pattern
Template method pattern
Command pattern
Chain of responsibility pattern
Mediator pattern
Memento pattern
State pattern
Visitor Pattern
The visitor design pattern enables us to create new operations to be
performed on an existing structure. The new operations don’t change the
classes/nodes. With the pattern you define two class hierarchies.
The first for the elements which the operations will operate on.
The second is for the visitors that define the operations on the elements.
The pattern is rarely used but it is common in compilers implementation.
Use Cases for the Visitor Pattern
You should use the pattern in the following cases:
- You have a class hierarchy with many distinct operations.
- The classes that defined in the object structure rarely change, but you
need sometimes to define new operations on the object structure.
UML Diagram
Example in C#
The following code is an example of how to implement the pattern:
#region Visitor
public interface IVisitor
{
#region Methods
void Visit(Element element);
#endregion
}
#endregion
#region Visitor Concrete
public class VisitorConcreteA : IVisitor
{
#region IVisitor Members
public void Visit(Element element)
{
Console.WriteLine("{0} Visited {1}",
this.GetType().Name, element.GetType().Name);
}
#endregion
}
public class VisitorConcreteB : IVisitor
{
#region IVisitor Members
public void Visit(Element element)
{
Console.WriteLine("{0} Visited {1}",
this.GetType().Name, element.GetType().Name);
}
#endregion
}
#endregion
#region Element
public interface IElement
{
#region Methods
void Accept(IVisitor visitor);
#endregion
}
public abstract class Element : IElement
{
#region IElement Members
public void Accept(IVisitor visitor)
{
visitor.Visit(this);
}
#endregion
}
#endregion
#region Concrete Element
public class ElementConcreteA : Element
{
// implement whatever you need
}
public class ElementConcreteB : Element
{
// implement whatever you need
}
#endregion
#region Object Structure
public class ObjectStructure
{
#region Members
private List<Element> _elements;
#endregion
#region Ctor
/// <summary>
/// Construct a new object structure
/// </summary>
public ObjectStructure()
{
_elements = new List<Element>();
}
#endregion
#region Methods
/// <summary>
/// Attach the given element to the object structure
/// </summary>
/// <param name="element">The element to attach</param>
public void AttachElement(Element element)
{
_elements.Add(element);
}
/// <summary>
/// Detaches the given element from the object structure
/// </summary>
/// <param name="element">The element to detach</param>
public void DetachElement(Element element)
{
_elements.Remove(element);
}
/// <summary>
/// Perform accept operation on all the object structure
/// with the given visitor
/// </summary>
/// <param name="visitor">The given visitor</param>
public void Accept(IVisitor visitor)
{
foreach (Element element in _elements)
{
element.Accept(visitor);
}
}
#endregion
}
#endregion
In the example I use an object structure that is implemented with
an inner list. You can use whatever object structure you need in order to
implement the pattern. As can be seen in the example, I use two main
interfaces to implement the pattern – IVisitor and IElement. The IElement
dictates the Accept method to the Element abstract class which every concrete
element implement (I could drop the IElement or the Element class but I have chosen
not to). Every visitor concrete implement the Visit operation to perform the
desired operation (in my implementation the Visit method is implement the same in
both concrete classes).
The next code shows an example of how to use the classes above:
// Build the structure
ObjectStructure structure = new ObjectStructure();
structure.AttachElement(new ElementConcreteA());
structure.AttachElement(new ElementConcreteB());
// Create visitor objects
VisitorConcreteA visitorA = new VisitorConcreteA();
VisitorConcreteB visitorB = new VisitorConcreteB();
// Structure accepting visitors
structure.Accept(visitorA);
structure.Accept(visitorB);
Console.Read();
Summary
To sum up the post, you were introduced to the visitor design pattern.
The pattern is used in order to extend elements of an object structure with new
operations without the need to change the elements.
As written earlier the pattern is rarely used.
The next pattern I’ll cover will be the observer pattern.
Expert Days 2008
In the middle of August between the 11 and the 14 there is a Microsoft expert conference
that take place in the Interdisciplinary center (IDC) in Herzelia. During the week there will
be over 20 one day workshops in various of subjects in the .Net developing world.
Some of the workshops will be delivered by co-workers in SRL including my manager
Maor David or Leon Langleyben. Even though I won’t participate in the conference because
I’m on vacation in these days (someone need to take care of Oron, my baby boy, in the
summer vacation), I recommend you to participate. This is a unique opportunity to be
in a wonderful place like IDC which I’m its graduate and also to hear Microsoft
experts teaching very helpful workshops. In the developing area’s that I like there is a
workshop in design patterns that you can participate.
See you in the next posts.
State Pattern
This post is a post in the design patterns series I’m writing.
The post will describe why and how to use the state design pattern and will
have a C# example of how to implement it.
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
Strategy pattern
Iterator pattern
Template method pattern
Command pattern
Chain of responsibility pattern
Mediator pattern
Memento pattern
State Pattern
The state design pattern enables us to change the object’s behavior according
to its internal state. The pattern is sometimes described as a dynamic version
of the strategy pattern. The changing of the state is done by an inner object which
has different subclasses that represent the relevant behavior.
Use Cases for the State Pattern
You should use the pattern in the following cases:
- An object’s behavior depends on it’s current state and you need to change
it behavior in runtime according to it’s state.
- The inner operations are becoming complex with a lot of conditional statements
that depend on the object’s inner state.
- You need flexibility in assigning requests to their handlers.
UML Diagram
Example in C#
The following code is an example of how to implement the pattern:
#region State
public interface IState
{
void Handle(StateContext context);
}
#endregion
#region Context
public class StateContext
{
#region Properties
/// <summary>
/// The current inner state
/// </summary>
public IState State { get; set; }
/// <summary>
/// An inner counter of this context
/// </summary>
public int Counter { get; set; }
#endregion
#region Ctor
/// <summary>
/// Construct a new StateContext with the
/// given first state
/// </summary>
/// <param name="state">The first state of the object</param>
public StateContext(IState state)
{
State = state;
}
#endregion
#region Methods
/// <summary>
/// Send a request to be handled by the inner state
/// behavior
/// </summary>
public void Request()
{
State.Handle(this);
}
#endregion
}
#endregion
#region Concrete State
public class ConcreteStateA : IState
{
#region IState Members
public void Handle(StateContext context)
{
context.Counter += 2;
// change the context state to a new state
context.State = new ConcreteStateB();
}
#endregion
}
public class ConcreteStateB : IState
{
#region IState Members
public void Handle(StateContext context)
{
context.Counter -= 1;
// change the context state to a new state
context.State = new ConcreteStateA();
}
#endregion
}
#endregion
The implementation of state depends on inheritance. The main issues is to
understand that every concrete state is responsible to change the current
context behavior to the next context behavior in the chain of behaviors. The
example I gave is simple and can be run with this code:
// initialize a context with a first state behavior
StateContext context =
new StateContext(new ConcreteStateA());
context.Request();
Console.WriteLine("The current counter need to be 2: {0}",
context.Counter);
context.Request();
Console.WriteLine("The current counter need to be 1: {0}",
context.Counter);
context.Request();
Console.WriteLine("The current counter need to be 3: {0}",
context.Counter);
Console.Read();
Summary
To sum up the post, the state pattern is very simple to implement as you can
see form the example I gave above. The pattern is very effective in graphic tools or
in game programing. Even so, the pattern is not commonly used in programming.
The next pattern in the series will be the visitor pattern.
More Posts
Next page »