Project Description
Ajax Web Portal built on Linq, Workflow Foundation and ASP.NET AJAX. Code is in Visual Studio 2008 using .NET 3.0 and .NET 3.5.

Production site

http://dropthings.omaralzabir.com
For latest news and updates, visit my blog
http://msmvps.com/blogs/omar/

Source Code

Latest source code and releases:
http://code.google.com/p/dropthings/

Click here for the code that matches with the book


Book about this project
MyBook.jpg
This book explains how this project has been built step by step. It also explains many advance AJAX concepts, development and production challenges for building and maintaining a high volume production website.

Get it from Amazon:
http://www.amazon.com/Building-Web-2-0-Portal-ASP-NET/dp/0596510500

Technologies
  • ASP.NET 2.0
  • jQuery
  • ASP.NET AJAX (.NET 3.5)
  • Silverlight
  • Linq to Sql
  • Linq to Xml
  • Workflow Foundation (.NET 3.0)
  • Visual Studio 2008 and SQL Server 2005

Features
  • Configure widgets for specific user roles.
  • Configure different default page setup for different roles - Managers get some widgets, Employees get different widgets and so on.
  • Ability to define page setup for anonymous users and different page setup for logged in users.
  • Multiple Tabs.
  • Customizable Widget Gallery.
  • Different column setup.
  • Build your own widgets using Silverlight, ASP.NET or plain Javascripts.
  • Host widgets on any page of your website
  • Easy to integrate Dropthings to your own website e.g. http://myoffice.bt.com is built on top of Dropthings.
  • Business Layer is entirely Workflow Foundation driven - easy to plug-in your own business logic as Activities.

Join Us
If you are a seasoned ASP.NET Developer and have ASP.NET AJAX skill, come and join us to make Dropthings a feature rich Ajax Web Portal. Please email me at "OmarALZabir" at gmail dot com.

What is an AJAX Portal
A Portal refers to a page that allows users to customize their own homepage by dragging and dropping widgets onto the page. This approach gives users complete control over what content they see on their page, where they want to see it, and how they want to interact with it.

A widget is a discrete piece on a Web page that performs a particular function and comes with its own UI and set of features. Examples of widgets include a to-do-list, an address book, a contact list, an RSS feed, or even a clock, calendar, playlist, stock ticker, weather report, traffic report, dictionary, game, or almost anything you can imagine that can be packaged up and dropped on a Web page. In a corporate environment, widgets can connect to internal systems, such as an Expense Tracker widget that interacts directly with the internal Accounting System. If you are familiar with Sharepoint Portal, then you already know about Widgets. They are called Web parts in Sharepoint’s term and also in ASP.NET 2.0.

Portals are powerful RSS aggregation platform. You can put as many RSS widgets as you like on your page and get fresh content delivered to you as soon as it is published. Some Portal like Pageflakes archives RSS for a long time and thus you can go back in time and read older posts, save posts, and forward interesting articles to your friends.

An Ajax-powered portal is specifically a portal that uses Ajax technologies to create richer experiences for its users. It is one step ahead of previous generation portals like My Yahoo or MSN.com, because it gives you state-of-the-art UI that behaves more like a Windows client application -- with widgets, animations, popups, client side data grids, and other effects not usually found on a non-Ajax Web portal .

How to run the project
  1. Download the latest source code from Google Code site http://code.google.com/p/dropthings/
  2. Follow the Readme.txt

How is ASP.NET AJAX used in this project?
It is an N-tier application, with a user interface (UI) layer, a business layer, and a data access layer. I have used ASP.NET AJAX to implement the UI layer of the portal application which includes the homepage and the widgets’ UI. ASP.NET AJAX provides the framework for loading widgets onto the home page, updating widgets without doing any postbacks (via UpdatePanel), and changing page layout by dragging and dropping widgets on the page. It also provides a rich collection of Control Extenders, that add cool effects like fade in/fade out, smooth transitions, and client side animations . You can add to the rich clientside experience by providing auto-completion behavior on text boxes, asynchronous data loading via webservice calls, and client side paging, sorting and many more.

How is .NET 3.5 used in this project
The business layer of the application is built with the Workflow Foundation in .NET 3.0 . Major operations like a first-time user visit, a subsequent user visit, adding a new widget, and creating a new page are all orchestrated using workflow . The workflows contain all the business rules and activities needed to complete each operation. For example, the "New User Visit" workflow creates the user account, populates the user profile with default values, creates some default pages, populates them with specific widgets, etc. Such compound operations are very easy to build with Workflows , which enables you to break the complete workflow operation into smaller chunks named Activities. Each Activity does a very small amount of work. It talks to the data access layer and performs the task. The data access layer is built with .NET 3.5 , utilizing LINQ to SQL .
The web project and the widgets make good use of .NET 3.5 by utilizing lambda expressions , LINQ to SQL, and LINQ to XML. You will use Linq queries to work with collections and database rows. Widgets make good use of Linq to Xml in order to consume XML from external data sources.

Warning: Dropthings.com is a very simple, open-source example of what can be done with AJAX and Microsoft technologies. It is intended for educational purposes only. Dropthings.com has absolutely nothing to do with http://www.pageflakes.com. But this project does a good job to show you how all the new hot technologies work together in a working web application that's production ready.


My Blog

---
 Omar AL Zabir blog on ASP.NET Ajax and .NET 3.5 News Feed 
Sunday, March 14, 2010  |  From Omar AL Zabir blog on ASP.NET Ajax and .NET 3.5

ParallelWork is an open source free helper class that lets you run multiple work in parallel threads, get success, failure and progress update on the WPF UI thread, wait for work to complete, abort all work (in case of shutdown), queue work to run after certain time, chain parallel work one after another. It’s more convenient than using .NET’s BackgroundWorker because you don’t have to declare one component per work, nor do you need to declare event handlers to receive notification and carry additional data through private variables. You can safely pass objects produced from different thread to the success callback. Moreover, you can wait for work to complete before you do certain operation and you can abort all parallel work while they are in-flight. If you are building highly responsive WPF UI where you have to carry out multiple job in parallel yet want full control over those parallel jobs completion and cancellation, then the ParallelWork library is the right solution for you.

I am using the ParallelWork library in my PlantUmlEditor project, which is a free open source UML editor built on WPF. You can see some realistic use of the ParallelWork library there. Moreover, the test project comes with 400 lines of Behavior Driven Development flavored tests, that confirms it really does what it says it does.

The source code of the library is part of the “Utilities” project in PlantUmlEditor source code hosted at Google Code.

The library comes in two flavors, one is the ParallelWork static class, which has a collection of static methods that you can call. Another is the Start class, which is a fluent wrapper over the ParallelWork class to make it more readable and aesthetically pleasing code.

ParallelWork allows you to start work immediately on separate thread or you can queue a work to start after some duration. You can start an immediate work in a new thread using the following methods:

  • void StartNow(Action doWork, Action onComplete)
  • void StartNow(Action doWork, Action onComplete, Action<Exception> failed)

For example,

ParallelWork.StartNow(() =>
{
workStartedAt = DateTime.Now;
Thread.Sleep(howLongWorkTakes);
},
() =>
{
workEndedAt = DateTime.Now;
});



Or you can use the fluent way Start.Work:



Start.Work(() =>
{
workStartedAt = DateTime.Now;
Thread.Sleep(howLongWorkTakes);
})
.
OnComplete(() =>
{
workCompletedAt = DateTime.Now;
})
.
Run();



Besides simple execution of work on a parallel thread, you can have the parallel thread produce some object and then pass it to the success callback by using these overloads:



  • void StartNow<T>(Func<T> doWork, Action<T> onComplete)

  • void StartNow<T>(Func<T> doWork, Action<T> onComplete, Action<Exception> fail)

For example,



ParallelWork.StartNow<Dictionary<string, string>>(
() =>
{
test = new Dictionary<string,string>();
test.Add("test", "test");

return test;
},
(
result) =>
{
Assert.True(result.ContainsKey("test"));
});



Or, the fluent way:



Start<Dictionary<string, string>>.Work(() =>
{
test = new Dictionary<string, string>();
test.Add("test", "test");

return test;
})
.
OnComplete((result) =>
{
Assert.True(result.ContainsKey("test"));
})
.
Run();



You can also start a work to happen after some time using these methods:



  • DispatcherTimer StartAfter(Action onComplete, TimeSpan duration)

  • DispatcherTimer StartAfter(Action doWork,Action onComplete,TimeSpan duration)

You can use this to perform some timed operation on the UI thread, as well as perform some operation in separate thread after some time.



ParallelWork.StartAfter(
() =>
{
workStartedAt = DateTime.Now;
Thread.Sleep(howLongWorkTakes);
},
() =>
{
workCompletedAt = DateTime.Now;
},
waitDuration);



Or, the fluent way:



Start.Work(() =>
{
workStartedAt = DateTime.Now;
Thread.Sleep(howLongWorkTakes);
})
.
OnComplete(() =>
{
workCompletedAt = DateTime.Now;
})
.
RunAfter(waitDuration);



 



There are several overloads of these functions to have a exception callback for handling exceptions or get progress update from background thread while work is in progress. For example, I use it in my PlantUmlEditor to perform background update of the application.




// Check if there's a newer version of the app
Start<bool>.Work(() =>
{
return UpdateChecker.HasUpdate(Settings.Default.DownloadUrl);
})
.
OnComplete((hasUpdate) =>
{
if (hasUpdate)
{
if (MessageBox.Show(Window.GetWindow(me),
"There's a newer version available.
Do you want to download and install?"
,
"New version available",
MessageBoxButton.YesNo,
MessageBoxImage.Information) == MessageBoxResult.Yes)
{
ParallelWork.StartNow(() => {
var tempPath = System.IO.Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
Settings.Default.SetupExeName);

UpdateChecker.DownloadLatestUpdate(Settings.Default.DownloadUrl, tempPath);
}, () => { },
(
x) =>
{
MessageBox.Show(Window.GetWindow(me),
"Download failed. When you run next time,
it will try downloading again."
,
"Download failed",
MessageBoxButton.OK,
MessageBoxImage.Warning);
});
}
}
})
.
OnException((x) =>
{
MessageBox.Show(Window.GetWindow(me),
x.Message,
"Download failed",
MessageBoxButton.OK,
MessageBoxImage.Exclamation);
});



The above code shows you how to get exception callbacks on the UI thread so that you can take necessary actions on the UI. Moreover, it shows how you can chain two parallel works to happen one after another.



Sometimes you want to do some parallel work when user does some activity on the UI. For example, you might want to save file in an editor while user is typing every 10 second. In such case, you need to make sure you don’t start another parallel work every 10 seconds while a work is already queued. You need to make sure you start a new work only when there’s no other background work going on. Here’s how you can do it:



private void ContentEditor_TextChanged(object sender, EventArgs e)
{
if (!ParallelWork.IsAnyWorkRunning())
{
ParallelWork.StartAfter(SaveAndRefreshDiagram,
TimeSpan.FromSeconds(10));
}
}


If you want to shutdown your application and want to make sure no parallel work is going on, then you can call the StopAll() method.



ParallelWork.StopAll();


If you want to wait for parallel works to complete without a timeout, then you can call the WaitForAllWork(TimeSpan timeout). It will block the current thread until the all parallel work completes or the timeout period elapses.



result = ParallelWork.WaitForAllWork(TimeSpan.FromSeconds(1));


The result is true, if all parallel work completed. If it’s false, then the timeout period elapsed and all parallel work did not complete.



For details how this library is built and how it works, please read the following codeproject article:



ParallelWork: Feature rich multithreaded fluent task execution library for WPF



http://www.codeproject.com/KB/WPF/parallelwork.aspx



If you like the article, please vote for me.

Shout it

Tuesday, March 09, 2010  |  From Omar AL Zabir blog on ASP.NET Ajax and .NET 3.5

PlantUmlEditor is my new free open source UML designer project built using WPF and .NET 3.5. If you have used plantuml before, you know that you can quickly create sophisitcated UML diagrams without struggling with a designer. Especially those who use Visio to draw UML diagrams (God forbid!), you will be at heaven. This is a super fast way to get your diagrams up and ready for show. You can *write* UML diagrams in plain English, following a simple syntax and get diagrams generated on-the-fly.

This editor really saves time designing UML diagrams. I have to produce quick diagrams to convey ideas quickly to Architects, Designers and Developers everyday. So, I use this tool to write some quick diagrams at the speed of coding, and the diagrams get generated on the fly. Instead of writing a long mail explaining some complex operation or some business process in English, I can quickly write it in the editor in almost plain English, and get a nice looking activity/sequence diagram generated instantly. Making major changes is also as easy as doing search-replace and copy-pasting blocks here and there. You don't get such agility in any conventional mouse-based UML designers.

PlantUML editor screencast

I have submited a full codeproject article to give you a detail walkthrough how I have built this. Please read this article and vote for me if you like it.

PlantUML Editor: A fast and simple UML editor using WPF

http://www.codeproject.com/KB/smart/plantumleditor.aspx

You can download the project from here:

http://code.google.com/p/plantumleditor/

Sunday, February 28, 2010  |  From Omar AL Zabir blog on ASP.NET Ajax and .NET 3.5

You usually write unit test and integration test code separately using different technologies. For example, for unit test, you use some mocking framework like Moq to do the mocking. For integration test, you do not use any mocking, just some test classes that hits some service or facade to do end-to-end integration test. However, sometimes you see that the integration and unit test are more or less same, they test the same class using its interface and perform the same tests against the same expectation. For example, if you think about a WCF service, you write unit test to test the ServiceContract using the interface where you use some mocking framework to mock the interface of the WCF Service. If you look at the following example, I am using Moq to test IPortalService interface which is a ServiceContract for a WCF service. I am using xUnit and SubSpec to do BDD style tests.

[Specification]
public void GetAllWidgetDefinitions_should_return_all_widget_in_widget_gallery()
{
var portalServiceMock = new Mock<IPortalService>();
var portalService = portalServiceMock.Object;

"Given a already populated widget gallery".Context(() =>
{
portalServiceMock.Setup(p => p.GetAllWidgetDefinitions())
.
Returns(new Widget[] { new Widget { ID = 1 }, new Widget { ID = 2 }})
.
Verifiable();
});

Widget[] widgets = default(Widget[]);
"When a widget is added to one of the page".Do(() =>
{
widgets = portalService.GetAllWidgetDefinitions();
});

"It should create the widget on the first row and first
column on the same page"
.Assert(() =>
{
portalServiceMock.VerifyAll();
Assert.NotEqual(0, widgets.Length);
Assert.NotEqual(0, widgets[0].ID);
});
}


 



Now when I want to do an end-to-end test to see if the service really works by connecting all the wires, then I write a test like this:



[Specification]
public void GetAllWidgetDefinitions_should_return_all_widget_in_widget_gallery()
{
var portalService = new ManageCustomerPortalClient();

"Given a already populated widget gallery".Context(() =>
{
});

Widget[] widgets = default(Widget[]);
"When a widget is added to one of the page".Do(() =>
{
widgets = portalService.GetAllWidgetDefinitions();
});

"It should create the widget on the first row and
first column on the same page"
.Assert(() =>
{
Assert.NotEqual(0, widgets.Length);
Assert.NotEqual(0, widgets[0].ID);
});
}



 



If you look at the difference, it’s very little. The mockings are gone. The same operation is called using the same parameters. The same Asserts are done to test against the same expectation. It’s an awful duplication of code.



Conditional compilation saves the day. You could write the unit test using some conditional compilation directive so that in real environment, those mockings are gone and the real stuff gets run. For example, the following code does both unit test and integration test for me. All I do is turn on/off some conditional compilation.



[Specification]
public void GetAllWidgetDefinitions_should_return_all_widget_in_widget_gallery()
{
#if MOCK
var portalServiceMock = new Mock<IPortalService>();
var portalService = portalServiceMock.Object;
#else
var portalService = new ManageCustomerPortalClient();
#endif

"Given a already populated widget gallery".Context(() =>
{
#if MOCK
portalServiceMock.Setup(p => p.GetAllWidgetDefinitions())
.
Returns(new Widget[] { new Widget { ID = 1 }, new Widget { ID = 2 }})
.
Verifiable();
#endif
});

Widget[] widgets = default(Widget[]);
"When a widget is added to one of the page".Do(() =>
{
widgets = portalService.GetAllWidgetDefinitions();
});

"It should create the widget on the first row and
first column on the same page"
.Assert(() =>
{
#if MOCK
portalServiceMock.VerifyAll();
#endif
Assert.NotEqual(0, widgets.Length);
Assert.NotEqual(0, widgets[0].ID);
});
}



 



The code is now in unit test mode. When I run this, it performs unit test using Moq. When I want to switch to integration test mode, all I do is take out the “MOCK” word from Project Properties->Build->Conditional Compilation.



image



Hope this gives you ideas to save unit test and integration test coding time.

Sunday, February 28, 2010  |  From Omar AL Zabir blog on ASP.NET Ajax and .NET 3.5

If your computer is running hot or battery running out quickly then it is most likely due to some application or process consuming high CPU or memory. If you keep running applications for a long time, for example, Outlook, then it continues to grow in memory consumption and does not free up memory efficiently. As a result, your computer runs out of physical memory and other applications run slower. Sometimes Outlook, browser, image editing applications or some other application start taking full CPU as they get into some heavy internal processing and make your CPU hot and other applications perform slower.

My new CPUAlert is an application that monitors CPU and memory consumption of applications and alerts you if some application is consistently taking high CPU or high memory. It not only saves your CPU and Battery’s lifetime but also makes your computer run smooth and let your active applications run as fast as they can be.

While it is running, if some process is consuming more than 200 MB memory, it will show you an alert:

image

Here you can see my Outlook is taking 244 MB of physical RAM.

You can either postpone the alert for 5 mins (just press ESC), or ignore the process permanently so that you no longer receive alert for the process anymore, or you can close it and reclaim memory.

The handy feature is “Restart” which closes the application and starts again. This generally frees up memory that clogs up in the process.

Same alert will come if some process is consuming more than 30% CPU for over 5 mins.

You can configure all these settings like what’s the tolerable limit for CPU and memory, how frequently to show alert, how long to wait before closing application etc by right clicking on the Task bar icon and choosing Settings.

image

image

Source code of the project is available at:

http://code.google.com/p/cpualert/

The installer can also be downloaded from there.

Warning: The code is not in a good shape. I was frustrated at some process taking high CPU and memory and I wrote this app within hours to get the job done for me.

If you like the application, spread the word!

Sunday, February 21, 2010  |  From Omar AL Zabir blog on ASP.NET Ajax and .NET 3.5

I have enhanced my streaming Ajax Proxy with POST, PUT and DELETE features. Previously it supported only GET. Now it supports all 4 popular methods for complete REST support. Using this proxy, you can call REST API on external domain directly from your website’s javascript code. You can test the proxy from this link:
labs.omaralzabir.com/ajaxstreamingproxy/GetPutDeleteTest.aspx
The latest source code for the Ajax Proxy is available here:
http://code.google.com/p/fastajaxproxy/
You can find a detail CodeProject article that explains how the streaming asynchronous aspect of this proxy works:
Fast, Scalable, Streaming AJAX Proxy - continuously deliver data from across domains
Here’s how the test UI looks like where you can test POST, PUT and DELETE:

If you want to run the sample source code on your local IIS, make sure you allow the POST, PUT, and DELETE headers on .ashx extension from IIS properties:

The sample project shows how you can use the proxy to make calls to external domains. You can directly hit any external URL and perform POST or DELETE from your javascript code: var proxyUrl = "StreamingProxy.ashx";
function download(method, proxyUrl, contentUrl, isJson, bodyContent, completeCallback) {
var request = new Sys.Net.WebRequest();

if (method == "POST" || method == "PUT")
request.set_httpVerb("POST");
else
request.set_httpVerb("GET");

var url = proxyUrl + "?m=" + method +
(isJson ? "&t=" + escape("application/json") : "") + "&u=" + escape(contentUrl);

request.set_url(url);

if (bodyContent.length > 0) {
request.set_body(bodyContent);
request.get_headers()["Content-Length"] = bodyContent.length;
}

var startTime = new Date().getTime();

request.add_completed(function(executor) {
if (executor.get_responseAvailable()) {
var content = executor.get_responseData();
var endTime = new Date().getTime();

var statistics =
"Duration: " + (endTime - startTime) + "ms" + '\n' +
"Length: " + content.length + " bytes" + '\n' +
"Status Code: " + executor.get_statusCode() + " " + '\n' +
"Status: [" + executor.get_statusText() + "]" + '\n';
appendStat(statistics);

$get('resultContent').value = content;
completeCallback();
}
});

var executor = new Sys.Net.XMLHttpExecutor();
request.set_executor(executor);
executor.executeRequest();
}



 


I am using MS AJAX here. You can use jQuery to perform the same test as well. All you need to do is hit the URL of the StreamingProxy.ashx and pass the actual URL in query string parameter “u” and pass the type of the http method...



Visit my Blog for more details.



Thursday, February 04, 2010  |  From Omar AL Zabir blog on ASP.NET Ajax and .NET 3.5

I am a 64bit freak. I got Windows 7, Outlook 2010, Conferencing Addin all 64 bit versions to work on a Macbook pro. Those who are thinking about moving to 64bit and hesitating whether something will break, GO AHEAD! Macbook Pro hardware and Microsoft’s software are the best combination out there. You will enjoy every moment you spend with your laptop. Moreover, I have tried these combinations on HP tablet PC, Sony VAIO, Dell Inspiron and Dell Vostro. HP works best. Others are struggling with driver issues.
I will give you positive and negative feedback with the apps I have tried so far: Outlook 2010 64 bit:

Here are my negative feedback. Outlook Product Manager, please read this. I am a hardcore Outlook customer of you. All my Outlook COM addins are dead. Outlook 2010 64bit does not support them. Looks like not so good backward compatibility. Not so significant improvement with Exchange 2007. The startup time has improved from about 5 secs to 2 secs. But the startup time saving is not really a big saver since I start outlook and it keeps running for days until my PC is so screwed that I need a restart. Office Communicator 2005 does not work. The beta Office 2010 applications are CPU hungry. I see 30% to 40% CPU most of the time. It took me over 30 hours until Outlook 2010 started to perform well. All this time, it was indexing and indexing and indexing and burning CPU. There’s nothing so ground breaking and productivity enhancing in Outlook 2010 yet. After upgrading and using it for couple of days, I don’t see something so attractive that justifies the time spent in upgrading for busy professional. It’s not upgrade at this stage so far. You have to uninstall all Office 2007 or earlier products, addins etc and then install Outlook 2010. Outlook Keyboard shortcuts are changed, having hard time adjusting. My precious Alt+L for Reply to All is gone. Now it’s Ctrl+Shift+R. Come on guys, when do you just Reply and not to Reply to All? I barely remember ever using Reply only. It’s always Reply to All. Can’t you make a easier shortcut for this? Keyboard focus gets lost to some weird place sometimes and my navigation using cursor gets broken. I have to click using mouse to get into track. Quick Tasks are kind of limited. For ex, “Reply & Delete”, who would want to press CTRL+SHIFT+1 to do reply and delete? It’s more natural to press Ctrl+R to reply and then send it and hit DEL. The choices on Quick Tasks are limited as well. I was hoping I would be able to chain multiple commands like – open a new message window, select a specific account to send mail using, select a specific signature and after the mail is sent, show move dialog box to move the conversation to a specific folder. Nope, it does not work this way. First of all there are limited commands which does not even support this. Secondly, all the actions are performed instantly one after another without waiting for the first action to complete. ...



Visit my Blog for more details.



Saturday, November 21, 2009  |  From Omar AL Zabir blog on ASP.NET Ajax and .NET 3.5

I am yet to find a proper sample on how to do realistic Test Driven Development (TDD) and how to write proper unit tests for complex business applications, that gives you enough confidence to stop doing manual tests anymore. Generally the samples show you how to test a Stack or a LinkedList, which is far simpler than testing a typical N-tier application, especially if you are using Entity Framework or Linq to SQL or some ORM in data access layer, and doing logging, validation, caching, error handling at middle tier. There are many articles, blog posts, video tutorials on how to write unit tests, which I believe are all very good starting points. But all these examples show you basic tests, not good enough to let your QA team go. So, let me try to show you some realistic unit and integration test examples which should help you write tests that gives you confidence and helps you gradually move towards TDD.  
I will show you tests done on my open source project Dropthings, which is a Web 2.0 AJAX portal built using jQuery, ASP.NET 3.5, Linq to SQL, Dependency Injection using Unity, caching using Microsoft Enterprise Library, Velocity and so on. Basically all the hot techs you can grasp in one shot. The project is a typical N-tier application where there’s a web layer, a business layer and a data access layer. Writing unit tests, integration tests and load tests for this project was challenging, and thus interesting to share so that you can see how you can implement Unit Testing and Integration Testing in a real project and gradually get into Test Driven Development.

Read this codeproject article of mine to learn how I did Integration Tests and Unit Tests using Behavior Driven Development approach:
Unit Testing and Integration Testing in business applications
http://www.codeproject.com/KB/testing/realtesting.aspx
If you like it, please vote for me. 



Visit my Blog for more details.



Sunday, November 01, 2009  |  From Omar AL Zabir blog on ASP.NET Ajax and .NET 3.5

Caching of frequently used data greatly increases the scalability of your application since you can avoid repeated queries on database, file system or to webservices. When objects are cached, it can be retrieved from the cache which is lot faster and more scalable than loading from database, file or web service. However, implementing caching is tricky and monotonous when you have to do it for many classes. Your data access layer gets a whole lot of code that deals with caching objects and collection, updating cache when objects change or get deleted, expire collections when a contained object changes or gets deleted and so on. The more code you write, the more maintenance overhead you add. Here I will show you how you can make the caching a lot easier using Linq to SQL and my library AspectF. It’s a library that helps you get rid of thousands of lines of repeated code from a medium sized project and eliminates plumbing (logging, error handling, retrying etc) type code completely.
Here’s an example how caching significantly improves the performance and scalabitlity of applications. Dropthings – my open source Web 2.0 AJAX portal, without caching can only serve about 11 request/sec with 10 concurrent users on a dual core 64 bit PC. Here data is loaded from database as well as from external sources. Avg page response time is 1.44 sec.

After implementing caching, it became significantly faster, around 32 requests/sec. Page load time decreased significantly as well to 0.41 sec only. During the load test, CPU utilization was around 60%.

It shows clearly the significant difference it can make to your application. If you are suffering from poor page load performance and high CPU or disk activity on your database and application server, then caching Top 5 most frequently used objects in your application will solve that problem right away. It’s a quick win to make your application a lot faster than doing complex re-engineering in your application.
Common approaches to caching objects and collections
Sometimes the caching can be simple, for example caching a single object which does not belong to a collection and does not have child collections that are cached separately. In such case, you write simple code like this: Is the object being requested already in cache? Yes, then serve it from cache. No, then load it from database and then cache it.
On the other hand, when you are dealing with cached collection where each item in the collection is also cached separately, then the caching logic is not so simple. For example, say you have cached a User collection. But each User object is also cached separately because you need to load individual User objects frequently. Then the caching logic gets more complicated: Is the collection being requested already in cache? Yes. Get the collection. For each object in the collection: Is that object individually available in cache? ...



Visit my Blog for more details.



Friday, September 25, 2009  |  From Omar AL Zabir blog on ASP.NET Ajax and .NET 3.5

Introduction
When you create rich Ajax application, you use external JavaScript frameworks and you have your own homemade code that drives your application. The problem with well known JavaScript framework is, they offer rich set of features which are not always necessary in its entirety. You may end up using only 30% of jQuery but you still download the full jQuery framework. So, you are downloading 70% unnecessary scripts. Similarly, you might have written your own javascripts which are not always used. There might be features which are not used when the site loads for the first time, resulting in unnecessary download during initial load. Initial loading time is crucial – it can make or break your website. We did some analysis and found that every 500ms we added to initial loading, we lost approx 30% traffic who never wait for the whole page to load and just close browser or go away. So, saving initial loading time, even by couple of hundred milliseconds, is crucial for survival of a startup, especially if it’s a Rich AJAX website.
You must have noticed Microsoft’s new tool Doloto which helps solve the following problem:
Modern Web 2.0 applications, such as GMail, Live Maps, Facebook and many others, use a combination of Dynamic HTML, JavaScript and other Web browser technologies commonly referred as AJAX to push page generation and content manipulation to the client web browser. This improves the responsiveness of these network-bound applications, but the shift of application execution from a back-end server to the client also often dramatically increases the amount of code that must first be downloaded to the browser. This creates an unfortunate Catch-22: to create responsive distributed Web 2.0 applications developers move code to the client, but for an application to be responsive, the code must first be transferred there, which takes time.
Microsoft Research looked at this problem and published this research paper in 2008, where they showed how much improvement can be achieved on initial loading if there was a way to split the javascripts frameworks into two parts – one primary part which is absolutely essential for initial rendering of the page and one auxiliary part which is not essential for initial load and can be downloaded later or on-demand when user does some action. They looked at my earlier startup Pageflakes and reported:
2.2.2 Dynamic Loading: Pageflakes
A contrast to Bunny Hunt is the Pageflakes application, an
industrial-strength mashup page providing portal-like functionality.
While the download size for Pageflakes is over 1 MB, its initial
execution time appears to be quite fast. Examining network activity
reveals that Pageflakes downloads only a small stub of code
with the initial page, and loads the rest of its code dynamically in
the background. As illustrated by Pageflakes, developers today can
use dynamic code loading to improve their web...



Visit my Blog for more details.



Saturday, September 19, 2009  |  From Omar AL Zabir blog on ASP.NET Ajax and .NET 3.5

Windows 7 64bit finally works! This is the first 64bit OS I could really use in my daily acitvities. I tried Vista 64bit, it was unreliable. It would show blue screen right when I am about to make a presentation to the CEO. Until Microsoft released SP1, Vista 64 bit was not usable at all. Then came Windows 7 beta. I immediately tried the 64bit version of Windows 7 beta. It was even worse than Vista. It would crash every now and then – waking up from standby, trying to do livemeeting share, switching screens, plugging in external USB drives and what not. So, I patiently waited for the final version to come out before I get on installing it on all my laptops. Happy to say, the final version works perfectly on HP tx2000 Tablet PC, DELL Vostro 1500, DELL Inspiron 1520. Once you do a full windows update and install some drivers here and there, it all works perfectly. And let me say, Windows 7 is beautiful. I found back the joy of working on computers again!
Working on 64bit Operating System is challenging. You don’t always find the right printer driver. Your cool external USB speakers won’t work – even if it is made by Microsoft. And above all, there’s that C:\Windows\Winsxs folder which keeps increasing forever. By the time I was done with Vista 64bit (two years approx in business), my Winsxs folder was staggering 26 GB eating up every bit out of my C: partition. I had no choice but to format and start over. It seems like this folder keeps copy of every single DLL version it ever sees. The more windows update I do, the larger it gets. Now on a fresh new Windows 7 installation, after installing VS 2008, Office Applications, Windows Live applications and some handy tools, the Winsxs folder is 5.62 GB. Let’s see how it keeps growing over the year. A useful information for 64bit wannabes, make sure your C partition is at least 60 GB. I just installed Windows 7 64bit 3 days back and it has already taken 31 GB space.

Since I am doing a totally useless post, let me sprinkle some productivity tips on it before you lose interest reading my blog.
I realized I do a lot of context swiching. I get over 200 mails per day, so I pretty much switch focus from Visual Studio/Browser to Outlook once every minute, which is big cencentration killer. So, I tried the above setup on my 25” screen and it works great!
The left half of the screen is visual studio and the right half screen shows Outlook and my todolist. As you see, I can see the emails coming up on Outlook without ever switching. The Visual Studio screen width is the right size to read code without horizontally scrolling. The right bottom half of the screen shows my toodlist so that I am always doing the right task from my todolist and not wondering around heedless. If I browse, I bring up the browser on top of the Visual Studio and keep the right half same so that while browsing I am not missing important mails and I still have an eye on my next actions.
I have been using Toodledo for a year. I...



Visit my Blog for more details.



Saturday, September 19, 2009  |  From Omar AL Zabir blog on ASP.NET Ajax and .NET 3.5

Aspects are common features that you write every now and then in different parts of your project. it can be some specific way of handling exceptions in your code, or logging method calls, or timing execution of methods, or retrying some methods and so on. If you are not doing it using any Aspect Oriented Programming framework, then you are repeating a lot of similar code throughout the project, which is making your code hard to maintain. For ex, say you have a business layer where methods need to be logged, errors need to be handled in a certain way, execution needs to be timed, database operations need to be retried and so on. So, you write code like this: public bool InsertCustomer(string firstName, string lastName, int age,
Dictionary<string, string> attributes)
{
if (string.IsNullOrEmpty(firstName))
throw new ApplicationException("first name cannot be empty");

if (string.IsNullOrEmpty(lastName))
throw new ApplicationException("last name cannot be empty");

if (age < 0)
throw new ApplicationException("Age must be non-zero");

if (null == attributes)
throw new ApplicationException("Attributes must not be null");

// Log customer inserts and time the execution
Logger.Writer.WriteLine("Inserting customer data...");
DateTime start = DateTime.Now;

try
{
CustomerData data = new CustomerData();
bool result = data.Insert(firstName, lastName, age, attributes);
if (result == true)
{
Logger.Writer.Write("Successfully inserted customer data in "
+ (DateTime.Now-start).TotalSeconds + " seconds");
}
return result;
}
catch (Exception x)
{
// Try once more, may be it was a network blip or some temporary downtime
try
{
CustomerData data = new CustomerData();
if (result == true)
{
Logger.Writer.Write("Successfully inserted customer data in "
+ (DateTime.Now-start).TotalSeconds + " seconds");
}
return result;
}
catch
{
// Failed on retry, safe to assume permanent failure.

// Log the exceptions produced
Exception current = x;
int indent = 0;
while (current != null)
{
string message = new string(Enumerable.Repeat('\t', indent).ToArray())
+ current.Message;
Debug.WriteLine(message);
Logger.Writer.WriteLine(message);
current = current.InnerException;
indent++;
}
Debug.WriteLine(x.StackTrace);
Logger.Writer.WriteLine(x.StackTrace);

return false;
}
}

}



Here  you see the two lines of real code, which inserts the...



Visit my Blog for more details.



Wednesday, June 17, 2009  |  From Omar AL Zabir blog on ASP.NET Ajax and .NET 3.5

Venue.
IDB Auditorium
E/8-A Rokeya Sharani,
Sher-e-Bangla Nagar,
Agargaon, Dhaka 1207
Saturday June 20th 9:00 AM to 6:00 PM
Microsoft Community in Bangladesh proudly presents Microsoft Day @ Dhaka. This is a special day dedicated to all Microsoft technology professionals and students in Bangladesh. We will be having the best Microsoft community technologists from Bangladesh - Microsoft Most Valuable Professionals (MVPs) delivering sessions at the event. This technology marathon is a great opportunity to learn from the best and network with each other.
Both Microsoft developers and networking professionals would find the event worth attending.
The event will also feature a demo bonanza with Windows 7 and an extensive Question and Answer panel with the Bangladesh MVPs to answer your queries.
http://msdnbangladesh.net/content/msday.aspx
Please register soon! Limited sits. I have a session there as well.
 
AUDITORIUM – Dev Track
9:00 - 9:30: Opening Speech - Feroz Mahmood
9:30 - 10:30: Development in ASP.NET [LINQ, Web Forms, Dynamic Data] - Tanzim Saqib
10:30 - 11:15: My First ASP.NET MVC App - Mehfuz Hossain
11:15 - 11:45 : Unit Testing in MVC and Demo of dotnetshoutouts.com - Kazi Manzur Rashid
11:45- 12:30: Developing in Silverlight - Faisal Hossain Khan
12:30 - 1:30: Lunch
1:30 - 2:00 : Introduction to Sharepoint/ MOSS - Jannatul Ferdous
2:00 - 2:45: Production Challenges of ASP.NET Websites - Omar Al Zabir
2:45 - 3:15: Windows Azure - Ashic
3:15 - 3:45: Tea Break
3:45 - 4:30:  Overview of Visual Studio Team System 2010 - Mohammad Ashraful Alam
4:30 - 5:30:   Features of Windows 7 - IE8 and Windows Live Features - Omi Azad
BREAK OUT – IT Pro Track
9:00 - 9:30: Opening Speech - Feroz Mahmood [IN AUDITORIUM]
9:30 – 10:30: Exchange Server 2010
10:30 - 11:30: Windows Server 2008 - Virtualisation & HyperV
11:30 - 12:30: Talking Windows Server 2008 and R2 [Windows Client & Windows Server 2008 NAP – Better Together] - Anwar Hossain (Technical Specialist, MS Bangladesh)
12:30 - 1:30: Lunch
1:30 - 2:15:  Session on MS Project & EPM : M. Manzurur Rahman (CEO, ICT Alliance)
2:15 - 3:00: Office 2007
3:00 - 3:30: Tea Break
3:30 - 4:30:  Introduction to SQL Server 2008
4:30 - 5:30:   Features of Windows 7 - IE8 and Windows Live Features - Omi Azad [IN AUDITORIUM]



Visit my Blog for more details.



Monday, May 25, 2009  |  From Omar AL Zabir blog on ASP.NET Ajax and .NET 3.5

Visual Studio 2008 comes with rich Web Testing support, but it’s not rich enough to test highly dynamic AJAX websites where the page content is generated dynamically from database and the same page output changes very frequently based on some external data source e.g. RSS feed. Although you can use the Web Test Record feature to record some browser actions by running a real browser and then play it back. But if the page that you are testing changes everytime you visit the page, then your recorded tests no longer work as expected. The problem with recorded Web Test is that it stores the generated ASP.NET Control ID, Form field names inside the test. If the page is no longer producing the same ASP.NET Control ID or same Form fields, then the recorded test no longer works. A very simple example is in VS Web Test, you can say “click the button with ID ctrl00_UpdatePanel003_SubmitButton002”, but you cannot say “click the 2nd Submit button inside the third UpdatePanel”. Another key limitation is in Web Tests, you cannot address Controls using the Server side Control ID like “SubmitButton”. You have to always use the generated Client ID which is something weird like “ctrl_00_SomeControl001_SubmitButton”. Moreover, if you are making AJAX calls where certain call returns some JSON or updates some UpdatePanel and then based on the server returned response, you want to make further AJAX calls or post the refreshed UpdatePanel, then recorded tests don’t work properly. You *do* have the option to write the tests hand coded and write code to handle such scenario but it’s pretty difficult to write hand coded tests when you are using UpdatePanels because you have to keep track of the page viewstates, form hidden variables etc across async post backs. So, I have built a library that makes it significantly easier to test dynamic AJAX websites and UpdatePanel rich web pages. There are several ExtractionRule and ValidationRule available in the library which makes testing Cookies, Response Headers, JSON output, discovering all UpdatePanel in a page, finding controls in the response body, finding controls inside some UpdatePanel all very easy.
First, let me give you an example of what can be tested using this library. My open source project Dropthings produces a Web 2.0 Start Page where the page is composed of widgets.

Each widget is composed of two UpdatePanel. There’s a header area in each widget which is one UpdatePanel and the body area is another UpdatePanel. Each widget is rendered from database using the unique ID of the widget row, which is an INT IDENTITY. Every page has unique widgets, with unique ASP.NET Control ID. As a result, there’s no way you can record a test and play it back because none of the ASP.NET Control IDs are ever same for the same page on different visits. This is where my library comes to the rescue.
See the web test I did:

This test simulates an anonymous user visit. When anonymous user visits Dropthings for the first...



Visit my Blog for more details.



Wednesday, April 08, 2009  |  From Omar AL Zabir blog on ASP.NET Ajax and .NET 3.5

Dropthings – my open source Web 2.0 Ajax Portal has gone through a technology overhauling. Previously it was built using ASP.NET AJAX, a little bit of Workflow Foundation and Linq to SQL. Now Dropthings boasts full jQuery front-end combined with ASP.NET AJAX UpdatePanel, Silverlight widget, full Workflow Foundation implementation on the business layer, 100% Linq to SQL Compiled Queries on the data access layer, Dependency Injection and Inversion of Control (IoC) using Microsoft Enterprise Library 4.1 and Unity. It also has a ASP.NET AJAX Web Test framework that makes it real easy to write Web Tests that simulates real user actions on AJAX web pages. This article will walk you through the challenges in getting these new technologies to work in an ASP.NET website and how performance, scalability, extensibility and maintainability has significantly improved by the new technologies. Dropthings has been licensed for commercial use by prominent companies including BT Business, Intel, Microsoft IS, Denmark Government portal for Citizens; Startups like Limead and many more. So, this is serious stuff! There’s a very cool open source implementation of Dropthings framework available at National University of Singapore portal.
Visit: http://dropthings.omaralzabir.com

I have published a new article on this on CodeProject:
http://www.codeproject.com/KB/ajax/Web20Portal.aspx Get the source code
Latest source code is hosted at Google code:
http://code.google.com/p/dropthings
There’s a CodePlex site for documentation and issue tracking:
http://www.codeplex.com/dropthings
You will need Visual Studio 2008 Team Suite with Service Pack 1 and Silverlight 2 SDK in order to run all the projects. If you have only Visual Studio 2008 Professional, then you will have to remove the Dropthings.Test project. New features introduced
Dropthings new release has the following features: Template users – you can define a user who’s pages and widgets are used as a template for new users. Whatever you put in that template user’s pages, it will be copied for every new user. Thus this is an easier way to define the default pages and widgets for new users. Similarly you can do the same for a registered user. The template users can be defined in the web.config. Widget-to-Widget communication – Widgets can send message to each other. Widgets can subscribe to an Event Broker and exchange messages using a Pub-Sub pattern. WidgetZone – you can create any number of zones in any shape on the page. You can have widgets laid in horizontal layout, you can have zones on different places on the page and so on. With this zone model, you are no longer limited to the Page-Column model where you could only have N vertical columns. Role based widgets – now widgets are mapped to roles so that you can allow different users to see different widget list using ManageWidgetPersmission.aspx. Role based page setup – you can define page setup for different roles. For...



Visit my Blog for more details.



Saturday, March 14, 2009  |  From Omar AL Zabir blog on ASP.NET Ajax and .NET 3.5

Recently after Load Testing my open source project Dropthings, I encountered a lot of memory leak. I found lots of Workflow Instances and Linq Entities were left in memory and never collected. After profiling the web application using .NET Memory Profiler, it showed the real picture:

It shows you that instances of the several types are being created but not being removed. You see the “New” column has positive value, but the “Remove” column has 0. That means new instances are being created, but not removed. Basically the way you do Memory Profiling is, you take two snapshots. Say you take one snapshot when you first visit your website. Then you do some action on the website that results in allocation of objects. Then you take another snapshot. When you compare both snapshots, you can see how many instances of classes were created between these two snapshots and how many were removed. If they are not equal, then you have leak. Generally in web application many objects are created on every page hit and the end of the request, all those objects are supposed to be released. If they are not released, then we have a problem. But that’s the scenario for desktop applications because in a desktop application, objects can remain in memory until app is closed. But you should know best from the code which objects were supposed to go out of scope and get released.
For beginners, leak means objects are being allocated but not being freed because someone is holding reference to the objects. When objects leak, they remain in memory forever, until the process (or app domain) is closed. So, if you have a leaky website, your website is continuously taking up memory until it runs out of memory on the web server and thus crash. So, memory leak is a bad – it prevents you from running your product for long duration and requires frequent restart of app pool.
So, the above screenshot shows Workflow and Linq related classes are not being removed, and thus leaking. This means somewhere workflow instances are not being released and thus all workflow related objects are remaining. You can see the number is same 48 for all workflow related objects. This is a good indication that, almost every instance of workflow is leaked because there were total 48 workflows created and ran. Moreover it indicates we have a leak from a top Workflow instance level, not in some specific Activity or somewhere deep in the code.
As the workflows use Linq stuff, they held reference to the Linq stuffs and thus the Linq stuffs leaked as well. Sometimes you might be looking for why A is leaking. But you actually end up finding that since B was holding reference to A and B was leaking and thus A was leaking as well. This is sometimes tricky to figure out and you spend a lot of time looking at the wrong direction.
Now let me show you the buggy code: ManualWorkflowSchedulerService manualScheduler =
workflowRuntime.GetService<ManualWorkflowSchedulerService>();

WorkflowInstance...



Visit my Blog for more details.



Friday, March 13, 2009  |  From Omar AL Zabir blog on ASP.NET Ajax and .NET 3.5

Last year at Pageflakes, when we were getting millions of hits per day, we were having query timeout due to lock timeout and Transaction Deadlock errors. These locks were produced from aspnet_Users and aspnet_Membership tables. Since both of these tables are very high read (almost every request causes a read on these tables) and high write (every anonymous visit creates a row on aspnet_Users), there were just way too many locks created on these tables per second. SQL Counters showed thousands of locks per second being created. Moreover, we had queries that would select thousands of rows from these tables frequently and thus produced more locks for longer period, forcing other queries to timeout and thus throw errors on the website.

If you have read my last blog post, you know why such locks happen. Basically every table when it grows up to hold millions of records and becomes popular goes through this trouble. It’s just a part of scalability problem that is common to database. But we rarely take prevention about it in our early design.

The solution is simple, you should either have WITH (NOLOCK) or SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED before SELECT queries. Either of this will do. They tell SQL Server not to hold any lock on the table while it is reading the table. If some row is locked while the read is happening, it will just ignore that row. When you are reading a table thousand times per second, without these options, you are issuing lock on many places around the table thousand times per second. It not only makes read from table slower, but also so many lock prevents insert, update, delete from happening timely and thus queries timeout. If you have queries like “show the currently online users from last one hour based on LastActivityDate field”, that is going to issue such a wide lock that even other harmless select queries will timeout. And did I tell you that there’s no index on LastActivityDate on aspnet_Users table?

Now don’t blame yourself for not putting either of these options on your every stored proc and every dynamically generated SQL from the very first day. ASP.NET developers made the same mistake. You won’t see either of these used in any of the stored procs used by ASP.NET Membership. For example, the following stored proc gets called whenever you access Profile object:
ALTER PROCEDURE [dbo].[aspnet_Profile_GetProperties]
@ApplicationName nvarchar(256),
@UserName nvarchar(256),
@CurrentTimeUtc datetime
AS
BEGIN

DECLARE @ApplicationId uniqueidentifier
SELECT @ApplicationId = NULL
SELECT @ApplicationId = ApplicationId FROM
dbo.aspnet_Applications WHERE LOWER(@ApplicationName) = LoweredApplicationName
IF (@ApplicationId IS NULL)
RETURN

DECLARE @UserId uniqueidentifier
DECLARE @LastActivityDate datetime
SELECT @UserId = NULL

SELECT @UserId = UserId, @LastActivityDate = LastActivityDate
FROM...



Visit my Blog for more details.



Saturday, March 07, 2009  |  From Omar AL Zabir blog on ASP.NET Ajax and .NET 3.5

When your database tables start accumulating thousands of rows and many users start working on the same table concurrently, SELECT queries on the tables start producing lock contentions and transaction deadlocks. This is a common problem in any high volume website. As soon as you start getting several concurrent users hitting your website that results in SELECT queries on some large table like aspnet_users table that are also being updated very frequently, you end up having one of these errors:
Transaction (Process ID ##) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.
Or,
Timeout Expired. The Timeout Period Elapsed Prior To Completion Of The Operation Or The Server Is Not Responding.
The solution to these problems are – use proper index on the table and use transaction isolation level Read Uncommitted or WITH (NOLOCK) in your SELECT queries. So, if you had a query like this: SELECT * FORM aspnet_users
where ApplicationID =’xxx’ AND LoweredUserName = 'someuser'


You should end up having any of the above errors under high load. There are two ways to solve this:

SET TRANSACTION LEVEL READ UNCOMMITTED;
SELECT * FROM aspnet_Users
WHERE ApplicationID =’xxx’ AND LoweredUserName = 'someuser'





Or use the WITH (NOLOCK):

SELECT * FROM aspnet_Users WITH (NOLOCK)
WHERE ApplicationID =’xxx’ AND LoweredUserName = 'someuser'


The reason for the errors are that since aspnet_users is a high read and high write table, during read, the table is partially locked and during write, it is also locked. So, when the locks overlap on each other from several queries and especially when there’s a query that’s trying to read a large number of rows and thus locking large number of rows, some of the queries either timeout or produce deadlocks.


Linq to Sql does not produce queries with the WITH (NOLOCK) option nor does it use READ UNCOMMITTED. So, if you are using Linq to SQL queries, you are going to end up with any of these problems on production pretty soon when your site becomes highly popular.


For example, here’s a very simple query:

using (var db = new DropthingsDataContext())
{
var user = db.aspnet_Users.First();
var pages = user.Pages.ToList();
}


DropthingsDataContext is a DataContext built from Dropthings database.


When you attach SQL Profiler, you get this:





You see none of the queries have READ UNCOMMITTED or WITH (NOLOCK).


The fix is to do this:

using (var db = new DropthingsDataContext2())
{
db.Connection.Open();
db.ExecuteCommand("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;");

var user = db.aspnet_Users.First();
var pages = user.Pages.ToList();
}


This will result in the following profiler output






As you see, both queries execute within the same connection and the isolation level is set before the queries execute. So, both queries enjoy the isolation level.


Now there’s a...



Visit my Blog for more details.



Saturday, December 27, 2008  |  From Omar AL Zabir blog on ASP.NET Ajax and .NET 3.5

When you run a Workflow using Workflow Foundation, you pass arguments to the workflow in a Dictionary form where the type of Dictionary is Dictionary<string, object>. This means you miss the strong typing features of .NET languages. You have to know what arguments the workflow expects by looking at the Workflow public properties. Moreover, there’s no way to make arguments required. You pass parameter, expect it to run, if it throws exception, you pass more arguments, hope it works now. Similarly, if you are running workflow synchronously using ManualWorkflowSchedulerService, you expect return arguments from the Workflow immediately, but there again, you have to rely on the Dictionary key and value pair. No strong typing there as well.
In order to solve this, so that you could pass Workflow arguments as strongly typed classes, you can establish a format that every Workflow has only two arguments named "Request” and “Response” and none other. Whatever needs to be passed to the Workflow and expected out of it, must be passed via Request and must be expected via Response properties. Now the type of these arguments can be workflow specific, it can be any class with one or more parameters. This way, you could write code like this:

The advantages of these strongly typed approach are: Compile time validation of input parameters passed to workflow. No risk of passing unexpected object in Dictionary’s object type value. Enforce required values by creating Request objects with non-default constructor. Establish a fixed contract for Workflow input and output via the strongly typed Request and Response classes or interfaces. Validate input arguments for the Workflow directly from the Request class, without going through the overhead of running a workflow.
If we follow this approach, we create workflows with only two DependencyProperty, one for Request and one for Response. Showing you an example from my open source project Dropthings, which uses Workflow for the entire Business Layer. Below you see the Workflow that executes when a new user visits Dropthings.com, creates a new user and setups all the pages and widgets for the user. It has only two Dependency property – Request and Response.

The Request parameters is of type IUserVisitWorkflowRequest. So, you can pass any class as Request argument that implements the interface.

Here I have used fancy inheritance to create Request object hierarchy. You don’t need to do that. Just remember, you can pass any class. You don’t even need to use interface for Request parameter. It can be a class directly. I use all these interfaces in order to facilitate Dependency Inversion.
Similarly, the Response object is also a class.

The Response returns quite some properties. So, it’s kinda handy to wrap them all in one property.
So, there you have it, strongly typed Workflow arguments. You can attach properties of the Request object to any activity directly form the...



Visit my Blog for more details.



Wednesday, December 10, 2008  |  From Omar AL Zabir blog on ASP.NET Ajax and .NET 3.5

You have a hot ASP.NET+SQL Server product, growing at thousand users per day and you have hit the limit of your own garage hosting capability. Now that you have enough VC money in your pocket, you are planning to go out and host on some real hosting facility, maybe a colocation or managed hosting. So, you are thinking, how to design a physical architecture that will ensure performance, scalability, security and availability of your product? How can you achieve four-nine (99.99%) availability? How do you securely let your development team connect to production servers? How do you choose the right hardware for web and database server? Should you use Storage Area Network (SAN) or just local disks on RAID? How do you securely connect your office computers to production environment?

Here I will answer all these queries. Let me first show you a diagram that I made for Pageflakes where we ensured we get four-nine availability. Since Pageflakes is a Level 3 SaaS, it’s absolutely important that we build a high performance, highly available product that can be used from anywhere in the world 24/7 and end-user gets quick access to their content with complete personalization and customization of content and can share it with others and to the world. So, you can take this production architecture as a very good candidate for Level 3 SaaS:



Here’s a CodeProject article that explains all the ideas:

99.99% available ASP.NET and SQL Server SaaS Production Architecture

Hope you like it. Appreciate your vote.

















Visit my Blog for more details.



Thursday, October 30, 2008  |  From Omar AL Zabir blog on ASP.NET Ajax and .NET 3.5

Linq to Sql does not come with a function like .Delete(ID) which allows you to delete an entity using it’s primary key. You have to first get the object that you want to delete and then call .DeleteOnSubmit(obj) to queue it for delete. Then you have to call DataContext.SubmitChanges() to play the delete queries on database. So, how to delete object without getting them from database and avoid database roundtrip?



You can call this function using DeleteByPK<Employee, int>(10, dataContext);

First type is the entity type and second one is the type of the primary key. If your object’s primary key is a Guid field, specify Guid instead of int.

How it works:

It figures out the table name and the primary key field name from the entity
Then it uses the table name and primary key field name to build a DELETE query


Figuring out the table name and primary key field name is a bit hard. There’s some reflection involved. The GetTableDef<TSource>() returns the table name and primary key field name for an entity.

Every Linq Entity class is decorated with a Table attribute that has the table name:



Then the primary key field is decorated with a Column attribute with IsPrimaryKey = true.



So, using reflection we can figure out the table name and the primary key property and the field name.

Here’s the code that does it:



Before you scream “Reflection is SLOW!!!!” the definition is cached. So, reflection is used only once per appDomain per entity. Subsequent call is just a dictionary lookup away, which is as fast as it can get.

You can also delete a collection of object without ever getting any one of them. The the following function to delete a whole bunch of objects:



The code is available here:

http://code.msdn.microsoft.com/DeleteEntitiesLinq













Visit my Blog for more details.



 Omar AL Zabir blog on ASP.NET Ajax and .NET 3.5 News Feed 
Last edited Oct 6 2009 at 2:37 PM by oazabir, version 30

 

Want to leave feedback?
Please use Discussions or Reviews instead.

Archived page comments (5)

Updating...
© 2006-2010 Microsoft | Get Help | Privacy Statement | Terms of Use | Code of Conduct | Advertise With Us | Version 2010.2.24.16331