January 2009 - Posts
Hierarchical Datasets Updates
As a part of a session that
I’m suppose to deliver on March,
I’m going to explain the
datasets enhancements that
came along with Visual Studio 2008.
In particularly, I’m going to explain what is the TableAdapterManager and
how it is going to help you with hierarchical datasets updates. The post
is going to explain that subject as well.
The TableAdapterManager Class
When you create a new typed-dataset in Visual Studio 2008 by default a class
by the name TableAdapterManager is generated. The main purpose of the class
is to enable the functionality to save data in related data tables. The
TableAdapterManager uses the relations between the data tables in order to
determine in which order to perform a set of CRUD operations without violating
any foreign-key constraints. This behavior is called hierarchical update. This new
behavior is suppose to free the developers from the plumbing of building
CRUD scenarios by themselves when using datasets. The hierarchical update behavior
is best suited to Master-Details forms. As a backward compatibility a new property
with the name Hierarchical Update was added to the typed-dataset. That property is
by default True but in datasets that were added to projects that were created in
earlier versions of Visual Studio the Hierarchical Update property is set to False.
How to Perform Hierarchical Datasets Updates
The following example is going to use the typed-dataset that is
generated from the following database schema:
Lets generate the dataset. I’ve created a class library that is called
DataAccessLayer. In that library I generated a new typed-dataset
with the name SchoolDataSet. Then, I dragged the Course and
Department tables to the designer. The following image shows the
outcome of the operations I described:
As you can see in the image I put the mouse pointer on the new
Hierarchical Update property. If you don’t want to use that feature
change the property to False.
The following class provide a method to update Courses and Departments
in hierarchical update:
public class DataProvider
{
public void UpdateCoursesAndDepartments(SchoolDataSet ds)
{
TableAdapterManager manager = new TableAdapterManager();
manager.CourseTableAdapter = new CourseTableAdapter();
manager.DepartmentTableAdapter = new DepartmentTableAdapter();
manager.UpdateAll(ds);
}
}
In order to use hierarchical update we need to create a new
TableAdapterManager and insert the relevant table adapters that will
participate in the update. The reason for that is obvious. If we have a lot
of data tables in the dataset that don’t participate in the update, why should
we build adapters for them? it will be a waist of memory. After building the
adapters all we have to do is to call the UpdateAll method that perform the
hierarchical update. Simple as that.
Summary
Lets sum up, Visual Studio 2008 brought with it some enhancements for the
datasets world. One enhancement is the hierarchical update feature that enables
to update a set of data tables that relate to one another without the need to
indicate the order of operations. I showed how to use the TableAdapterManager
which is the base for the hierarchical update behavior.
How to Write Your Own Code Snippets
IntelliSense code snippets
are a very useful tool for
developers in order to write
code faster.In the post I’m
going to describe how to
write your own code snippet and to show an example of a code snippet that
I wrote which divides classes by regions in the style that I like.
What are Code Snippets?
IntelliSense code snippets are basically Xml files that have a strict schema
and have a .snippet file name extension. They are used by developers for
faster code writing and therefore can reduce the time it takes to code.
When you locate a code pattern that always repeat itself in some varieties
you should consider writing it in a code snippet in order to save time.
Code snippets are also used by lecturers in order to write faster code in
their sessions (using the IntelliSense) in order to reduce the amount
of technical coding that they write and reduce problems that may occur.
Writing Your Own Code Snippet
Building a code snippet is easy. All you have to do is to follow the
code snippet XML schema. The first thing to do is to create a new
Xml file with the .snippet file name extension. After you have that
file you need to follow the code snippet XML schema in order to create
your snippet. In the file the first thing to add is the CodeSnippets element
with a Xml namespace to direct to the snippets namespace like this:
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
</CodeSnippet>
</CodeSnippets>
After you wrote the namespace it will help you to create the snippet
by showing errors of missing Xml elements that you need to provide.
Every snippet has to have a snippet header. The header provide the details for
the snippet such as the Title, the Author, the Description and the Shortcut
which is the code you write to invoke the snippet in the IntelliSense.
An example for a header can look like:
<Header>
<Title>
Arrange Class Snippet
</Title>
<Author>Gil Fink</Author>
<Description>The snippet helps to divide a class to its parts using regions</Description>
<Shortcut>ArrangeClass</Shortcut>
</Header>
The last element that we have to include in the Xml is the Snippet itself.
The main element of the Snippet element is the Code element which inside
of it you provide the snippet code. You have to indicate which language the
snippet belongs (C#, VB or more). The code of the snippet needs to be
located inside of a <![CDATA[ …Code ]]> element.
An example of a Snippet element can look like:
<Snippet>
<Code Language="CSharp">
<![CDATA[#region Consts
#endregion
#region Members
#endregion
#region Properties
#endregion
#region Ctor
#endregion
#region Methods
#region API Public Methods
#endregion
#region Private Methods
#endregion
#endregion]]>
</Code>
</Snippet>
The following example is a code snippet that I wrote to help me arrange
classes to regions in the way that I like. This is a full example for how to
write a code snippet:
<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>
Arrange Class Snippet
</Title>
<Author>Gil Fink</Author>
<Description>The snippet helps to divide a class to its parts using regions</Description>
<Shortcut>ArrangeClass</Shortcut>
</Header>
<Snippet>
<Code Language="CSharp">
<![CDATA[#region Consts
#endregion
#region Members
#endregion
#region Properties
#endregion
#region Ctor
#endregion
#region Methods
#region API Public Methods
#endregion
#region Private Methods
#endregion
#endregion]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
How to Import a Code Snippet into the Code Snippet Manager?
After writing a code snippet the next thing to do is to import it to the
Code Snippet Manager of Visual Studio. The following steps will help you
to do this thing:
- In Visual Studio choose Tools menu and from it the Code Snippet
Manager:
- From the Code Snippet Manager choose your language of choice and
press the Import button.
A dialog will be opened and in it browse the file system and find
your snippet. This will open the Import Code Snippet dialog.
In the Import Code Snippet dialog choose where to put the snippet
and you are done.
Summary
Lets sum up, in the post I introduced code snippets. I also showed
how to write your own code snippet and then how to import it to
Visual Studio 2008’s Code Snippet Manager. Code snippets can reduce
the amount of coding time by writing patterns of code into a code snippet
fragment and then use that fragment through the IntelliSense.
The following link is a good place to start when you want to get more
information about code snippets:
creating and using IntelliSense code snippets.
Deciding When to Use ASP.NET MVC Framework
The post aim is to
help you decide
when it’s
appropriate to
use ASP.NET MVC
Framework and when
it is appropriate to use ASP.NET Web Forms.
Web Forms Web Application Advantages
The old ASP.NET Web Forms framework is a mature framework that is
being used in a lot of applications and web sites. The advantages of Web
Forms are:
- State Management – in Web Forms state management is more easier.
The use of ViewState or server based forms simplify the state management
but reduce the control over the application behavior. - Event driven model – the Web Forms uses an event model that helps
to develop a more event driven application. You can wire to a lot of
events that are supported by the framework through controls and your pages. - Server Controls – the Web Forms approach has a massive control libraries
that can be used to build your application. On the other hand, the MVC
framework doesn’t currently have a lot of controls that can help to
build a more rich application and therefore you’ll have to build them
yourself. - Rapid development – it is faster to develop applications in the Web Forms
approach. The reasons for that are the support for components like server
controls or the page class that make it easier to develop (but brings a lot of
cons which are some of the advantages of MVC framework).
MVC Web Application Advantages
The ASP.NET MVC Framework is a new framework and therefore is more
risky then Web Forms approach which proved itself (or if you would like, didn’t
proved itself) in the past. The MVC framework brings the following advantages
over Web Forms approach:
- Separation of concern – the application is divided to Model, View and
Controller parts which makes it easier to manage the application complexity. - TDD – the MVC framework brings better support to test-driven
development. - Extensible and pluggable – the MVC framework components were designed
to be pluggable and extensible and therefore can be replaced or customized
easier then Web Forms. - Full control over application behavior – the MVC framework doesn’t use
ViewState or server based forms like Web Forms. This gives the application
developer more control over the behaviors of the application and also reduce
the bandwidth of requests to the server. - ASP.NET features are supported – MVC framework is built on top of
ASP.NET and therefore can use most of the features that ASP.NET include
such as the providers architecture, authentication and authorization
scenarios, membership and roles, caching, session and more. - URL routing mechanism – the MVC framework supports a powerful URL
routing mechanism that helps to build a more comprehensible and
searchable URLs in your application. This mechanism helps to the application
to be more addressable from the eyes of search engines and clients and can
help in search engine optimization.
Summary
Lets sum up, I wrote about the advantages of each ASP.NET approach.
When starting a new web application you will have to consider every aspect
of the application and then choose which framework is suitable for you to use.
Each framework brings its pros and cons and I hope I gave enough details
for you to make the right choice. I would like to read what are your thoughts
about which framework to use and when.
Extending ASP.NET MVC HtmlHelper Class
In the post I’ll show
an example of how
to extend the
ASP.NET MVC
HtmlHelper class
that you can use
within your MVC
views. In the example I’ll provide a simple solution for building an Html table.
The HtmlHelper class
The HtmlHelper class is a class that can be used within ASP.NET MVC
framework in order to help us render Html fragments of views.
The class is provided with a lot of methods that can help you render Html
types (textboxes, checkboxes etc) or Html parts (<form> for example).
The ASP.NET MVC framework helpers are currently the following:
- Html.ActionLink()
- Html.BeginForm()
- Html.CheckBox()
- Html.DropDownList()
- Html.EndForm()
- Html.Hidden()
- Html.ListBox()
- Html.Password()
- Html.RadioButton()
- Html.TextArea()
- Html.TextBox()
For example if I would like to render a checked checkbox with the name
myChkbox I can do it like that in my view:
<%= Html.CheckBox("myChkbox", true) %>
All the Html helpers are built as extension methods and can be located in
the System.Web.Mvc.Html namespace for review (if you like).
Building Html Table Extension For HtmlHelper
In my example I wrote an extension method for HtmlHelper to supply the
Html table rendering method. The example is supplied as is and you can
modify it or build your own example of how to render an Html table:
public static class MVCHelpers
{ public static string Table(this HtmlHelper helper, string name, IList items, IDictionary<string, object> attributes)
{ if (items == null || items.Count == 0 || string.IsNullOrEmpty(name))
{ return string.Empty;
}
return BuildTable(name, items, attributes);
}
private static string BuildTable(string name, IList items, IDictionary<string, object> attributes)
{ StringBuilder sb = new StringBuilder();
BuildTableHeader(sb, items[0].GetType());
foreach (var item in items)
{ BuildTableRow(sb, item);
}
TagBuilder builder = new TagBuilder("table"); builder.MergeAttributes(attributes);
builder.MergeAttribute("name", name); builder.InnerHtml = sb.ToString();
return builder.ToString(TagRenderMode.Normal);
}
private static void BuildTableRow(StringBuilder sb, object obj)
{ Type objType = obj.GetType();
sb.AppendLine("\t<tr>"); foreach (var property in objType.GetProperties())
{ sb.AppendFormat("\t\t<td>{0}</td>\n", property.GetValue(obj, null)); }
sb.AppendLine("\t</tr>"); }
private static void BuildTableHeader(StringBuilder sb, Type p)
{ sb.AppendLine("\t<tr>"); foreach (var property in p.GetProperties())
{ sb.AppendFormat("\t\t<th>{0}</th>\n", property.Name); }
sb.AppendLine("\t</tr>"); }
}
As you can see I’m extending the HtmlHelper with an extension method
that is called Table. The main function to render a table is the BuildTable
method that uses the ASP.NET MVC TagBuilder class in order to build the
table tag. You can also see that in my example I use reflection to get the
properties of the list of items I get and I use those properties as my
header and their values as the values of the table cells.
Using the Html Table Extension In a View
If you want to use the new custom Html helper for table that I showed
earlier you should do the following:
- Register the namespace of the new helper in the view using
the import tag in the view’s head like that:
<%@ Import Namespace="TaskList.Models" %>
- Use the Html property of the view with the new Table method.
For example the following line will add an Html table with the name
myTable and the current model of the view:
<%= Html.Table("myTable", (IList)ViewData.Model, null) %> Pay attention that if the Model isn’t IList you’ll get an exception.
Summary
Lets sum up, in today’s post I introduced the HtmlHelper class and
showed how to build a simple extension for that class. There is another way
to extend the HtmlHelper class by building your own class (for example
TableHelper) and all you have to do is to build methods that return the rendered
html to be added to the view. The use of extension method is easier in my opinion.
CodeProject
My Current Learning List of Technologies
In the last few days I have started to learn
few old/new technologies that I think you
should consider learning in the near future
as well (if you didn’t learn them before).
The technologies:
- ASP.NET MVC Framework – the new framework that
leverage the MVC pattern for ASP.NET. The technology
is a must learn technology for every .NET web developer in
my opinion. Learning the framework will give you a new
choice for implementing web applications with MVC pattern instead of
web forms. A lot was written in the area of ASP.NET MVC and I urge you to
go and explore the framework. The framework is going to be available side
by side with web forms and you’ll have the choice of using one of them or
using other non Microsoft web development framework. - Microsoft Sync Framework – the new Microsoft synchronization platform.
The Sync Framework helps to build sync ecosystems that will be able to
integrate any application (web, win, mobile and etc) with any data from
any store using any protocol over any network. for more details about the
framework you can read my previous post - Getting Started with Microsoft
Sync Framework. - NHibernate – I have always wanted to learn the NHibernate ORM in order to
compare it with Entity Framework or LINQ to SQL. Until now I haven’t had time
for this but lately I started to learn the framework and I enjoy it a lot.
I urge you to learn the framework in order to have more choices when you are
searching for a ORM solution. A very good place to start is the summer of
NHibernate screencast series.
In the near future I’m going to write about these subjects so stay tuned.
Which technologies you think that developers should consider learning in the near
future?
Getting Started with Microsoft Sync Framework
The post will introduce the
Microsoft Sync Framework which,
in my opinion, is going to be
one of the must know technologies
of the near future.
What is Microsoft Sync Framework?
Microsoft Sync Framework is a synchronization
platform that enables collaboration and offline
access across multiple data stores. The framework
enables taking data offline by working against a
cached set of data. Then we can submit the
changes to a global database in a batch by using
the framework features, technologies and tools.
The Sync Framework helps to build a sync ecosystems that will be able to
integrate any application (web, win, mobile and etc) with any data from
any store using any protocol over any network by using
custom synchronization providers.
A Little About Microsoft Sync Framework Components
The Sync Framework was designed as a componentized and layered architecture
to allow us to use only what we need to enable sync scenarios. The framework is
divided into the following three main components:
- Core Sync Runtime. The runtime that include all the algorithms and
components which we can use in order to sync our application. - Sync Provider Framework. The providers are software components that
represents a particular repository of information to be synchronized
(replica). We can write our own custom providers or use the providers that
were shipped in the framework. - Domain-specific components. An infrastructure to enable rapid development
when using specific stores and protocols like SQL Server or NTFS for example.
How Does it Work in a Nutshell
The next image which is taken from PDC lecture –
TL30: Microsoft Sync Framework: Advances in v2 shows the main issues of how
Microsoft Sync Framework works:
What you can see is the sync flow. The sync providers sits on top of the
data store and represent the repository. They are used to enumerate the items
in a data store and to maintain synchronization metadata and the state of the data
store. When a synchronization is needed a synchronization session is constructed
and with it a sync orchestrator. The sync orchestrator will manage the
synchronization from the source data store to the destination data store.
The destination provider will send its knowledge set to the source provider.
The source provider will compare that knowledge with its change set and will
send the changes to the destination. The destination provider will make sure that
the changes are not conflicting its storage and then will merge them and update its
knowledge.
Built in Sync Services
The following sync services are currently available to use in the Sync Framework v1:
- Sync Services for ADO.NET.
A synchronization provider for synchronizing across databases using ADO.NET. - Sync Services for File Systems.
A synchronization provider for synchronizing two file system locations. - Sync Services for FeedSync.
A synchronization provider for synchronizing replicas by creating a FeedSync,
either in RSS or ATOM, which can then be subscribed and used by whoever need
them.
Resources
The following resources will help you to start with the Sync Framework:
Summary
Lets sum up, in the post I introduced the Microsoft Sync Framework.
The Sync Framework is a rich synchronization platform which will be a very
useful tool for developers in the near future. I urge you to learn it today
and not to be left behind. In the future I’ll write more in the subject of
Microsoft Sync Framework.
Building ADO.NET Data Services Ajax Queries Using a QueryBuilder
In today’s post I’m
going to explain how
to use the QueryBuilder
object of the ASP.NET Ajax
client library for building
queries to an ADO.NET data
service.
The QueryBuilder Object
In the ASP.NET Ajax client library there is a new namespace – Sys.Data. This
namespace hosts the main client side objects to interact with data services.
You can recall that I wrote about the ASP.NET Ajax client library in a previous
post.
The QueryBuilder object is a part of the Sys.Data namespace.
The QueryBuilder provides methods and properties for manually creating a
data service query and enables us to build the queries through an API.
It can simplify the building of queries from the client side a lot because you
don’t need to remember all the syntax to create the query.
The following code is an example of how to create a QueryBuilder with a
Course Uri which is the resource we want to query:
var queryBuilder = new Sys.Data.QueryBuilder("Course");
In order to get to know the QueryBuilder’s API you can go to the following link.
QueryBuilder Example
The following example is a simple example to show how to work with the
QueryBuilder object in order to create a credits filter and an order by clause on a
course resource. The example is based on the ConsumeDataService example that
I wrote in the session I delivered lately. You can download the session’s
examples from here.
<%@ Page Title="" Language="C#" MasterPageFile="~/Master/AjaxClient.Master" AutoEventWireup="true" CodeBehind="QueryBuilder.aspx.cs" Inherits="DataServiceAjaxClient.QueryBuilder.QueryBuilder" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<label>Insert Credits to filter the results:</label><br />
<label>Credits:</label><input id="txtCredits" type="text" /><br/>
<input id="ButtonQuery" type="button" value="Perform Courses Query" onclick="doQuery()" /><br />
<br />
<span id="spanResults"></span>
<script type="text/javascript">
function doQuery() {
var queryBuilder = new Sys.Data.QueryBuilder("Course");
// set the filters if neccesery
queryBuilder.set_filter(buildFilter("txtCredits", "Credits eq "));
// set the order by the title
queryBuilder.set_orderby("Title");
// perform the query itself
proxy.query(queryBuilder.toString(), onSuccess, onFailure);
}
function buildFilter(txtName, query) {
debugger;
var txt = $get(txtName);
if (txt.value != null && txt.value != '')
{
return query + txt.value;
}
return '';
}
function onFailure(error, context, operation) {
$get("spanResults").innerHTML =
BuildErrorString(error, operation);
}
function BuildErrorString(error, operation) {
var sb = new Sys.StringBuilder("Error occurred while performing operation ");
sb.append(operation);
sb.append("!");
return sb.toString();
}
function onSuccess(result, context, operation) {
var spanResults = $get("spanResults");
spanResults.innerHTML = '';
// Get Customers list and render by using an HTML table.
var sb = new Sys.StringBuilder();
sb.append("<table cellpadding='1' cellspacing='1' border='1' bordercolor='green'>");
var firstRowOutput = false;
for (index in result) {
var course = result[index];
// If this is first row write the table header
if (!firstRowOutput) {
sb.append("<tr>");
for (key in course) {
if (key != "__metadata") {
sb.append("<th>");
sb.append(key);
sb.append("</th>");
}
}
sb.append("</tr>");
firstRowOutput = true;
}
// Display the data.
sb.append("<tr>");
for (key in course) {
if (key != "__metadata") {
sb.append("<td>");
sb.append(course[key]);
sb.append("</td>");
}
}
sb.append("</tr>");
}
sb.append("</table>");
spanResults.innerHTML = sb.toString();
}
</script>
</asp:Content>
In the example, you can fill a credits textbox to filter the returned result set
by credits and also I order the result set by the Title property. The only
interesting part of the example is the doQuery function which creates a
QueryBuilder object, sets it’s filter to the credits in the textbox and sets
the order by property. After the settings of the QueryBuilder properties we
can extract the query through the toString function of the object and use the
query function of the DataService object (the proxy object) with that query.
QueryBuilder Futures
As a part of ASP.NET 4.0 all the Sys.Data namespace is being refactored.
The QueryBuilder is going to be called AdoNetQueryBuilder and to deliver
almost the same functionality like I showed in this post.
Summary
Lets sum up, in the post I explained what is the Sys.Data.QueryBuilder and
I showed how to use it. That object is very useful in order to
create queries without the need to remember how to build the query string
for the data service in order to make a data service query.