August 2007 - Posts
-
" XML Tools team has released the first CTP of the XML Schema Designer - a graphical tool for working with XML Schemas. The XML Schema Designer is integrated with Microsoft Visual Studio 2008 and the XML Editor to enable you to work with XML Schema definition language (XSD) schemas. If you have used the Visual Studio editor or notepad to edit your schemas, consider downloading this CTP and using it for editing your schema files. You can download it from Microsoft Downloads site. This CTP introduces the Schema Explorer - a tool that helps you navigate, search and work with schema sets. You can view a short video of the new functionality here. Here are some of the main features that are included in this CTP. Details Overview An XML Schema can contain multiple XML Schema files. The new XML Schema Designer lets you work with a schema set. That is, when you open an XML Schema file, the XML Schema Designer opens it as a schema set, which includes any included or imported schemas. Tree View The Schema Explorer displays pre-compiled schema set information in a tree structure. The tree structure is organized as follows: - At the top level is the schema set node.
- The second level contains the namespaces.
- The third level contains the files.
- The fourth level contains the global nodes. This can include elements, groups, complex types, simple types, attributes, and attribute groups.
The following is an example of the tree structure: Schema Set Namespace 1 File 1 Global node 1 Namespace 2 File 2 Global node 2 Search The Schema Explorer enables you to search the schema set in the following ways: - Keyword search
- Schema-specific search (for example, "Show All Derived Types")
Filter and Sort Feature The Schema Explorer includes filter and sort options available on the Schema Explorer toolbar. The following filter options are available from the toolbar. The Show Namespaces and Show Schema Files options are selected by default. - Show Namespaces
- Show Schema Files
- Show Compositors (sequence/choice/all)
The following sorting options are available from the toolbar. The default is Sort By Type. - Sort By Type
- Sort by Name
- Sort by Document Order
" This article was copied directly from the XML Team's Weblog.
|
-
I was reading a forum on SA Developer .NET, where I saw an interesting post from Sibusiso. Hi, Im creatting an SSIS project that uses an Data Flow OLE DB Source to read data from an SQL Table and import it into Data Flow OLE DB Destination. but now everytime I run the project it appends all the rows not the new rows. How can I make the application so that it appends only the data from a source table to a destination table. Is there maybe another Data Flow Control that can copy source table to destination and the next time it runs it only copy new rows. your assistance will be highly appreciated. At first glance, I thought there was not a chance but then I had an idea. As it turns out there is a rather complex little SSIS package Scenario A created two tables with the same structure in two different databases, the field are actually irrelevant Assumptions - The tables in both databases have a common unique field which we can use to find missing data.
- We were not allowed to create any form of staging table to identify data already copied and had to directly compare source with destination. This adds a bit of fun.
Goal Copy the data from source to destination where it does not already exist in the destination, i.e. copy the changes only. Solution This is nasty, but it works! Step 1 - Add the data sources In this step we will create a Connection manager to the two databases, and two OLEDB Sources. Then we will sort the data so that we can perform a outer join merge. - Create a package with a single data flow.
- Create three connection managers. I chose to use OLE DB all the way even though .NET Native is more efficient.
- DB1.Source - An OLE DB connection to the source data where all existing data resides
- DB2.Destination - An OLE DB connection to the destination where the partial data resides.
- DB2.DestinationWRITE - Another OLE DB connection to the the same destination where the data resides. This is for the missing inserts.
Note: You cannot read and then write to the same connection and will require two connections in SSIS. - Add an OLE DB Source and rename it to Source Data.
- Edit the Source Data properties and set the following
| Connection Manager | | | OLE DB Connection Manager | DB1.Source | | Data Access Method | Table or View | | TableName | dbo.AllData | | Columns | | | Select all columns from source | | - Add another OLE DB Source and rename it to Target Reader.
- Edit the Target Reader properties and set them to the following:
| Connection Manager | | | OLE DB Connection Manager | DB2.Destination | | Data Access Method | Table or View | | TableName | dbo.ImportedData | | Columns | | | ONLY select the Primary Key fields | | We will be merging the data and will have to sort the two source streams - Add a Sort Data Flow Transformation, and rename it to Source Sort.
- Drag a source output from Source Data to the Source Sort.
- Edit the properties of the Source Sort
- Select the Primary Key to sort
- Pass through ALL other colums
- Add a Sort Data Flow Transformation, and rename it to Target Sort.
- Drag a source output from Target Reader to Target Sort.
- Edit the properties of the Target Sort
- Select the Primary Key to Sort (It should be the only column)
Your data flow should look something like Step 2 - Create an Outer Join to find missing data In this step we will merge the two streams with a left outer join to find missing id's. The merge should yield something like: | id | existId | | 1 | 1 | | 2 | 2 | | 3 | 3 | | 4 | NULL | | 5 | NULL | | 6 | NULL | - Add a Split Data Flow Transformation and rename it to Split.
- Drag a source output from the Source Sort to the Split.
- Add a Merge Join Data Flow Transformation and rename it to Source Left Outer Join Target.
- Drag a source output from Split to the Merge Join. A dialog box will appear and configure as follows:
- Drag a source output from the Target Sort to the Merge Join.
- Edit the properties of the Merge Join. (Note it is an left outer join)
Your data flow should now look something like Step 3 - Filter out missing data only In the previous merge we should have a table with id's and existId's. The objective is to filter out only the id's where exitId is null. | id | existId | | 1 | 1 | | 2 | 2 | | 3 | 3 | | 4 | NULL | | 5 | NULL | | 6 | NULL | - Add a Conditional Split Data Flow Transformation, and rename it to Split Missing Data.
- Drag a source output from the Merge Join to the Split Missing Data.
- Edit the Split Missing Data properties
Your data flow should now look like: Step 4 - Create a merge between the source and missing data In this step, we now have only the missing id's as well as all the source data. A simple merge join from source will suffice. In an earlier step a Split was created, we will merge with that source split. - Add a Merge Join Data Flow Transformation, and rename it to Merge Source with Missing.
- Drag a source output from Split to Merge Source with Missing Merge Join. A dialog box will pop up:
- Drag a source output from Split Missing Data to Merge Source with Missing Join. Configure the dialog:
- Configure the properties of the Merge Source with Missing Merge Join.
Your data flow should look like Step 5 - Update the Target data with the missing data Finally we need to create another connection manager to the target database as we cannot reuse the previous one. It will be in use for retrieving the data. Then we just have to configure a destination. - Add a new connection manger, called DB2.DestinationWrite to point to the same database as the Target Reader.
- Add a OLE DB Destination to the data flow and rename it Target Writer.
- Drag a source output from the Merge Source with Missing Merge join to Target Writer.
- Configure the Target Writer
| Connection Manager | | | OLE DB Connection Manager | DB2.DestinationWRITE | | Data Access Method | Table or View | | TableName | dbo.ImportedData | | Mappings | | | ALL Fields should be mapped!! | | Your final data flow should look like Conclusion Although there are other ways to do this, it is just to prove that SSIS can do it as well.
|
-
Abstract This article will give you the steps required to build a simple Web Part for Windows SharePoint Services using Visual Studio 2005 Introduction Web Parts are simply ASP.NET Server Side Controls that inherit form System.Web.UI.WebControls.WebParts.WebPart. WSS 3.0 fully leverages off all features within the .NET 2 Framework. There is basically two ways to create, test and deploy web parts. The first and hard way is to create a Library assembly and add a class that inherits from WebControls.WebParts.WebPart. Then you need to manually create a .webpart manifest to and import it into SharePoint. There are many blogs on this. I presume you will be like me, and want to do it the quick way. Install WSS 3.0 onto your development box As a developer install WSS 3.0 onto your machine, you do not need to install Microsoft Office SharePoint Services (MOSS) onto your machine unless you will be developing MOSS functionality. WSS Download WSS 3.0 Visual Studio 2005 Extensions This is a small download and adds a few project templates to Visual Studio. Download them from Windows SharePoint Services 3.0 Tools: Visual Studio 2005 Extensions and install them onto your machine. Creating a Web Part - Open Visual Studio 2005
- On the File menu, click New and then Project...
- In the Project Types, select Visual C#, and then select SharePoint.
- In the Templates, select Web Part.
- Specify the name, location and solution name for your Web Part and click OK. The extension will create the Web Part Project with all the necessary references.
- Reference to necessary DLL's
- AssemblyInfo.cs
- Temporary.snk (which you should replace when moving to production)
- A project with the same name as the Web Part.
- Now develop your Web Part as though you would create a Server Side control.
A simple Hello World Web Part using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
namespace HelloWebPart
{
[Guid("c7a1ee3a-b42a-4e62-be4a-7e38c1ded26f")]
public class HelloWebPart : System.Web.UI.WebControls.WebParts.WebPart
{
public HelloWebPart()
{
this.ExportMode = WebPartExportMode.All;
}
protected override void Render(HtmlTextWriter writer)
{
writer.WriteBeginTag("div");
writer.WriteAttribute( "style", "BORDER-RIGHT: #006633 thin solid; PADDING-RIGHT: 8px; "
+ "BORDER-TOP: #006633 thin solid; PADDING-LEFT: 8px; "
+ "PADDING-BOTTOM: 8px; BORDER-LEFT: #006633 thin solid; "
+ "PADDING-TOP: 8px; BORDER-BOTTOM: #006633 thin solid; "
+ "BACKGROUND-COLOR: #66cc66");
writer.RenderBeginTag("div");
writer.WriteFullBeginTag("h1");
writer.Write("Hello, World!");
writer.WriteEndTag("h1");
writer.WriteFullBeginTag("p");
writer.Write("Web part development is simply a server side control.");
writer.WriteEndTag("p");
writer.WriteEndTag("div");
}
}
}
Customising the Web Part solution Package
When you created the Web Part, the project template automatically creates the necessary feature for deployment onto a WSS site. It will thus create the .webpart file for you.
To configure the feature
- Select the Project menu, then choose <projectname> Properties...
- Click the SharePoint Solution tab.
- Expand the Solution
- Expand the Feature
- Select element
- Configure the Solution, Feature and element properties
Build and Deploy the Web Part
Compile and deploy the Web Part
- Select the Build menu, select Build <webpartname>.
- Select the Build menu, select Deploy <webpartname>.
After a few seconds the deploy should succeed.
Add the web part to a page
- Open Internet Exporer and navigate to the home page of your website (or any page you want to place the web part on)
- Select Site Actions menu, Select Edit Page.
- In any zone where you want to add the Web Part, click the Add Web Part hyperlink
- Choose the HelloWebPart Web Part that you want to add to your page.
- Click the Add button
- Click the Exit Edit Mode of the page
Done
Have fun, happy coding!!!
|
-
As a web developer, you should be on the SharePoint band wagon; if not do it now!!! This install in this article is the simplest, quickest way to get up and running; however, it is not a full farm install. It is enough for you to get up and running to start developing against WSS. Step 1: Review System Requirements This may hurt many of you - Windows Server 2003 Service Pack 1
- Microsoft .NET Framework 3.0
- SQL Server 2005 or SQL Server Express 2005, If you choose a basic install SQL 2005 Embedded Edition will be installed
Not running Server 2003? Create a Virtual PC for yourself an get playing!! Step 2: Downloading Requirements - Download WSS 3.0 from here (78Mb).
- Download .NET Framework 3.0 from here (51Mb).
- Download SQL Express 2005 from
Step 3: Create some service accounts - Select Start, then choose the Administrative Tools menu, then choose Computer Management control panel applet.
- Expand Local users and Groups.
- Click Users.
- Right-Click users, and then choose new User.
- Complete the dialgog
- Click Create.
Step 4: Install the prerequisites The sharepoint.exe installer is a bit of a pain if you do not have the right prerequisites, so install them - Install SQL Express 2005
- Install .NET Framework 3.0
Step 3: Install WSS 3.0 - Double-click the SharePoint.exe program file on your hard disk to start the Setup program.
- Click Run if you trust Microsoft's download :P
- Read and accept the terms of the agreement. Click Continue.
- Click Advanced as this is the will allow you to configure you site to a local instance of SQL and set up accounts correctly.
Note: If you choose the basic option, a stock standard next, next install will occur. However this is limiting as it will install SQL SSEE in another instance and create a site for you. As a developer, I am sure you would like to get to know the product a bit better. - Click the Server Type tab, choose Web Font End.
- Choose the Feedback tab, make your choice.
- Click Install Now and take a few minutes break while this installs minutes.
- When done I suggest you check the Run Configuration Wizard. and click Close.
Well done, you have managed to copy the WSS software onto your Server, sadly no portal yet! All the setup has done is copy all the SharePoint files into the C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12 folder, aka The 12 hive. Step 4 - Run the Configuration windows - Start the configuration wizard if not already started.
- The Install Process will stop and restart several services, click Yes.
- Choose No, I want to create a new server farm and then click Next.
- Type the details where the configuration database should be created on SQL and what account SharePoint should use to access it.
e.g. Database server: Miami Database name: SharePoint_Config Username: .\SharePointService Password: Pa$$w0rd - Click Next.
- You may wish to change the Administration site Portal and authentication provider, click Next.
- In the Completing the SharePoint Product and Technologies Configuration Wizard, click Next.
Note: Make a note somewhere of the Central Administration URL. - Go have another cup of coffee while the server is created, this takes some time.
- Your browser should pop up with the Central Administration Site.
We are not done yet, we have a server up and running but no site. Step 5: Create a site collection and a SharePoint site Create a new web application - In the SharePoint Central Administration Web site, on the Application Management page
- I the SharePoint Web Application Management section, click Create or extend Web application.
- On the Create or Extend Web Application page, in the Adding a SharePoint Web Application section, click Create a new Web application.
- On the Create New Web Application page, in the IIS Web Site section, you can configure the settings for your new Web application.
- To choose to use an existing Web site, select Use an existing Web site, and specify the Web site on which to install your new Web application by selecting it from the drop-down menu.
- To choose to create a new Web site, select Create a new IIS Web site, and type the name of the Web site in the Description box.
- In the Port box, type the port number you want to use to access the Web application. If you are creating a new Web site, this field is populated with a suggested port number. If you are using an existing Web site, this field is populated with the current port number.
- In the Host Header box, type the URL you want to use to access the Web application. This is an optional field.
- In the Path box, type the path to the site directory on the server. If you are creating a new Web site, this field is populated with a suggested path. If you are using an existing Web site, this field is populated with the current path.
- In the Security Configuration section, configure authentication and encryption for your Web application.
- In the Authentication Provider section, choose either Negotiate (Kerberos) or NTLM
- In the Allow Anonymous section, choose Yes or No. If you choose to allow anonymous access, this enables anonymous access to the Web site by using the computer-specific anonymous access account (that is, IUSR_<computername>).
- In the Use Secure Sockets Layer (SSL) section, select Yes or No. If you choose to enable SSL for the Web site, you must configure SSL by requesting and installing an SSL certificate.
- In the Load Balanced URL section, type the URL for the domain name for all sites that users will access in this Web application. This URL domain will be used in all links shown on pages within the Web application. By default, the box is populated with the current server name and port.
- In the Application Pool section, choose whether to use an existing application pool or create a new application pool for this Web application. To use an existing application pool, select Use existing application pool. Then select the application pool you want to use from the drop-down menu.
- To create a new application pool, select Create a new application pool.
- In the Application pool name box, type the name of the new application pool, or keep the default name.
- In the Select a security account for this application pool section, select Predefined to use an existing application pool security account, and then select the security account from the drop-down menu.
- Select Configurable to use an account that is not currently being used as a security account for an existing application pool. In the User name box, type the user name of the account you want to use, and type the password for the account in the Password box.
- In the Reset Internet Information Services section, choose whether to allow Microsoft Windows SharePoint Services to restart IIS on other farm servers. The local server must be restarted manually for the process to finish. If this option is not selected and you have more than one server in the farm, you must wait until the IIS Web site is created on all servers and then run iisreset/noforce on each Web server. The new IIS site is not usable until that action is completed. The choices are unavailable if your farm only contains a single server.
- In the Database Name and Authentication section, choose the database server, database name, and authentication method for your new Web application.
Database Server Type the name of the database server and Microsoft SQL Server instance you want to use in the format <SERVERNAME\instance>. You can also use the default entry. Database Name Type the name of the database, or use the default entry. Database Authentication Choose whether to use Windows authentication (recommended) or SQL authentication. - Click OK to create the new Web application, or click Cancel to cancel the process and return to the Application Management page.
- Open up the command prompt, and type iisreset /noforce
Well done, you have set up IIS and SharePoint! However you still do not have a web site. Step 6: Create a Site collection and top level site Create a site collection - On the SharePoint Central Administration home page, click the Application Management tab on the top link bar.
- On the Application Management page, in the SharePoint Site Management section, click Create site collection.
- On the Create Site Collection page, in the Web Application section, select a Web application to host the site collection from the Web Application drop-down list.
- In the Title and Description section, type a title and description for the site collection.
- In the Web Site Address section, select a URL type (personal or sites), and then type a URL for the site collection.
- In the Template Selection section, select a template from the tabbed template control.
- In the Primary Site Collection Administrator section, specify the user account for the user you want to be the primary administrator for the site collection. You can also browse for the user account by clicking the Book icon to the right of the text box. You can check the user account by clicking the Check Names icon to the right of the text box.
- Optionally, in the Secondary Site Collection Administrator section, specify the user account for the user you want to be the secondary administrator for the site collection. You can also browse for the user account by clicking the Book icon to the right of the text box. You can check the user account by clicking the Check Names icon to the right of the text box.
- Click Create to create the site collection.
Step 7: View your site - Navigate to your site URL, http://localhost.

|
-
Last night I thought I would write a blog on installing SharePoint for development purposes. As I never have used the Basic install option in WSS, I thought I would give it a go. It was pretty much a next, next, finish install without asking where to put the database. Ouch!!! SQL 2005 Embedded Edition is installed (yeah, yeah rtfm). To my wonderful delight, uninstalling WSS does not uninstall SSEE and there is nothing in the Control panels, add and remove programs. After a while I found a blog that shows how. In summary - Run Regedit.exe
- Navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
- Find "Microsoft SQL 2005 embedded Edition"
- You can do this by clicking on every GUID till you find it
- Or do a simple Edit, Find and search for "Embedded".
- In the right pane look for the UninstallString and copy this to your clipboard
- Open up the command prompt, Start, Run, cmd
- Paste the UninstallString from you clipboard
- At the end of the line type the following CALLERID=OCSETUP.EXE
Your command should look something like : MsiExec.exe /X{BDD79957-5801-4A2D-B09E-852E7FA64D01} CALLERID=OCSETUP.EXE - Run it!
The location for SSEE is %windir%\SYSMSI\SSEE, you may want to clean this out. Note: I assume you know the impact of uninstalling a SQL instance. Don't complain if you accedently removed and instance that is being used.
|
-
This post provides a small tutorial on the underlying mechanism of how AJAX works. Obviously it would be stupid to attempt to write your own implementation of AJAX, however it is useful to understand what is happening behind the scenes.
What does an Asynchronous JavaSript and XML request actually do? Traditional HTML web pages typically request a page from the server and server returns a HTML response stream. The browser then displays this in the window, however during the display it will also retrieve included items such as CSS files and images an display it. Web pages today do pretty much the same thing, however many pages are dynamic and are rendered via code that connects to back-end data sources. Also, these pages are becoming increasingly more complex with more information displayed with a rich graphical content. However, each time the page is requested the browser does a full page refresh, which is annoying to users due to: - There is a brief flicker on the screen as the browser redraws the entire page.
- The scroll position on page is lost causing the user to scroll down to where they were originally.
- Unnecessary bandwidth is consumed to retrieve the full page when only a small area is changed.
- Interface is cumbersome as it requires a change to be made and a post/submit request to server and does not give intuitive use as windows base form does.
Overall, the users perception of the system is degraded. With AJAX, the entire page does not need to be downloaded, and only a small portion of the page that changed needs to be updated. This has many benefits as the browser is less intense on bandwidth, user focus and context position on the page does not change. Information on the page can be updated based on input without having to resubmit the page. How does this work Over the past few years browsers have matured to include methods to perform an asynchronous call to the server without updating the entire page. This however does require the browser to support JavaScript and the Document Object Model. All modern day browsers do support these features: Below is a short explanation of what happens - The user requests a web page in the normal manner.
- The server renders the full page and returns the HTML to the browser. The browser clears the window and displays the HTML. The returned data will include
- HTML
- CSS
- JavaScript that will subscribe to DOM events, e.g. a click or change to an HTML element.
- The user will interact with the page and trigger of the event
- When the event handler code executes it will perform and XmlHttpRequest to the server on a specified URL.
- The server will typically process this request returning either data in some format (XML, JSON or other). It may also return the partial HTML.
- The response on the browser will fire another function which should handle the incoming data. This function will change the data into HTML, find a HTML element on the page and then insert the data into this element.
Sample code This sample code will simply place a button on a page, when the button is clicked a request will be made to the server to update a date and time. In the first mechanism, I will use traditional ASP.NET programming style and when running the page you will notice the page refresh. In the second sample, I will use the XmlHttpRequest and do a partial page. When testing the solution, notice the difference in screen refresh and browser scroll bar positioning. - Create a new ASP.NET web site application from visual studio
Traditional Page In the traditional we will place a service side event on the button to update the date and time. A full postback will be fired. - Create a web form traditional.aspx
- Copy the following code into the page
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
labTime.Text = DateTime.Now.ToString();
}
protected void cmdUpdateTime_Click(object sender, EventArgs e)
{
labTime.Text = DateTime.Now.ToString();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Traditional Postback</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="lipsum">
<h1>Asynchronous update</h1>
<p>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Morbi ac risus lacinia
velit ullamcorper auctor. Integer placerat. Phasellus iaculis laoreet sem. Aliquam
nulla dui, varius sit amet, facilisis id, sodales sed, dui. Sed leo tellus, interdum
et, sollicitudin commodo, feugiat ac, nulla. Integer purus tortor, porttitor sit
amet, vulputate lobortis, rhoncus sed, urna. Fusce ut est. Sed sed erat. Nunc pretium
turpis a lacus. In pharetra bibendum metus. Nunc eu sem. Praesent vitae mauris et
lectus placerat tincidunt. Quisque euismod adipiscing enim. Curabitur tempus posuere
orci. Nulla lectus lectus, condimentum viverra, vehicula vitae, adipiscing ac, lacus.
Vestibulum et justo at nisl placerat dictum. Vivamus id massa. Sed rhoncus massa.
Morbi dapibus, diam sit amet iaculis molestie, enim enim hendrerit augue, a tincidunt
felis mi non elit.
</p>
<p>
Sed mattis eros in libero. Nulla pulvinar nisl et risus. Nunc tristique purus et
erat faucibus blandit. Phasellus varius diam nec mauris. Ut tempor. Aliquam bibendum.
Nulla facilisi. Suspendisse dignissim faucibus dui. In interdum. Mauris erat dui,
interdum volutpat, hendrerit ac, viverra quis, dolor. Etiam ligula. Pellentesque
condimentum blandit enim. Donec mattis, lectus id aliquam rutrum, arcu tellus semper
sapien, ac tempor nisl nibh eu ante. Pellentesque nunc pede, malesuada non, aliquet
sit amet, luctus ut, ligula. Nullam consectetuer ipsum at ipsum. Cras dictum lacus.
Mauris ut quam lobortis metus tempor consequat.
</p>
<p>
Morbi urna. Praesent laoreet tincidunt sapien. Ut lacus pede, tincidunt a, ullamcorper
at, scelerisque quis, ipsum. Ut vel tellus nec ipsum vulputate euismod. Suspendisse
gravida eleifend nisi. Mauris blandit sapien a est facilisis vestibulum. Sed consequat
vulputate quam. Morbi nonummy. Etiam nisl neque, lacinia ac, laoreet sit amet, dictum
nec, dolor. Sed viverra molestie libero. Pellentesque varius. Cras et quam. Maecenas
sollicitudin.
</p>
<p>
Vivamus ut lorem a enim vestibulum imperdiet. Class aptent taciti sociosqu ad litora
torquent per conubia nostra, per inceptos hymenaeos. Morbi nisl. Praesent tempus
nisl a quam luctus tincidunt. Cras dapibus egestas diam. Vestibulum quam augue,
tincidunt id, volutpat et, pellentesque eget, massa. Proin at enim sit amet nunc
porttitor dapibus. Suspendisse varius leo at sapien. In ac dui. Sed nibh libero,
posuere id, dignissim sed, ullamcorper eget, sapien. Praesent eu orci. Mauris nisi.
Integer vitae justo. Nam diam magna, ultrices in, hendrerit tempus, elementum et,
arcu. Proin purus orci, vestibulum sed, posuere eu, convallis sed, quam. Quisque
cursus, leo in tincidunt viverra, mauris augue mollis ipsum, tempor rhoncus velit
diam et urna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam
feugiat purus eget ipsum. Aenean vehicula, tellus sit amet consectetuer imperdiet,
urna orci accumsan libero, in gravida arcu urna non nibh. Suspendisse vestibulum
mi et turpis faucibus convallis.
</p>
<p>
Aenean iaculis tellus quis magna. Nullam vulputate mollis elit. Praesent vehicula
malesuada elit. Nulla vel turpis vel lorem iaculis condimentum. Suspendisse ut arcu
at lacus laoreet imperdiet. Donec tempus, est eleifend eleifend venenatis, neque
arcu sollicitudin lectus, sed molestie odio dolor quis nisi. Nunc sem orci, venenatis
id, mollis sed, condimentum congue, orci. Vivamus sit amet tortor ut nisi scelerisque
facilisis. Etiam vitae risus quis ligula fringilla dictum. Nunc ligula. Donec luctus
fermentum lectus. Phasellus elit. Sed semper, leo ut tristique interdum, pede enim
porta lacus, nec interdum velit turpis id purus. Suspendisse sollicitudin. Nunc
ultricies dolor at magna. Cras cursus justo eget enim.
</p>
<hr />
<p>
<asp:Button ID="cmdUpdateTime" runat="server" Text="Update time" OnClick="cmdUpdateTime_Click" />
<asp:Label ID="labTime" runat="server" Text="[TIME]"></asp:Label></p>
</div>
</div>
</form>
</body>
</html>
- Run the project and view the web page. Scroll down and click the update button. Notice how the page is fully refreshed and position of scroll bar is lost.
XmlHttpRequest example
This page is very similar to the traditional page, however I have used a standard input button with a javascript event. When the button is clicked an XmlHttpRequest will be made to the server.
- Add a new web form to the project
- Copy the code below into the page
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["UpdateTime"] != null)
{
Response.Write(DateTime.Now.ToString());
Response.Flush();
Response.End();
}
labTime.Text = DateTime.Now.ToString();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="lipsum">
<h1>Asynchronous update</h1>
<p>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Morbi ac risus lacinia
velit ullamcorper auctor. Integer placerat. Phasellus iaculis laoreet sem. Aliquam
nulla dui, varius sit amet, facilisis id, sodales sed, dui. Sed leo tellus, interdum
et, sollicitudin commodo, feugiat ac, nulla. Integer purus tortor, porttitor sit
amet, vulputate lobortis, rhoncus sed, urna. Fusce ut est. Sed sed erat. Nunc pretium
turpis a lacus. In pharetra bibendum metus. Nunc eu sem. Praesent vitae mauris et
lectus placerat tincidunt. Quisque euismod adipiscing enim. Curabitur tempus posuere
orci. Nulla lectus lectus, condimentum viverra, vehicula vitae, adipiscing ac, lacus.
Vestibulum et justo at nisl placerat dictum. Vivamus id massa. Sed rhoncus massa.
Morbi dapibus, diam sit amet iaculis molestie, enim enim hendrerit augue, a tincidunt
felis mi non elit.
</p>
<p>
Sed mattis eros in libero. Nulla pulvinar nisl et risus. Nunc tristique purus et
erat faucibus blandit. Phasellus varius diam nec mauris. Ut tempor. Aliquam bibendum.
Nulla facilisi. Suspendisse dignissim faucibus dui. In interdum. Mauris erat dui,
interdum volutpat, hendrerit ac, viverra quis, dolor. Etiam ligula. Pellentesque
condimentum blandit enim. Donec mattis, lectus id aliquam rutrum, arcu tellus semper
sapien, ac tempor nisl nibh eu ante. Pellentesque nunc pede, malesuada non, aliquet
sit amet, luctus ut, ligula. Nullam consectetuer ipsum at ipsum. Cras dictum lacus.
Mauris ut quam lobortis metus tempor consequat.
</p>
<p>
Morbi urna. Praesent laoreet tincidunt sapien. Ut lacus pede, tincidunt a, ullamcorper
at, scelerisque quis, ipsum. Ut vel tellus nec ipsum vulputate euismod. Suspendisse
gravida eleifend nisi. Mauris blandit sapien a est facilisis vestibulum. Sed consequat
vulputate quam. Morbi nonummy. Etiam nisl neque, lacinia ac, laoreet sit amet, dictum
nec, dolor. Sed viverra molestie libero. Pellentesque varius. Cras et quam. Maecenas
sollicitudin.
</p>
<p>
Vivamus ut lorem a enim vestibulum imperdiet. Class aptent taciti sociosqu ad litora
torquent per conubia nostra, per inceptos hymenaeos. Morbi nisl. Praesent tempus
nisl a quam luctus tincidunt. Cras dapibus egestas diam. Vestibulum quam augue,
tincidunt id, volutpat et, pellentesque eget, massa. Proin at enim sit amet nunc
porttitor dapibus. Suspendisse varius leo at sapien. In ac dui. Sed nibh libero,
posuere id, dignissim sed, ullamcorper eget, sapien. Praesent eu orci. Mauris nisi.
Integer vitae justo. Nam diam magna, ultrices in, hendrerit tempus, elementum et,
arcu. Proin purus orci, vestibulum sed, posuere eu, convallis sed, quam. Quisque
cursus, leo in tincidunt viverra, mauris augue mollis ipsum, tempor rhoncus velit
diam et urna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam
feugiat purus eget ipsum. Aenean vehicula, tellus sit amet consectetuer imperdiet,
urna orci accumsan libero, in gravida arcu urna non nibh. Suspendisse vestibulum
mi et turpis faucibus convallis.
</p>
<p>
Aenean iaculis tellus quis magna. Nullam vulputate mollis elit. Praesent vehicula
malesuada elit. Nulla vel turpis vel lorem iaculis condimentum. Suspendisse ut arcu
at lacus laoreet imperdiet. Donec tempus, est eleifend eleifend venenatis, neque
arcu sollicitudin lectus, sed molestie odio dolor quis nisi. Nunc sem orci, venenatis
id, mollis sed, condimentum congue, orci. Vivamus sit amet tortor ut nisi scelerisque
facilisis. Etiam vitae risus quis ligula fringilla dictum. Nunc ligula. Donec luctus
fermentum lectus. Phasellus elit. Sed semper, leo ut tristique interdum, pede enim
porta lacus, nec interdum velit turpis id purus. Suspendisse sollicitudin. Nunc
ultricies dolor at magna. Cras cursus justo eget enim.
</p>
<hr />
<p>
<input id="cmdUpdateTime" type="button" value="Update Time" language="javascript" onclick="return cmdUpdateTime_onclick()" />
<asp:Label ID="labTime" runat="server" Text="[TIME]"></asp:Label></p>
</div>
</div>
</form>
</body>
<script language="javascript">
function cmdUpdateTime_onclick() {
if (window.XMLHttpRequest){
var request = new XMLHttpRequest();
}else{
var request = new ActiveXObject("MSXML2.XMLHTTP.3.0");
}
request.open("POST", "Async.aspx?UpdateTime=true", false);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.onreadystatechange = function(){
if (request.readyState == 4 && request.status == 200) {
if (request.responseText){
var labTime = document.getElementById("labTime") ;
labTime.innerHTML = request.responseText;
}
}
}
request.send(null);
}
</script>
</html>
- Run the project and view the asynchronous page. Notice how the date and time is updated without causing a full screen refresh.
Explanation of JavaScript codefunction cmdUpdateTime_onclick() {
- This defines a function that the onclick event of the button fires when the button is clicked
if (window.XMLHttpRequest){
var request = new XMLHttpRequest();
}else{
var request = new ActiveXObject("MSXML2.XMLHTTP.3.0");
}
- XMLHttpRequest is not in all browser versions, and older browsers need to load the XML COM object.
request.open("POST", "Async.aspx?UpdateTime=true", false);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
- This bit of code defines that the request will do a post to the Async.asp web page passing in a query string so we can identify it as a callback. Look in the Page_Load event of the aspx.
- Secondly we indicate that the data type is a normal HTTP POST.
request.onreadystatechange = function(){
- This line of code defines a function that will be called when the response is returned to the browser from the server.
if (request.readyState == 4 && request.status == 200) {
- The readyState==4 indicates that the request has completed and is ready to be processed by the client.
- The status == 200 is a web success status
if (request.responseText){
var labTime = document.getElementById("labTime") ;
labTime.innerHTML = request.responseText;
}
request.send(null);
- The send method initiates communication
Additional comments
- This article is only to demonstrate how AJAX works in the background.
- The design of this sample is by no ways intended for commercial applications.
|
-
When looking at your typical business data application, there are different groupings of data each with their own set of characteristics. These groupings also have their own set of design requirements. The common data groupings include: - Current active data
- Historical data
- Archived data
- Static data
- Master data
- Aggregated / summarised data
- Reporting data
- Audit information
Why is this important in design? These different groupings will affect how the data is stored, retrieved and managed. The different data groupings also affect topics of availability, archiving strategies and backup / restore strategies. Performance of the data store can be severely impacted by a bad data design. The following topics will discuss each data category Current active data Characteristics - The current active data in your database is the data that is needed to do business, to trade and "make money". This is the heart of any OLTP system and vital to the day-to-day business operations. It thus contains the day-to-day transactional information.
- This data typically is small in size; "small" is a relative term and depends on your organization, in most databases it is between 1-15% of all data.
Design goals - Keep this data small for insert, update and delete performance. The database referential integrity on these tables are paramount and should be thoroughly implemented, tested and maintained as this is the source of data; data corruption must be thus avoided.
- Few indexes for transactional processing and front end display. Indexes should be kept to a minimum for fast insert \ updates and deletes, however they should assist in finding information from a front-end.
- This data should not be directly used by any OLAP or reporting tools, it should rather be batch migrated to an OLAP database, consolidated and summarised for reporting. This will reduce lock contention on this active data allowing transactional processing systems to work faster. Front-end applications will processes new transactions and possibly use other information in this category, current transaction forms (reports) for customer transactions and business processes can however be printed.
- Once transactional data in this area is concluded and the business transaction complete, it should be moved to historical data as it will never change again. It is in the companies history. The migration should take place through nightly, weekly or monthly batch jobs. Size vs Performance vs High Availability should be considered in determining the time.
Historical data Characteristics - An data entered into the database is automatically deemed historical and should not be deleted but rather flagged and moved to history when no longer active. This data represents historical, old or concluded business transactions and trades.
- This data is very important for reporting, summarization and historical analysis within any company and should be protected at a transactional level.
- As the system ages over time, this data portion becomes large and bulk of the database.
- The data within this group only changes on an infrequent batch basis, e.g. month-end.
Design goals - Historical data should portray a day within the business's life and any legal documentation should be able to be recreated as it was on that day, e.g. You should be able to reprint an invoice of 5 years ago with all details as of the date; changes to product names, client address should not reflect on historical data. There could be serious legal ramifications if the system does not cater for this.
- As this data is large and only changes on a batch basis, it may not be necessary to back this data up daily which could drastically reduce backup times and backup space needed. Note that when data is migrated into history, a full backup should be done on the history data.
- Historical data is typically required to be kept through governance and legal requirements within the country or industry. An example of the South African company's act requires historical data to be kept for 5 years.
- The life span of the value of the data should be determined and once it is of "no use" to the business and past legal requirements, you may wish to archive this data.
- You may want to consider filegroup and table partitioning of this data to to increase performance, e.g. Sales2007, Sales2006, Sales2005, Sales 2004, SalesOld.
Archived data Characteristics - Historical data that is no longer of use to the business and past any legal and legislative requirements can be extracted out of the database to free up space.
Design goals - Archive data should be extract when it is no longer needed from the historical pool and then permanently archive to an off-line or near line solution.
- A single record can be inserted into the database that summarises the historical transactions. E.g. all invoices sumerised into a single invoice for an entire month to reflect sales totals.
- You should comply to legislative demands
- You should have mechanisms in place to re-import data should there be a need from the users. However you should evaluate these archiving mechanisms over time as these technologies do expire and become redundant.
- Archiving tools should evaluated as newer versions of tools may be incompatible with older versions thus preventing archives being restored. E.g. SQL 2005 cannot restore a SQL 6.5 database backup
Static data Characteristics - Most systems have tables with design time tables that do not change over time. The data in the tables are normally hard-coded into the applications, however provide a data referential integrity checks.
- This data only changes when application versions change and does not have any insert, update or delete requirement from a front-end.
- Normally this data is core to the operation of the database.
Design goals - Use static data when needed to enhance data integrity.
- Keep this data small.
Master data Characteristics - Master data is system or lookup information that is added to the system to perform transactions.
- The data is seldom changed and modified on an ad-hoc basis when needed.
- The master data may contain system runtime configuration settings.
- The data in these tables are normally small and easy to backup.
- Examples may include status codes, configuration, list of countries, regions and branch office names.
- Normally used to enforce database referential integrity.
Design goals - The data within these tables should be edited through user front-ends
- Data should be backed up regularly as on does not know when it will change.
- Indexes should be placed for read performance.
Aggregated / Summerised data Characteristics - This data should not be part of a transaction processing as it is used for reporting.
- When data is imported from the transaction system, the data is totaled or averaged ready for reports. The reports should run faster as the data is already summerised.
- The data size will be smaller than the historical transactional data as it is much smaller.
Design goals - Use summerised tables as much as possible in OLAP solutions as reports will run faster.
- Update the data through batch routines that run daily, weekly or monthly.
- The data should be able to be rebuilt from historical data.
- Design these tables with reports in mind.
Reports Characteristics - All systems have a need to report on business transactions with aggregation. The reports could be from lists to complex summerised and aggregated data.
- Lots of indexes may reside on a single table for performance reasons. The size of the indexes relative to the data may be large.
- Reports do not typically include up to the millisecond transactional details and for most companies a overnight update is more than satisfactory. Sensitive market data reports may be batch updated on a regular basis.
Design goals - Do not draw reports on the transactional data as it will introduce large lock contention on both the reports and the transactional processing system. The risk of deadlocks is greatly increased when third party and internal systems query the same data.
- Indexes should be optimized for report performance and several indexes should be created.
- The report data should be updated through batch jobs on a daily, weekly or monthly basis.
- Really look at the business drive behind the frequency of when the report should be updated. In many cases daily or weekly is more than satisfactory.
Audit data Characteristics - Audit data records the process / user and time and change to data and is vital in any business.
- Audit data does not necessarily need to be kept for long periods of times as issues normally arise soon after the transaction.
- The audit data is normally archived on a quarterly, half yearly or annual basis.
- There is no need to place performance indexes on this data as it should not normally be used.
Design goals - One should be able to trace every change to the data to form a migration path.
- Archived audit information should be restorable.
- Keep this data to minimum as it does impact insert, update and delete times.
- Indexes should be small and kept to a minimum.
General You do not necessarily have to create different databases for each type of data, however creation of file groups, schemas should do the trick. What is important though is that the data is logically segmented from an application perspective. Applications should also be aware that some historical data may not be available online and may require a manual process to pull it back. These applications should not presume all tables will be available, especially historical and archived data. In database design: - Look at backup / restore times
- Look at disaster recoverability
- Look at high availability
- focus on data integrity
Data retention should be considered based on the companies needs. Audit information for example may not be required for long periods as a typical who-one-it may surface within a month or two while the transaction is still live. Once it is deemed historical, archive information may be archived. Regardless of size of database or usage, common good practices should be implemented. Too often "small" systems are the important ones and heavily relied on. In my journeys if have seen the it's only a small system being used over many years turning to be quite a large database.
|
-
The term "Architecture" is often used loosely to describe the process of design using technology, where in fact this is far from architecture. Enterprise Architecture is the art designing and implementing a technical strategy that delivers on the business strategy. Architecture allows business to grow, adjust and react quickly to the marketplace using information technology. Architecture is a strategy, a big picture view of the technical needs of a organisation, both current and future. Architecture realises the good and bad within the organisation and focuses on enhancing the good and eradicating the bad. In doing this the primary objective is to allow business to deliver on its strategy, normally increased market share and profitability. Architecture needs to ensure that business gets a return on investment. Disciplines of architecture Architecture does not a single set of activities, but deals with many larger disciplines and practices within the field, the next few headings will introduce each discipline Information Architecture The discipline Information architecture - identify important information within the organisation.
- describe the information through metadata.
- describe the source and destination needs of the information.
- categorize the information.
- identify ownership of the information.
- identify duplication and variations in the information.
- apply legal requirements to the information
- sensitivity of information
- search requirements
The "information" does not only pertain to system data, it includes forms, processes, files, mail, configuration, management. Data architecture Data architecture will - segment information into logical categories
- storage and retrieval of information
- archiving and disaster recovery
- retrieval performance
- integrity of data
- data processing machanisms
- Extract Transform Load process
- Partner dependencies
- search mechanisms
Security architecture Security architecture focuses on - Authentication
- Authorization
- Structure of organization towards technology mechanisms
- Threats such as
- Hacking
- Denial of service
- Phishing
- Viruses and worms
- Copying
- Physical and logical access
- Encryption and decryption
- Data transportation security
- Public and private restrictions
Communication architecture Communication architecture addresses different communications areas the organisation has with its customers, suppliers and partners through - Voice
- E-Mail
- Fax
- Paper
- Others
Other disciplines are normally applied to architecture, such as security, disaster recovery, infrastructure Disaster and recovery architectures This discipline attemts to minimise the impact on business should there be a disaster - Risk management of disaster events
- Disaster recovery sites
- Data protection within the DR environment
- Software failure management processes
- Hardware failure processes
- Data corruption
Integration architecture Defines how systems communicate - Sharing of information
- system-to-system
- partner
- supplier
- customer
- warehousing
- Reduction in data duplication
- Business process management
- Communication mechanisms
- Data formats for integration
- Transport mechanisms
- Workflow usage within integration
- Security of integration
- Service level agreements and timings
- Fall out processes
- Extract, Transform and Load processes.
Workflow architecture A workflow architecture attempts to: - define business process mapping to technical processes
- system-to-system processes
- system processes
- business-processes
- human workflow on front-ends
- deliver on business processes
- automate processes where possible
- identify to business poor processes that do not technology work
- assist in re-engineering slow processes or inefficient processes
- automate processes
- application of service level agreements on processes.
Collaboration architecture Collaboration looks at the users desktop tools and applications to find most efficient toolset's, i.e. the right tool for the job. - Front-end reuse
- Application integration, e.g. to word, excel, outlook
- Desktop toolset's
- Human Interface Workflows
Infrastructure architecture An infrastructure architecture looks at the physical technology needs of an organisation, a few areas are identified below - High availability
- Voice communication
- Networking
- Server farms
- Backbons and communication paths
- Public zones
- Private zones
- Branch, national and international communications
- Security
- Load balancing
- Redirection
Application architecture Application architecture is one of the fundamental architectures that attempts to match business need with current systems - Identification of applications within the organisation
- Dependancy of applications
- Ownership of applications
- Functionality provided by applications
- Duplication of functionality
- Shared information and data
- Stability, performance and importance of systems to company
- Functionality vs Business need
- Gap management
- Development vs purchasing systems
Software architecture - Software design
- Reusability
- Framework design
- Technology usage
- Usage of software patterns
Component architecture The component architecture will assist software architects to - reuse components
- component accessibility
- structure of components
- standardisation
- application structures
Governance Architecture will implement a set of policies, procedures and systems in place to attempt to assist in the management of all of the above architectures. These will be monitored and validated that Summary Architecture is not a small subject and involves a big-picture view of the organisation. Over then next few weeks, months I will start describing different areas within architecture. Did this help? What focus areas would you like clarification on?
|
-
The versatile proxy pattern simply provides an interface or "middle man" access to another object. When the proxy is accessed by the client, the proxy acts on behalf of the client to retrieve or execute methods on the object. What the Proxy Pattern solves. The proxy design pattern solves many common business problems: - Cache proxy. The client requests an object from the proxy. The proxy checks a local cache and returns the object if it exists in the cache. If the object does not exist in the cache, the proxy forwards the request to the real subject which returns the object. The proxy then caches the object for future requests and the forwards it to the client.
- Remote proxy. The client executes or requests an object from the proxy. The proxy then forwards the request to another service or application either running on the local or a remote machine to get the object. The proxy then returns this to the client.
- Access Protection proxy. The client requests an object from a proxy. The proxy authorises the client and either denies access or executes or returns the object from the real proxy.
- Firewall proxy. This is a specialised Access Protection Proxy that protects targets from clients and vice versa.
- Virtual proxy. The client requests a potentially large or expensive object creation from the proxy. The proxy however will forward the request to create the object when it is really needed, thus lazy creation is used.
- Copy-on-Write proxy. The copy on write proxy will retrieve an object for a client. When the object is changed by the client the proxy will clone or create a copy of the object. This proxy prevents the unnecessary copying of objects unless really needed.
- Synchronisation proxy. The proxy provides concurrent access to real objects in a multi user or threaded application.
- Reference proxy. The reference proxy performs actions such as reference or usage counting on an object.
- Audit proxy. All requests through the proxy are audited in log files.
UML Diagram Participants | Client | The client initiates a requests or executes a method on the proxy. | | Proxy | - The proxy provides an identical interface as the real subject.
- The proxy maintains a reference to the real subject.
- When the proxy is accessed it forwards the request to the real subject. The forwarding may be subject to rules such as
- Caching
- Access control
- Synchronisation
- Lazy creation
- Remote access
| | Subject | The subject defines a common interface on the Proxy and the real subject. Thus the client is unaware that it is using a proxy. | | Real Subject | Defines the real object that the proxy access on behalf of the cleint | Sample C#namespace Brett.Patterns.GangOfFour.Command.Structural
{
using System;
/// <summary>
/// The client application that will execute a request through
/// the proxy to the real subject
/// </summary>
class Program
{
static void Main(string[] args)
{
// Creates an instance of a proxy. It is important to note
// That the client stores the Proxy as the interface and thus
// is unaware of the proxy.
Subject subject = new Proxy();
// Execute the subject request
subject.Request();
}
}
/// <summary>
/// The common interface that defines the subject on both the
/// Proxy and the real subject.
/// </summary>
interface Subject
{
void Request();
}
/// <summary>
/// The proxy will be used by the client and forward the request to
/// the client. This proxy implements a lazy creation of the real subject.
/// </summary>
class Proxy : Subject
{
/// <summary>
/// Stores a reference to the real subject
/// </summary>
Subject _realSubject = null;
/// <summary>
/// The proxy version of the request which could implement access
/// control, caching, lazy creation and more.
/// </summary>
public void Request()
{
// Lazy creation of the real subject.
if (_realSubject == null)
{
Console.WriteLine("Proxy crates real subject.");
_realSubject = new RealSubject();
}
// Forwards request to real subject.
Console.WriteLine("Proxy forwards request to real subject");
_realSubject.Request();
}
}
/// <summary>
/// The real subject defines the actual work to be done
/// </summary>
class RealSubject : Subject
{
/// <summary>
/// Performs the actual task
/// </summary>
public void Request()
{
Console.WriteLine("RealSubject.Request called.");
}
}
}
|
-
Definition The Chain-of-Responsibility pattern is a design pattern which is commonly used when a command needs to be passed to a sequence of tasks. The command is then passed from one handler to the next handler thus forming a well defined chain of tasks. What is it supposed to solve The chain of responsibility is a powerful pattern which can be used in different business scenarios - Sequence commands
- Make decisions within commands whether to continue
- Responsibility escalation
UML Diagram Participants | Client | The client instantiate the the first item in the chain of command and starts the execution of the chain. | | Handler | Defines an interface for concrete handlers and optionally sets the next successor | | Concrete Handler | Performs the task of the concrete handler Determines if it should call the successor based on business logic Optionally forwards to the successor (Note that any handler has the right to break the chain). | Implementation Notes - The client typically uses a factory to create the chain of command and then start execution.
- The sequence of chain my be defined at runtime based on configuration or database elements.
- A concrete handler may choose to forward the message and \ or handle the method.
- A concrete handler my exit thus breaking a chain if it deems no further action required.
Sample C# Code namespace Brett.Patterns.GangOfFour.ChainOfResponsibility.Structural
{
using System;
/// <summary>
/// The abstract class defines the logic to store the next
/// step handler as well is define the abstract handler.
/// </summary>
abstract class Handler
{
/// <summary>
/// Internally store the next handler
/// </summary>
protected Handler _next;
/// <summary>
/// Allow the next handler to be set
/// </summary>
/// <param name="next">The next handler</param>
public void SetNext(Handler next)
{
_next = next;
}
/// <summary>
/// The abstract method signature for logic in each concrete
/// handler
/// </summary>
public abstract void HandleRequest();
}
class ConcreteHandler1
: Handler
{
/// <summary>
/// Perform logic of the first handler
/// </summary>
public override void HandleRequest()
{
//Perform action
Console.WriteLine("Concrete Handler 1 Running");
//Pass it on if there are more steps
if (_next != null)
{
_next.HandleRequest();
}
}
}
class ConcreteHandler2 : Handler
{
/// <summary>
/// Perform logic of the second handler
/// </summary>
public override void HandleRequest()
{
//Perform action
Console.WriteLine("Concrete Handler 2 Running");
//Pass it on if there are more steps
if (_next != null)
{
_next.HandleRequest();
}
}
}
class ConcreteHandler3 : Handler
{
/// <summary>
/// Performs the logic of the third handler
/// </summary>
public override void HandleRequest()
{
//Perform action
Console.WriteLine("Concrete Handler 3 Running");
//Pass it on if there are more steps
if (_next != null)
{
_next.HandleRequest();
}
}
}
/// <summary>
/// The demonstration entry point application
/// </summary>
class Program
{
static void Main()
{
//Define the handlers
ConcreteHandler1 Step1 = new ConcreteHandler1();
ConcreteHandler2 Step2 = new ConcreteHandler2();
ConcreteHandler3 Step3 = new ConcreteHandler3();
//Define the chain
Step1.SetNext(Step2);
Step2.SetNext(Step3);
//Start executing the chain with the first step
Step1.HandleRequest();
}
}
}
|
More Posts
|
|
|