Tuesday, August 02, 2011

WebGrid in ASP.NET MVC

Earlier this year Microsoft released ASP.NET MVC version 3 (asp.net/mvc), as well as a new product called WebMatrix (asp.net/webmatrix). The WebMatrix release included a number of productivity helpers to simplify tasks such as rendering charts and tabular data. One of these helpers, WebGrid, lets you render tabular data in a very simple manner with support for custom formatting of columns, paging, sorting and asynchronous updates via AJAX.
In this article, I’ll introduce WebGrid and show how it can be used in ASP.NET MVC 3, then take a look at how to really get the most out of it in an ASP.NET MVC solution. (For an overview of WebMatrix—and the Razor syntax that will be used in this article—see Clark Sell’s article, “Introduction to WebMatrix,” in the April 2011 issue at msdn.microsoft.com/magazine/gg983489).
This article looks at how to fit the WebGrid component into an ASP.NET MVC environment to enable you to be productive when rendering tabular data. I’ll be focusing on WebGrid from an ASP.NET MVC aspect: creating a strongly typed version of WebGrid with full IntelliSense, hooking into the WebGrid support for server-side paging and adding AJAX functionality that degrades gracefully when scripting is disabled. The working samples build on top of a service that provides access to the AdventureWorksLT database via the Entity Framework. If you’re interested in the data-access code, it’s available in the code download, and you might also want to check out Julie Lerman’s article, “Server-Side Paging with the Entity Framework and ASP.NET MVC 3,” in the March 2011 issue (msdn.microsoft.com/magazine/gg650669).

Getting Started with WebGrid

To show a simple example of WebGrid, I’ve set up an ASP.NET MVC action that simply passes an IEnumerable to the view. I’m using the Razor view engine for most of this article, but later I’ll also discuss how the WebForms view engine can be used. My ProductController class has the following action:
  1. public ActionResult List()
  2.   {
  3.     IEnumerable model =
  4.       _productService.GetProducts();
  5.  
  6.     return View(model);
  7.   }
The List view includes the following Razor code, which renders the grid shown in Figure 1:
  1. @model IEnumerable< span="">.Domain.Product>
  2. @{
  3.   ViewBag.Title = "Basic Web Grid";
  4. }
  5. < span="">>Basic Web Grid

  6. < span="">>
  7. @{
  8.   var grid = new WebGrid(Model, defaultSort:"Name");
  9. }
  10. @grid.GetHtml()
A Basic Rendered Web Grid
(click to zoom)

Figure 1 A Basic Rendered Web Grid
The first line of the view specifies the model type (for example, the type of the Model property that we access in the view) to be IEnumerable. Inside the div element I then instantiate a WebGrid, passing in the model data; I do this inside an @{...} code block so that Razor knows not to try to render the result. In the constructor I also set the defaultSort parameter to “Name” so theWebGrid knows that the data passed to it is already sorted by Name. Finally, I use @grid.GetHtml() to generate the HTML for the grid and render it into the response.
This small amount of code provides rich grid functionality. The grid limits the amount of data displayed and includes pager links to move through the data; column headings are rendered as links to enable paging. You can specify a number of options in the WebGrid constructor and the GetHtml method in order to customize this behavior. The options let you disable paging and sorting, change the number of rows per page, change the text in the pager links and much more. Figure 2 shows the WebGrid constructor parameters and Figure 3 the GetHtml parameters.
Figure 2 WebGrid Constructor Parameters
NameTypeNotes
sourceIEnumerableThe data to render.
columnNamesIEnumerableFilters the columns that are rendered.
defaultSortstringSpecifies the default column to sort by.
rowsPerPageintControls how many rows are rendered per page (default is 10).
canPageboolEnables or disables paging of data.
canSortboolEnables or disables sorting of data.
ajaxUpdateContainerIdstringThe ID of the grid’s containing element, which enables AJAX support.
ajaxUpdateCallbackstringThe client-side function to call when the AJAX update is complete.
fieldNamePrefixstringPrefix for query string fields to support multiple grids.
pageFieldNamestringQuery string field name for page number.
selectionFieldNamestringQuery string field name for selected row number.
sortFieldNamestringQuery string field name for sort column.
sortDirectionFieldNamestringQuery string field name for sort direction.
Figure 3 WebGrid.GetHtml Parameters
NameTypeNotes
tableStylestringTable class for styling.
headerStylestringHeader row class for styling.
footerStylestringFooter row class for styling.
rowStylestringRow class for styling (odd rows only).
alternatingRowStylestringRow class for styling (even rows only).
selectedRowStylestringSelected row class for styling.
captionstringThe string displayed as the table caption.
displayHeaderboolIndicates whether the header row should be displayed.
fillEmptyRowsboolIndicates whether the table can add empty rows to ensure the rowsPerPage row count.
emptyRowCellValuestringValue used to populate empty rows; only used when fillEmptyRows is set.
columnsIEnumerableColumn model for customizing column rendering.
exclusionsIEnumerableColumns to exclude when auto-populating columns.
modeWebGridPagerModesModes for pager rendering (default is NextPrevious and Numeric).
firstTextstringText for a link to the first page.
previousTextstringText for a link to the previous page.
nextTextstringText for a link to the next page.
lastTextstringText for a link to the last page.
numericLinksCountintNumber of numeric links to display (default is 5).
htmlAttributesobjectContains the HTML attributes to set for the element.
The previous Razor code will render all of the properties for each row, but you may want to limit which columns are displayed. There are a number of ways to achieve this. The first (and simplest) is to pass the set of columns to the WebGrid constructor. For example, this code renders just the Name and ListPrice properties:
  1. var grid = new WebGrid(Model, columnNames: new[] {"Name""ListPrice"});
You could also specify the columns in the call to GetHtml instead of in the constructor. While this is slightly longer, it has the advantage that you can specify additional information about how to render the columns. In the following example, I specified the header property to make the ListPrice column more user-friendly:
  1. @grid.GetHtml(columns: grid.Columns(
  2.  grid.Column("Name"),
  3.  grid.Column("ListPrice", header:"List Price")
  4.  )
  5. )
Often when you render a list of items, you want to let users click on an item to navigate to the Details view. The format parameter of the Column method allows you to customize the rendering of a data item. The following code shows how to change the rendering of names to output a link to the Details view for an item, and outputs the list price with two decimal places as typically expected for currency values; the resulting output is shown in Figure 4.
  1. @grid.GetHtml(columns: grid.Columns(
  2.  grid.Column("Name", format: @@Html.ActionLink((string)item.Name,
  3.             "Details""Product"new {id=item.ProductId}, null)),
  4.  grid.Column("ListPrice", header:"List Price"
  5.              format: @@item.ListPrice.ToString("0.00"))
  6.  )
  7. )
A Basic Grid with Custom Columns
Figure 4 A Basic Grid with Custom Columns
Although it looks like there’s some magic going on when I specify the format, the format parameter is actually a Func—a delegate that takes a dynamic parameter and returns an object. The Razor engine takes the snippet specified for the format parameter and turns it into a delegate. That delegate takes a dynamic parameter named item, and this is the item variable that’s used in the format snippet. For more information on the way these delegates work, see Phil Haack’s blog post at bit.ly/h0Q0Oz.
Because the item parameter is a dynamic type, you don’t get any IntelliSense or compiler checking when writing your code (see Alexandra Rusina’s article on dynamic types in the February 2011 issue at msdn.microsoft.com/magazine/gg598922). Moreover, invoking extension methods with dynamic parameters isn’t supported. This means that, when calling extension methods, you have to ensure that you’re using static types—this is the reason that item.Name is cast to a string when I call the Html.ActionLink extension method in the previous code. With the range of extension methods used in ASP.NET MVC, this clash between dynamic and extension methods can become tedious (even more so if you use something like T4MVC: bit.ly/9GMoup).

Adding Strong Typing

While dynamic typing is probably a good fit for WebMatrix, there are benefits to strongly typed views. One way to achieve this is to create a derived type WebGrid, as shown in Figure 5. As you can see, it’s a pretty lightweight wrapper!
Figure 5 Creating a Derived WebGrid
  1. public class WebGrid : WebGrid
  2.   {
  3.     public WebGrid(
  4.       IEnumerable source = null,
  5.       ... parameter list omitted for brevity)
  6.     : base(
  7.       source.SafeCast<object>(), 
  8.       ... parameter list omitted for brevity)
  9.     { }
  10.   public WebGridColumn Column(
  11.               string columnName = null
  12.               string header = null
  13.               Funcobject> format = null
  14.               string style = null
  15.               bool canSort = true)
  16.     {
  17.       Funcobject> wrappedFormat = null;
  18.       if (format != null)
  19.       {
  20.         wrappedFormat = o => format((T)o.Value);
  21.       }
  22.       WebGridColumn column = base.Column(
  23.                     columnName, header, 
  24.                     wrappedFormat, style, canSort);
  25.       return column;
  26.     }
  27.     public WebGrid Bind(
  28.             IEnumerable source, 
  29.             IEnumerable<string> columnNames = null
  30.             bool autoSortAndPage = true
  31.             int rowCount = -1)
  32.     {
  33.       base.Bind(
  34.            source.SafeCast<object>(), 
  35.            columnNames, 
  36.            autoSortAndPage, 
  37.            rowCount);
  38.       return this;
  39.     }
  40.   }
  41.  
  42.   public static class WebGridExtensions
  43.   {
  44.     public static WebGrid Grid(
  45.              this HtmlHelper htmlHelper,
  46.              ... parameter list omitted for brevity)
  47.     {
  48.       return new WebGrid(
  49.         source, 
  50.         ... parameter list omitted for brevity);
  51.     }
  52.   }
So what does this give us? With the new WebGrid implementation, I’ve added a new Column method that takes a Func for the format parameter, which means that the cast isn’t required when calling extension methods. Also, you now get IntelliSense and compiler checking (assuming that MvcBuildViews is turned on in the project file; it’s turned off by default).
The Grid extension method allows you to take advantage of the compiler’s type inference for generic parameters. So, in this example, you can write Html.Grid(Model) rather than new WebGrid(Model). In each case, the returned type is WebGrid.

Adding Paging and Sorting

You’ve already seen that WebGrid gives you paging and sorting functionality without any effort on your part. You’ve also seen how to configure the page size via the rowsPerPage parameter (in the constructor or via the Html.Grid helper) so that the grid will automatically show a single page of data and render the paging controls to allow navigation between pages. However, the default behavior may not be quite what you want. To illustrate this, I’ve added code to render the number of items in the data source after the grid is rendered, as shown in Figure 6.
The Number of Items in the Data Source
Figure 6 The Number of Items in the Data Source
As you can see, the data we’re passing contains the full list of products (295 of them in this example, but it’s not hard to imagine scenarios with even more data being retrieved). As the amount of data returned increases, you place more and more load on your services and databases, while still rendering the same single page of data. But there’s a better approach: server-side paging. In this case, you pull back only the data needed to display the current page (for instance, only five rows).
The first step in implementing server-side paging for WebGrid is to limit the data retrieved from the data source. To do this, you need to know which page is being requested so you can retrieve the correct page of data. When WebGrid renders the paging links, it reuses the page URL and attaches a query string parameter with the page number, such as http://localhost:27617/Product/DefaultPagingAndSorting?page=3 (the query string parameter name is configurable via the helper parameters—handy if you want to support pagination of more than one grid on a page). This means you can take a parameter called page on your action method and it will be populated with the query string value.
If you just modify the existing code to pass a single page worth of data to WebGrid, WebGrid will see only a single page of data. Because it has no knowledge that there are more pages, it will no longer render the pager controls. Fortunately, WebGrid has another method, named Bind, that you can use to specify the data. As well as accepting the data, Bind has a parameter that takes the total row count, allowing it to calculate the number of pages. In order to use this method, the List action needs to be updated to retrieve the extra information to pass to the view, as shown in Figure 7.
Figure 7 Updating the List Action
  1. public ActionResult List(int page = 1)
  2. {
  3.   const int pageSize = 5;
  4.  
  5.   int totalRecords;
  6.   IEnumerable products = productService.GetProducts(
  7.     out totalRecords, pageSize:pageSize, pageIndex:page-1);
  8.             
  9.   PagedProductsModel model = new PagedProductsModel
  10.                                  {
  11.                                    PageSize= pageSize,
  12.                                    PageNumber = page,
  13.                                    Products = products,
  14.                                    TotalRows = totalRecords
  15.                                  };
  16.   return View(model);
  17. }
With this additional information, the view can be updated to use the WebGrid Bind method. The call to Bind provides the data to render and the total number of rows, and also sets the autoSortAndPage parameter to false. The autoSortAndPage parameter instructs WebGrid that it doesn’t need to apply paging, because the List action method is taking care of this. This is illustrated in the following code:
  1. < span="">>
  2. @{
  3.   var grid = new WebGrid< span="">>(null, rowsPerPage: Model.PageSize, 
  4.     defaultSort:"Name");
  5.   grid.Bind(Model.Products, rowCount: Model.TotalRows, autoSortAndPage: false);
  6. }
  7. @grid.GetHtml(columns: grid.Columns(
  8.  grid.Column("Name", format: @< span="">>@Html.ActionLink(item.Name, 
  9.    "Details", "Product", new { id = item.ProductId }, null)),
  10.   grid.Column("ListPrice", header: "List Price", 
  11.     format: @< span="">>@item.ListPrice.ToString("0.00"))
  12.   )
  13.  )
  14.  
With these changes in place, WebGrid springs back to life, rendering the paging controls but with the paging happening in the service rather than in the view! However, with autoSortAndPage turned off, the sorting functionality is broken. WebGrid uses query string parameters to pass the sort column and direction, but we instructed it not to perform the sorting. The fix is to add the sort and sortDir parameters to the action method and pass these through to the service so that it can perform the necessary sorting, as shown in Figure 8.
Figure 8 Adding Sorting Parameters to the Action Method
  1. public ActionResult List(
  2.            int page = 1
  3.            string sort = "Name"
  4.            string sortDir = "Ascending" )
  5. {
  6.   const int pageSize = 5;
  7.  
  8.   int totalRecords;
  9.   IEnumerable products =
  10.     _productService.GetProducts(out totalRecords,
  11.                                 pageSize: pageSize,
  12.                                 pageIndex: page - 1,
  13.                                 sort:sort,
  14.                                 sortOrder:GetSortDirection(sortDir)
  15.                                 );
  16.  
  17.   PagedProductsModel model = new PagedProductsModel
  18.   {
  19.     PageSize = pageSize,
  20.     PageNumber = page,
  21.     Products = products,
  22.     TotalRows = totalRecords
  23.   };
  24.   return View(model);
  25. }

AJAX: Client-Side Changes

WebGrid supports asynchronously updating the grid content using AJAX. To take advantage of this, you just have to ensure the div that contains the grid has an id, and then pass this id in the ajaxUpdateContainerId parameter to the grid’s constructor. You also need a reference to jQuery, but that’s already included in the layout view. When the ajaxUpdateContainerId is specified, WebGrid modifies its behavior so that the links for paging and sorting use AJAX for the updates:
  1. < span=""> id="grid">
  2.  
  3. @{
  4.   var grid = new WebGrid< span="">>(null, rowsPerPage: Model.PageSize, 
  5.   defaultSort: "Name", ajaxUpdateContainerId: "grid");
  6.   grid.Bind(Model.Products, autoSortAndPage: false, rowCount: Model.TotalRows);
  7. }
  8. @grid.GetHtml(columns: grid.Columns(
  9.  grid.Column("Name", format: @< span="">>@Html.ActionLink(item.Name, 
  10.    "Details", "Product", new { id = item.ProductId }, null)),
  11.  grid.Column("ListPrice", header: "List Price", 
  12.    format: @< span="">>@item.ListPrice.ToString("0.00"))
  13.  )
  14. )
  15.  
While the built-in functionality for using AJAX is good, the generated output doesn’t function if scripting is disabled. The reason for this is that, in AJAX mode, WebGrid renders anchor tags with the href set to “#,” and injects the AJAX behavior via the onclick handler.
I’m always keen to create pages that degrade gracefully when scripting is disabled, and generally find that the best way to achieve this is through progressive enhancement (basically having a page that functions without scripting that’s enriched with the addition of scripting). To achieve this, you can revert back to the non-AJAX WebGrid and create the script in Figure 9 to reapply the AJAX behavior:
Figure 9 Reapplying the AJAX Behavior
  1. $(document).ready(function () {
  2.  
  3.   function updateGrid(e) {
  4.     e.preventDefault();
  5.     var url = $(this).attr('href');
  6.     var grid = $(this).parents('.ajaxGrid'); 
  7.     var id = grid.attr('id');
  8.     grid.load(url + ' #' + id);
  9.   };
  10.   $('.ajaxGrid table thead tr a').live('click', updateGrid);
  11.   $('.ajaxGrid table tfoot tr a').live('click', updateGrid);
  12.  });
To allow the script to be applied just to a WebGrid, it uses jQuery selectors to identify elements with the ajaxGrid class set. The script establishes click handlers for the sorting and paging links (identified via the table header or footer inside the grid container) using the jQuery live method (api.jquery.com/live). This sets up the event handler for existing and future elements that match the selector, which is handy given the script will be replacing the content.
The updateGrid method is set as the event handler and the first thing it does is to call preventDefault to suppress the default behavior. After that it gets the URL to use (from the href attribute on the anchor tag) and then makes an AJAX call to load the updated content into the container element. To use this approach, ensure that the default WebGrid AJAX behavior is disabled, add the ajaxGrid class to the container div and then include the script from Figure 9.

AJAX: Server-Side Changes

One additional point to call out is that the script uses functionality in the jQuery load method to isolate a fragment from the returned document. Simply calling load(‘http://example.com/someurl’) will load the contents of the URL. However, load(‘http://example.com/someurl #someId’) will load the content from the specified URL and then return the fragment with the id of “someId.” This mirrors the default AJAX behavior of WebGrid and means that you don’t have to update your server code to add partial rendering behavior; WebGrid will load the full page and then strip out the new grid from it.
In terms of quickly getting AJAX functionality this is great, but it means you’re sending more data over the wire than is necessary, and potentially looking up more data on the server than you need to as well. Fortunately, ASP.NET MVC makes dealing with this pretty simple. The basic idea is to extract the rendering that you want to share in the AJAX and non-AJAX requests into a partial view. The List action in the controller can then either render just the partial view for AJAX calls or the full view (which in turn uses the partial view) for the non-AJAX calls.
The approach can be as simple as testing the result of the Request.IsAjaxRequest extension method from inside your action method. This can work well if there are only very minor differences between the AJAX and non-AJAX code paths. However, often there are more significant differences (for example, the full rendering requires more data than the partial rendering). In this scenario you’d probably write an AjaxAttribute so you could write separate methods and then have the MVC framework pick the right method based on whether the request is an AJAX request (in the same way that the HttpGet and HttpPost attributes work). For an example of this, see my blog post at bit.ly/eMlIxU.

WebGrid and the WebForms View Engine

So far, all of the examples outlined have used the Razor view engine. In the simplest case, you don’t need to change anything to use WebGrid with the WebForms view engine (aside from differences in view engine syntax). In the preceding examples, I showed how you can customize the rendering of row data using the format parameter:
  1. grid.Column("Name"
  2.   format: @@Html.ActionLink((string)item.Name, 
  3.   "Details""Product"new { id = item.ProductId }, null)),
The format parameter is actually a Func, but the Razor view engine hides that from us. But you’re free to pass a Func—for example, you could use a lambda expression:
  1. grid.Column("Name"
  2.   format: item => Html.ActionLink((string)item.Name, 
  3.   "Details""Product"new { id = item.ProductId }, null)),
Armed with this simple transition, you can now easily take advantage of WebGrid with the WebForms view engine!

Wrapping Up

In this article I showed how a few simple tweaks let you take advantage of the functionality that WebGrid brings without sacrificing strong typing, IntelliSense or efficient server-side paging. WebGrid has some great functionality to help make you productive when you need to render tabular data. I hope this article gave you a feel for how to make the most of it in an ASP.NET MVC application.

Ref: http://msdn.microsoft.com/en-us/magazine/hh288075.aspx

Sunday, July 31, 2011

What is Public Cloud

A public cloud is one based on the standard cloud computing model, in which a service provider makes resources, such as applications and storage, available to the general public over the Internet. Public cloud services may be free or offered on a pay-per-usage model.
  The main benefits of using a public cloud service are:
  • Easy and inexpensive set-up because hardware, application and bandwidth costs are covered by the provider.
  • Scalability to meet needs.
  • No wasted resources because you pay for what you use.
The term "public cloud" arose to differentiate between the standard model and the private cloud, which is a proprietary network or data center that uses cloud computing technologies, such as virtualization. A private cloud is managed by the organization it serves. A third model, the hybrid cloud, is maintained by both internal and external providers.
Examples of public clouds include Amazon Elastic Compute Cloud (EC2), IBM's Blue Cloud, Sun Cloud, Google AppEngine and Windows Azure Services Platform.
Ref: http://searchcloudcomputing.techtarget.com/definition/public-cloud

Identifying the blockers in SQL Server 2005 and 2008

Problem

In our SQL Server environment, we have frequent locking and blocking across a few different versions of SQL Server. How can I find blocking and blocked SPID’s in SQL Server 2005 and later versions?  Is there only one way to find out which spids are blocking?  Are there any commands that I can run against multiple SQL Server versions?  Check out this tip to learn more about locking and blocking.

Solution

Whenever a user contacts the DBA team indicating a processes looks hung or a process is not proceeding checking the applicable database blocking makes a great deal of sense. Blocking happens when one connection from an application holds a lock and a second connection requires a conflicting lock. This forces the second connection to be blocked until the first connection completes. With this being said, locking is a natural occurrence in SQL Server in order to maintain data integrity.  For more information about locking and blocking review these tips: Understanding SQL Server Locking and Understanding SQL Server Blocking.
There are number of ways to find out the details of the system processes IDs (spids) involved in blocking. I have tried to cover some of the options in this tip to include:
  • sp_who2 System Stored Procedure
  • sys.dm_exec_requests DMV
  • Sys.dm_os_waiting_tasks
  • SQL Server Management Studio Activity Monitor
  • SQL Server Management Studio Reports
  • SQL Server Profiler

sp_who2 System Stored Procedure

The sp_who2 system stored procedure provides information about the current SQL Server processes with the associated users, application, database, CPU time, etc. The information returned can be filtered to return only the active processes by using the ‘active’ parameter.  Below is some sample code and a screen shot with showing process 55 being blocked by process 54.
USE Master
GO
EXEC sp_who2
GO
Additional resources:

sys.dm_exec_requests DMV

The sys.dm_exec_requests DMV provides details on all of the processes running in SQL Server. With the WHERE condition listed below, only blocked processes will be returned.
USE Master
GO
SELECT * 
FROM sys.dm_exec_requests
WHERE blocking_session_id <> 0;
GO
Additional resources:

sys.dm_os_waiting_tasks DMV

The sys.dm_os_waiting_tasks DMV returns information about the tasks that are waiting on resources. To view the data, users should have SQL Server System Administrator or VIEW SERVER STATE permissions on the instance.
USE Master
GO
SELECT session_id, wait_duration_ms, wait_type, blocking_session_id 
FROM sys.dm_os_waiting_tasks 
WHERE blocking_session_id <> 0
GO
Additional resources:

SQL Server Management Studio Activity Monitor

If you are more comfortable using SQL Server Management Studio to review locking and blocking as opposed to querying system objects or executing stored procedures, you are in luck.  There are even a few different tools in SQL Server Management Studio you can use.  The first option is the Activity Monitor, which can be accessed by navigating to the instance name | right click | select 'Activity Monitor'.  To view the Activity Monitor in SQL Server 2005 and SQL Server 2008, users should have SQL Server System Administrator or VIEW SERVER STATE permissions on the instance.
Additional resources:

SQL Server Management Studio Reports

The second option in SQL Server Management Studio to monitor blocking is with the standard reports, which can be accessed by navigating to the instance name | right click | Reports | Standard Reports | Activity - All Blocking Transactions.  Once again, users should have SQL Server System Administrator or VIEW SERVER STATE permissions on the instance.

Additional resources:

SQL Server Profiler

To capture blocking related data on a continuous basis, one option is to run SQL Server Profiler and save the data to a table or file for analysis purposes.  In order to configure Profiler to capture blocking related data, execute Profiler, configure the general properties then navigate to Event Selection tab | select Show all events | Errors and Warnings | check the Blocked process report and then run the application.  In addition, be sure to configure the 'blocked process threshold' before you start Profiler using this code:
sp_configure 'show advanced options', 1
GO
RECONFIGURE
GO 
sp_configure 'blocked process threshold', 20
GO 
RECONFIGURE 
GO 
Ref: http://www.mssqltips.com/tip.asp?tip=2429

Thursday, July 28, 2011

WCF System.Net.WebException: The underlying connection was closed: The connection was closed unexpectedly

WCF System.Net.WebException: The underlying connection was closed: The connection was closed unexpectedly

If you get the above error when trying to return large numbers of items in a List from a WCF service, then ensure you have set the following behaviour for the dataContractSerializer in both your client and service configuration files..

<dataContractSerializer maxItemsInObjectGraph="2147483646"/>

As in this blog, but with larger number (i.e. max of int) http://processmentor.com/community/blogs/scott_middleton/archive/2007/06/08/169.aspx

Need the settings in service layer and client, set to this.
Service has this
<behavior name="MyServiceBehavior">
                                  <serviceDebug includeExceptionDetailInFaults="true" />
                                  <serviceMetadata httpGetEnabled="true" />
                                  <dataContractSerializer maxItemsInObjectGraph="2147483646"/>
                           behavior>
                     serviceBehaviors>
<service behaviorConfiguration="MyServiceBehavior"
                      name="MyService.ServiceImplementation.MyService">
                           <endpoint binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_Leads"
                                           bindingNamespace="http://MyService.ServiceContracts/2007/04"
                            contract="MyService.ServiceContracts.IMyService" />
                           <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
                     service>
              services>

Client has this …

<behaviors>
<endpointBehaviors>
<behavior name="LargeList">
<dataContractSerializer maxItemsInObjectGraph="2147483646" />
                           behavior>
                     endpointBehaviors>
              behaviors>
<endpoint address="http://localhost/myservice.svc" binding="basicHttpBinding"
                                    bindingConfiguration="BasicHttpBinding_IMyService" contract="LeadsServiceInternal.IMyService" name="BasicHttpBinding_IMyService"
                             behaviorConfiguration="LargeList"
                                    />
Note you must also set the following two settings on the client maxReceivedMessageSize and maxBufferSize

<binding name="BasicHttpBinding_IMyService" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" allowCookies="false" bypassProxyOnLocal="false"
                                          hostNameComparisonMode="StrongWildcard" maxBufferSize="2147483646" maxBufferPoolSize="524288" maxReceivedMessageSize="2147483646" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
                                  <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384"/>
                                  <security mode="None">
                                         <transport clientCredentialType="None" proxyCredentialType="None" realm=""/>
                                         <message clientCredentialType="UserName" algorithmSuite="Default"/>
                                  security>
                           binding>
Ref: http://consultingblogs.emc.com/merrickchaffer/archive/2007/09/19/WCF-System.Net.WebException_3A00_-The-underlying-connection-was-closed_3A00_-The-connection-was-closed-unexpectedly.aspx

Sql Server Deadlocks

Deadlocks can kill an application’s performance. Users will complain about the app being slow or broken. Developers will ask the DBA to fix the problem, DBAs will push the problem back on developers. The next thing you know, the office looks like Lord of the Flies.
What is a Deadlock?

A deadlock occurs when two queries need exclusive access to different tables and each query is waiting for the other to finish. Assume that there are two tables, tA and tB. There are also two queries, Q1 and Q2. The first query, Q1, takes an exclusive lock on tA at the same time that the second query, Q2, takes an exclusive lock on tB. So far, there’s nothing out of the ordinary happening. Q1 then requests exclusive access to tB. At this point we have a block. Q1 must wait for Q2 to release its lock before Q1 can finish. Q2 now requests an exclusive lock on tA. And here we have a deadlock.

Q1 won’t release its lock on tA until it can get a lock on tB. Q2 won’t release its lock on tB until it can get a lock on tA. In order for either query to finish, they need access to the other query’s resources. That’s just not going to happen. This is a deadlock.

In order for the database to keep responding, one of these queries has to go. The query that’s eliminated is called the deadlock victim.
Finding Deadlocks

What is the first sign of a deadlock? Queries that should be fast start taking a long time to respond. That’s the first sign of a deadlock, but that’s also the first sign of a lot of other problems. Another sign of a deadlock is an error (error 1205 to be precise) and a very helpful error message: Transaction (Process ID %d) was deadlocked on {%Z} resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

SQL Server is telling you exactly how to solve the problem – re-run your transaction. Unfortunately, if the cause of the deadlock is still running, odds are that your transaction will fail. You can enable several trace flags to detect deadlocks (trace flag2 1204 and 1222), but they output the deadlock to the SQL Server error log and produce output that is difficult to read and analyze.

Once deadlocks show up, your database administrator might reach for a script to pull deadlocks out of Extended Events. Extended Events are a great source of data for analysis. Although they’re a relatively new feature to SQL Server, they first appeared in SQL Server 2008, Extended Events already provide an incredibly rich set of tools for monitoring SQL Server. Event data can be held in memory (which is the default) or written out to a file. It’s possible that to build a set of monitoring tools that log all deadlocks to a file and then analyze that file after the events happen.

Yesterday's deadlocks are tomorrow's news!
Just like newspapers help us find out what happened yesterday, Extended Events provide a great way to investigate deadlocks that have already occurred. If you don’t have any other monitoring tools in place, Extended Events are a great place to start. Once you start seeing deadlocks, you’ll want to start gathering more information about them. It takes some skill to read the XML from a deadlock graph, but it contains a great deal of information about what happened. You can find out which tables and queries where involved the deadlock process, which process was killed off, and which locks caused the deadlock to occur.

The flip side of the coin is that Extended Events will give you very fine grained information about every deadlock that has already happened. There’s nothing in Extended Events to help you stop deadlocks from happening or even to detect them right when they are happening. Much like a microscope lets you look at a prepared slide in excruciating detail, Extended Events let you look at a single point in time in excruciating detail. You can only find out about things after they happen, not as they happen.
Deadlock Notifications

Wouldn’t be nice if you received notifications of deadlocks as they were happening? Good news! Deadlocks only happen when data is changed; it’s possible to wrap your modification statements inside a template to record any deadlocks that happen. This template takes advantage of some features in SQL Server to allow the deadlock notifications to get sent out asynchronously – the notifications won’t slow down any applications while they interact with SQL Server.

There is a big problem here: every stored procedure that modifies data needs this wrapper. If the wrapper is missed in one place, there won’t be any deadlock information collected from that query. If the wrapper needs to be changed, it has to be changed everywhere. This can be a good thing, of course, because you can target problem queries for reporting or different queries can respond in different ways. Like using Extended Events, this is a very fine grained mechanism for dealing with deadlocks. Action is taken at the level of a single execution of a query and not at the level of our entire application. If we’re going to take care of deadlocks, we want to do it once and fix things across the entire application.
Deadlocks by Design

Both the Extended Events and notification solution are very cunning ways to get information about deadlocks that have already happened. Neither solution helps applications respond to deadlocks as they happen.

Much like a director deciding to fix it in post, monitoring for deadlocks and trying to solve the problem is a reaction to something that should have been done right in the first place. Maybe budget constraints got in the way, maybe the software had to ship by a deadline, maybe there wasn’t expertise on the team to look into these problems. For whatever reason, something made it into production that causes deadlocks. It doesn’t matter what happened, the problem is there; deadlocks are happening.
Error 1205: Catching Deadlocks with Code

Application developers have tool they can use to cope with deadlocks. When SQL Server detects a deadlock and kills of a query, an error is thrown. That error makes its way back up to the software that made the database call. .NET developers can catch the exception and check the Number. (Deadlocks throw an error number of 1205.)

When a deadlock happens, SQL Server will kill off the cheapest transaction. The “cheapest” transaction is the transaction with the lowest cost. It’s getting rid of something that will be easy to run a second time around. Instead of having deadlocks cause problems, developers can easily check the errors that come back from the database server and try again. You can set the deadlock priority; if you don’t have time to fix to the code, you can specify which queries should run at a lower priority.

This is moving the problem up the chain. The users may not see that there is a deadlock, but the application code still needs to deal with it. Things can still be tricky, though. If there’s a long running transaction holding locks and causing deadlocks, no reasonable amount of re-tries will solve the deadlocking problem.
Reacting to Deadlocks with Architecture

The easiest way to eliminate deadlocks is to design the database to avoid deadlocks. It sounds facetious, doesn’t it? Of course the easiest way to avoid deadlocks is to design so they don’t happen!

There are a few architectural patterns to use in an application to avoid deadlocks.
Pattern 1: Using NOLOCK to Stop Deadlocks

NOLOCK for YESOUCH
A common way to stop deadlocks is to use the NOLOCK query hint. NOLOCK users advocate this approach because they believe it does what it says – it eliminates locking.

NOLOCK doesn’t get rid of all locks, just the ones that make your queries return the right results. You see, NOLOCK stops locking during read operations. In effect, it throws the hinted table or index into READ UNCOMMITTED and allows dirty reads to occur. Locks are still necessary for data modification; only one process can update a row at a time.

By using NOLOCK, you’re telling the database that it’s okay to avoid locking for read safety in exchange for still letting deadlocks happen.
Pattern 2: Indexing for Concurrency

In some cases, deadlocks are caused by bookmark lookups on the underlying table. A new index can avoid deadlocks by giving SQL Server an alternate path to the data. There’s no need for the select to read from the clustered index so, in theory, it’s possible to avoid a deadlock in this scenario.

Think about the cost of an index:
* Every time we write to the table, we probably end up writing to every index on the table.
* Every time we update an indexed value, there’s a chance that the index will become fragmented.
* More indexes mean more I/O per write.
* More indexes mean more index maintenance.

To top it off, there’s a good chance that the index that prevents a deadlock may only be used for one query. A good index makes a single query faster. A great index makes many queries faster. It’s always important to weight the performance improvement of a single index against the cost to maintain and index and the storage cost to keep that index around.
Pattern 3: Data Update Order

A simple change to the order of data modifications can fix many deadlocks. This is an easy pattern to say that you’re going to implement. The problem with this pattern is that it’s a very manual process. Making sure that all updates occur in the same order requires that developers or DBAs review all code that access the database both when it’s first written and when any changes are made. It’s not an impossible task, but it will certainly slow down development.

There’s another downside to this approach: in many scenarios, managing update order is simply too complex. Sometimes the correct order isn’t clear. Managing update order is made more difficult because SQL Server’s locking granularity can change from query to query.

In short, carefully controlling update order can work for some queries, but it’s not a wholesale way to fix the problem.
Common Patterns: Common Failures

One of the problems of all three patterns is that they’re all reactionary. Just like the two methods for detecting deadlocks, they get implemented after there is a problem. Users are already upset at this point. There has already been some kind of outage or performance problem that caused the users to complain in the first place. Of course, sometimes you inherit a problem and you don’t have the opportunity to get good design in place. Is there hope?

Whether you’re starting off new design, or combating existing problems, there is a way that you can almost entirely prevent deadlocks from occurring.
Using MVCC to Avoid Deadlocks

MVCC is a shorthand way of saying Multi-Version Concurrency Control. This is a fancy way of hinting at a much broader concept that can be summarized simply: by maintaining copies of the data as it is read, you can avoid locking on reads and move to a world where readers never block writers and writers never block readers.

This probably sounds like a big architectural change, right? Well, not really.

SQL Server 2005 introduced READ COMMITTED SNAPSHOT ISOLATION (RSCI). RCSI uses snapshots for reads, but still maintains much of the same behavior as the READ COMMITTED isolation level. With a relatively quick change (and about a 10 second outage), any database can be modified to make use of RCSI.
When Should You Use RCSI?

If you actually want my opinion on the subject: always. If you’re designing a new application, turn on RCSI from the get go and plan your hardware around living in a world of awesome. TempDB usage will be higher because that’s where SQL Server keeps all of the extra versions. Many DBAs will be worried about additional TempDB utilization, but there are ways to keep TempDB performing well.

The bigger question, of course, is why should I use RCSI?
Use RCSI to Eliminate Locking, Blocking, Deadlocks, Poor Application Performance, and General Shortness of Breath

RCSI may not cure pleurisy, but it’s going to future proof your application. Somewhere down the road, if you’re successful, you’ll have to deal with deadlocks. Turning on RCSI is going to eliminate that concern, or make it so minimal that you’ll be surprised when it finally happens.
A Snapshot of The Future: Looking Past RCSI

RCSI is probably all that most people think they going to need at the start of their architectural thinking. There will be circles and arrows and lines on a whiteboard and someone will say “We need to make sure that the DBAs don’t screw this up.” What they really mean is “Let’s talk to the data guys in a year about how we can make this greased pig go faster.”

Both of these versions can poop and bark.
During the early stages of an application’s life, a lot of activity consists of getting data into the database. Reporting isn’t a big concern because there isn’t a lot of data to report on and a few tricks can be used to make the database keep up with demands. Sooner or later, though, demand will outstrip supply and there will be problems. Someone might notice that long running reports aren’t as accurate as they should be. Numbers are close enough, but they aren’t adding up completely.

Even when you’re using RCSI, versions aren’t held for the duration of a transaction. The different isolation levels correspond to different phenomenon and those phenomenon, under a strict two-phase locking model, correspond to how long locks are held. When using one of the two MVCC implementations (RSCI or snapshots), the isolation levels and their phenomenon correspond to how long versions are kept around.

Using RCSI, or even READ COMMITTED, locks/versions are only held for a single statement. If a query has to read a table multiple times for a report, there’s a chance that there can be minor (or even major) changes to the underlying data during a single transaction. That’s right, even transactions can’t save you and your precious versions.

SNAPSHOT isolation makes it possible to create versions for the duration of a transaction – every time a query reads a row, it’s going to get the same copy of that row, no matter if it reads it after 5 seconds, 5 minutes, or 5 hours. There could be multiple updates going on in the background but the report will still see the same version of the row.
Getting Rid of Deadlocks in Practice

There are manual ways to accomplish eliminate deadlocks, but they require significant effort to design and implement. In many cases deadlocks can be eliminated by implementing either READ COMMITTED SNAPSHOT ISOLATION or SNAPSHOT isolation. Making the choice early in an application’s development, preferably during architectural decisions, can make this change easy, painless, and can be designed into the application from the start, making deadlocks a thing of the past.
Ref: http://www.brentozar.com/archive/2011/07/difficulty-deadlocks/

SQL Server, locking and hints

Over the past few years, SQL Server has blossomed from a small office data store to an enterprise-level database server. The number of users concurrently accessing a database also increased with this upgrade. SQL Server 2000's standard approach to locking resources often seems inefficient, but thankfully it provides features to override the standard locking. Locking hints may be used to tell the server how to lock resources, but let's examine locking before covering them.

What is a lock?
Relational database systems like SQL Server use locks to prevent users from stepping on each other's toes. That is, locks prevent users from making conflicting data changes. When one user has a particular piece of data locked, no other user may modify it. In addition, a lock prevents users from viewing uncommitted data changes. Users must wait for the changes to be saved before viewing. Data may be locked using various methods. SQL Server 2000 uses locks to implement pessimistic concurrency control among multiple users performing modifications in a database at the same time.

Deadlocks
A database deadlock can occur when there is a dependency between two or more database sessions for some set of resources. A deadlock is a condition that can occur on any system with multiple threads, not just on a relational database management system. A thread in a multithreaded system may acquire one or more resources (for example, locks). If the resource being acquired is currently owned by another thread, the first thread may have to wait for the owning thread to release the target resource. The waiting thread is said to have a dependency on the owning thread for that particular resource. The following listing shows the text of an exception where a deadlock occurred:
System.Data.SqlClient.SqlException: Transaction (Process ID 12) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

This exception was thrown when one SQL Server call conflicted with another resource that held a lock on the necessary resource. Consequently, one of the processes was terminated. This is a common error message for deadlocks with the process ID being unique to the system.

Types of locks
A database system may lock data items at one of many possible levels within the system hierarchy. The possibilities include:

Rows—an entire row from a database table
Pages—a collection of rows (usually a few kilobytes)
Extents—usually a collection of a few pages
Table—an entire database table
Database—the entire database table is locked


Unless otherwise specified, the database uses its own judgment to determine the best locking approach based upon the scenario. Locking is a resource-intensive activity (with respect to memory), so this is not always the best approach. Thankfully, SQL Server does provide a way to circumvent the default behavior. This is accomplished with locking hints.

Hints
There are times when you need to override SQL Server's locking scheme and force a particular range of locks on a table. Transact-SQL provides a set of table-level locking hints that you can use with SELECT, INSERT, UPDATE, and DELETE statements to tell SQL Server how you want it to lock the table by overriding any other system-wide or transactional isolation levels. The available hints include the following:

FASTFIRSTROW—The query is optimized to get the first row of the result set.
HOLDLOCK—Hold a shared lock until the transaction has been completed.
NOLOCK—Do not issue shared locks or recognize exclusive locks. This may result in data being returned that has been rolled back or has not been committed; therefore, working with dirty data is possible. This may only be used with the SELECT statement.
PAGLOCK—Locks the table.
READCOMMITTED—Read only data from transactions that have been committed. This is SQL Server's default behavior.
READPAST—Rows locked by other processes are skipped, so the returned data may be missing rows. This may only be used with the SELECT statement.
READUNCOMMITTED—Equivalent to NOLOCK.
REPEATABLEREAD—Locks are placed on all data used in queries. This prevents other users from updating the data, but new phantom rows can be inserted into the data set by another user and are included in later reads in the current transaction.
ROWLOCK—Locks the data at row level. SQL Server often locks at the page or table level to modify a row, so developers often override this setting when working with single rows.
SERIALIZABLE—Equivalent to HOLDLOCK.
TABLOCK—Lock at the table level. You may want to use this when performing many operations on table-level data.
UPDLOCK—Use update locks instead of shared locks while reading a table, and hold locks until the end of the transaction. This has the advantage of allowing you to read data without locking and to update that data later knowing the data has not changed.
XLOCK—Uses an exclusive lock on all resources until the end of the transaction.


Microsoft has two categories for the hints: granularity and isolation-level. Granularity hints include PAGLOCK, NOLOCK, ROWLOCK, and TABLOCK. On the other hand, isolation-level hints include HOLDLOCK, NOLOCK, READCOMMITTED, REPEATABLEREAD, and SERIALIZABLE. A maximum of one from each group may be used.

These hints allow the consultant to control the locking used by SQL Server, and they are included in the Transact-SQL statement. They are placed in the FROM portion of the statement preceded by the WITH statement. The WITH statement is an option with SQL Server 2000, but Microsoft strongly urges its inclusion. This leads many to believe that it may be mandatory in future SQL Server releases. Here is the hint syntax as it applies to the FROM clause:
[ FROM { < table_source > } [ ,...n ] ]
< table_source > ::=
table_name [ [ AS ] table_alias ] [ WITH ( < table_hint > [ ,...n ] ) ]
< table_hint > ::=
{ INDEX ( index_val [ ,...n ] )
| FASTFIRSTROW
| HOLDLOCK
| NOLOCK
| PAGLOCK
| READCOMMITTED
| READPAST
| READUNCOMMITTED
| REPEATABLEREAD
| ROWLOCK
| SERIALIZABLE
| TABLOCK
| TABLOCKX
| UPDLOCK
| XLOCK }

While this syntax does show its usage, it's easier to show a real example. The following Transact-SQL statement selects all data from the Employees table of the Northwind database:
SELECT *
FROM Employees WITH (nolock)

This gives me all data regardless of what other processes are currently doing with it, so the data may be dirty, but this is not important to my task. Another example updates all rows in a table, setting a field to a certain value:
UPDATE
Employees WITH (tablock)
SET Title='Test'

This example is updating every row in the table, so a table lock is utilized.

Alternate
At this point, I must stress the fact that even though a table-level hint is specified in code, the query optimizer may ignore the hint. Table-level hints are ignored if the query optimizer does not choose the table and used in the subsequent query plan. Also, the query optimizer will often choose an indexed view over a table. Lastly, a hint may be ignored if the table contains computed columns.

Use your discretion
Using table hints in your applications depends upon what is required. Whether you use them at all will depend upon your needs. For example, many consultants love to use the FASTFIRSTROW hint to return the first row quickly. This gives them something to work with while the rest of the query completes. When the data is unlikely to change (e.g., archived data), the NOLOCK hint is a good choice since the data is basically static. On the other hand, this approach would not be good when doing financial applications, when accuracy is a must.
Ref: http://www.techrepublic.com/article/control-sql-server-locking-with-hints/5181472

What is Cloud Computing

Cloud computing is a general term for anything that involves delivering hosted services over the Internet. These services are broadly divided into three categories: Infrastructure-as-a-Service (IaaS), Platform-as-a-Service (PaaS) and Software-as-a-Service (SaaS). The name cloud computing was inspired by the cloud symbol that's often used to represent the Internet in flowcharts and diagrams.

A cloud service has three distinct characteristics that differentiate it from traditional hosting. It is sold on demand, typically by the minute or the hour; it is elastic -- a user can have as much or as little of a service as they want at any given time; and the service is fully managed by the provider (the consumer needs nothing but a personal computer and Internet access). Significant innovations in virtualization and distributed computing, as well as improved access to high-speed Internet and a weak economy, have accelerated interest in cloud computing.

A cloud can be private or public. A public cloud sells services to anyone on the Internet. (Currently, Amazon Web Services is the largest public cloud provider.) A private cloud is a proprietary network or a data center that supplies hosted services to a limited number of people. When a service provider uses public cloud resources to create their private cloud, the result is called a virtual private cloud. Private or public, the goal of cloud computing is to provide easy, scalable access to computing resources and IT services.

Infrastructure-as-a-Service like Amazon Web Services provides virtual server instanceAPI) to start, stop, access and configure their virtual servers and storage. In the enterprise, cloud computing allows a company to pay for only as much capacity as is needed, and bring more online as soon as required. Because this pay-for-what-you-use model resembles the way electricity, fuel and water are consumed, it's sometimes referred to as utility computing.

Platform-as-a-service in the cloud is defined as a set of software and product development tools hosted on the provider's infrastructure. Developers create applications on the provider's platform over the Internet. PaaS providers may use APIs, website portals or gateway software installed on the customer's computer. Force.com, (an outgrowth of Salesforce.com) and GoogleApps are examples of PaaS. Developers need to know that currently, there are not standards for interoperability or data portability in the cloud. Some providers will not allow software created by their customers to be moved off the provider's platform.

In the software-as-a-service cloud model, the vendor supplies the hardware infrastructure, the software product and interacts with the user through a front-end portal. SaaS is a very broad market. Services can be anything from Web-based email to inventory control and database processing. Because the service provider hosts both the application and the data, the end user is free to use the service from anywhere.
Reference: http://searchcloudcomputing.techtarget.com/definition/cloud-computing

Wednesday, May 13, 2009

Building a WPF Barcode Application

The referring article describes building a WPF Barcode Application using a Barcode Library. At this moment, the Barcode Library implements only the Code 39 barcode, but they promised that more will be added in the near future. Read on...

Steps for Migrating the Program to a 64-bit System

The following article describes the main steps which should be performed to correctly port 32-bit Windows applications on 64-bit Windows systems. Although the article is meant for developers using C/C++ in Visual Studio 2005/2008 environment, it will be also useful for other developers who plan to port their applications on 64-bit systems. Read more...

Monday, April 27, 2009

Using Enums

Hi Guys,
Here are the useful methods that can be utilized against the Enums:


Public Enum WeekDays
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
End Enum

1. The following method helps easily to load the enum names to the combo/list box
Example:
lstWeekDays.Items.AddRange([Enum].GetNames(GetType(WeekDays)))
2. The following method helps easily to load all the enum values at once to an array
Example:
dim myArray as Array = [Enum].GetValues(GetType(WeekDays))
3. The following method helps easily to determine if a name or a value exists in the Enum
Example:

if [Enum].IsDefined(GetType(WeekDays), "Sunday") Then 'do something
If [Enum].IsDefined(GetType(WeekDays), 1) Then ' do something its Monday

Monday, April 20, 2009

Load a ComboBox with Installed Fonts

Hi Guys,
Here's an easiest way to load all the installed fonts to a combo box.
myComboBox.Items.AddRange (System.Drawing.FontFamily.Families);
That's it.

Reversing a string

The easiest way to reverse the string is as follows:

char[] actualDataInArray = myStringData.ToCharArray();
Array.Reverse(actualDataInArray);
string reversedString = new string(actualDataInArray);

That's it.

Tuesday, April 14, 2009

Microsoft Code Analysis Tool .NET

Hi Guys,
CAT.NET is a snap-in to the Visual Studio IDE that helps you identify security flaws within a managed code (C#, Visual Basic .NET, J#) application you are developing. It does so by scanning the binary and/or assembly of the application, and tracing the data flow among its statements, methods, and assemblies. This includes indirect data types such as property assignments and instance tainting operations. The engine works by reading the target assembly and all reference assemblies used in the application -- module-by-module -- and then analyzing all of the methods contained within each. It finally displays the issues its finds in a list that you can use to jump directly to the places in your application's source code where those issues were found. The following rules are currently support by this version of the tool. - Cross Site Scripting - SQL Injection - Process Command Injection - File Canonicalization - Exception Information - LDAP Injection - XPATH Injection - Redirection to User Controlled Site. You can download this package here.

Wednesday, March 11, 2009

Getting Started with the .NET Task Parallel Library

Hi Guys,
Microsoft's new Task Parallel Library (TPL) provides a new approach for using multiple threads. It provides a set of relatively simple method calls that let you launch a group of routines all at once. This article provides an introduction to TPL. It explains the main pieces of TPL and provides simples examples. Know more...

Tuesday, July 29, 2008

Error: The name 'instance-variable' does not exist in the current context

Recently I got the following error "The name 'instance-variable' does not exist in the current context" where 'instance-variable' was the member variable of one of my page.  I was really confused as I was sure that I was doing it right.  So what else could be the problem?  Well it turns out that I had made a backup copy of the file in the same directory before I had changed it.  I turns out that in a Asp.Net 2.0 website you can't have two ASP.NET pages or user controls with the same name class name.  Because the pages are partial classes it does not give the error "The namespace 'global-namespace' already contains a definition for 'instance-variable'" like you would normally get if you redefined a class.  Read more here...

Thursday, June 05, 2008

Microsoft ACT standalone installation

Microsoft ACT is great for stress testing web sites. The only "problem" is that you have to install Visual Studio .NET in order to use it. I use it frequently on my dev machine but some times it is useful have it on a remote machine for stress testing directly in a pre-production environment. The steps below shows how you can copy your local ACT installation to a standalone computer.

Pre-requisite: Internet Explorer 6.0

Steps by step instructions:

  • Copy the C:\Program Files\Microsoft ACT directory from you dev PC to the same directory on the remote machine
  • Create the Act.Reg and Register.cmd files below
  • Execute Register.cmd
  • Create a local user: ACTUser with the "User" rights
  • Set the Identify of the following COM objects to ACTUser (using dcomcnfg):
    • Application Center Test Broker
    • Application Center Test Controller
  • Give full control to ACTUser on the following WMI namespace using "Computer Management": Root/CIMV2/Application/MicrosoftACT


== Save as Register.cmd ==
c:
cd "C:\Program Files\Microsoft ACT"
regedit -s act.reg
for %%i in (*.dll) do regsvr32 /s %%i
ACTBroker.exe -regserver
actcontroller.exe -regserver
ACTRegMof.exe -i "C:\Program Files\Microsoft ACT\actnamespace.mof"
ACTRegMof.exe -i "C:\Program Files\Microsoft ACT\actbroker.mof"
ACTRegMof.exe -i "C:\Program Files\Microsoft ACT\actcontroller.mof"


== Save as Act.Reg ==
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\ACT]
"AppPath"="C:\\Program Files\\Microsoft ACT\\"
"ProductCode"="{E05F0409-0E9A-48A1-AC04-E35E3033604A}"
"Feature"="AppCenter_Test_for_VS.NET"
"Version"="1.0.0536"

Disclaimer: Follow the instructions at your own risk and make sure you have a working backup!

Tuesday, March 27, 2007

Patterns and Software: Essential Concepts and Terminology

Patterns for software development are one of the latest "hot topics" to emerge from the object-oriented community. They are a literary form of software engineering problem-solving discipline that has its roots in a design movement of the same name in contemporary architecture, literate programming, and the documentation of best practices and lessons learned in all vocations. Learn more...

Friday, May 19, 2006

Gaining Remote Access to Microsoft Access with RDO

The following tutorial shows how to use the RDO control, which is similar to the ADO control, to access a Microsoft Access Database on a network drive from a machine on another node of the network. Learn more...

Thursday, May 18, 2006

LINQ Into Microsoft's New Query Capabilities

At PDC 2005, Microsoft introduced brand new technology known as LINQ, which stands for "Language Integrated Query."

The feature set hiding behind this acronym is truly mind-boggling and worthy of a lot of attention. In short, LINQ introduces a query language similar to SQL Server's T-SQL, in C# and VB.NET. Imagine that you could issue something like a "select * from customers" statement within C# or VB.NET. This sounds somewhat intriguing, but it doesn't begin to communicate the power of LINQ. LINQ represents the ability to apply query-style syntax to objects rather than just data sources. This difference, as well as some of the implementation specifics, makes LINQ significantly more powerful than other query languages. Learn more...

Monday, February 27, 2006

Make Your ASP.NET Applications Talk with Text-to-Speech

Text-to-Speech (TTS), also known as speech synthesis, is the process in which typed text is transformed into audible speech. This is preferable to pre-recorded text in which it must be known ahead of time exactly what must be said. With text-to-speech there are opportunities to introduce information that is dynamic. The dynamic information could be from a database or a case where text spoken by a user is repeated for confirmation. Read more...

Monday, February 20, 2006

Filtering HTTP Requests with .NET

ASP.NET has a number of extensibility points that developers can use. One such point is response filtering, accessible via the Filter property of the HttpResponse class. Filters intercept content destined for the client and have an opportunity to modify that content prior to sending it out. Filters are unique in that they can access the raw byte stream that is going to be sent to the client. Read more...

Friday, February 17, 2006

DataGrid/GridView Paging and Sorting Using A DataReader - Introduction

Now, the Datareader is forward-only right? Hmm, but what about paging and sorting? Can we natively implement a DataReader to provide paging and sorting as one would typically with a DataSet? The answer unfortunately is no, and if you try doing this you receive this error message:

AllowCustomPaging must be true and VirtualItemCount must be set for a DataGrid with ID DataGridID when AllowPaging is set to true and the selected datasource does not implement ICollection.

Read more...

Roaming Web Applications in Visual Studio 2003

Visual Studio 2003 provides a nice development environment for creating ASP.NET web applications. However, it has significant shortcomings that create difficulties in a school lab environment: in order to debug ASP.NET applications, the user must

Run IIS on the local workstation

Have administrator-level privileges to the local workstation

Store project files on the c: drive

In a lab environment, it is usually not desirable for users to have administrative privileges on the workstations, and it is preferable for project files to be stored on a network server, rather than a local workstation drive. Read more...

Nine Options for Managing Persistent User State in Your ASP.NET Application

ASP.NET provides many different ways to persist data between user requests. You can use the Application object, cookies, hidden fields, the Session or Cache objects, and lots of other methods. Deciding when to use each of these can sometimes be difficult. Read more...

Don't Use Select *

Something you see in a lot of database access code is a select statement that looks something like this:

SELECT * FROM TableName WHERE ...

While there's technically nothing wrong with it, using the SELECT * syntax could be stealing away precious performance from your application, and even it it's not now, it might someday soon. Read more...

Saturday, February 04, 2006

A Developer's Introduction to VoIP

Voice over Internet Protocol applications aren't just for telecommunications programmers working on phone switches. Thanks to emerging technologies and standards, enterprise programmers and commercial developers can leverage voice technologies in traditional Web, desktop and server software. Not familiar with VoIP? You're not alone. This primer will help. Read more...

Google Maps and ASP.NET - Building a custom server control

I am sure that most of you have heard about or have had a chance to use Google Maps. It's a great service and I was really impressed by the responsiveness of the application and the ease with which users could drag and zoom maps from a Web browser. It has in many ways heralded the arrival of AJAX (Asynchronous JavaScript and XML), which I am sure will revitalize Web development in the days to come. Read more...

GnuPG Encryption for Email, XML, and Others in a VB.NET Wrapper

For email there is only one security standard that is highly used--PGP or the public domain version GnuPG. Read more...

Sending Email with AJAX

AJAX has become ubiquitous, thanks to the fact that it gives web developers the ability to create applications that make http requests without reloading the page on which the application is running. It is also extremely versatile and powerful. Read more...

Read Part 2

Read Part 3

.NET CLR stored procedures within Oracle database: Another breaking revolution

In this article, Jagadish Chaterjee shall introduce you to developing, deploying and testing a .NET based CLR stored procedure with Oracle database using Visual Studio.NET. Read more...

VB and Voice Recognition, Part 3: The Voice Controls

In the previous articles we covered a few of the basic properties and methods of the Voice recognition controls. You now are going to look at each control's properties, methods, and events. Read more...

VB and Voice Recognition, Part 2

This part covers using the Microsoft Dictation Control, and adding it to your previous project to make a full speech-to-text application. Read more...

Friday, February 03, 2006

Use Video Captures in Your .NET Applications

Today, a webcam is a common peripheral, used most often for video conferencing, that most people can easily afford. But what can you do with your webcam besides video conferencing? If you are a developer, the answer is plenty; you will be glad to know that integrating a webcam with an application is not as difficult as you might imagine. Read more...

Getting Hardware Information using Visual Basic.NET and VBScript

The following article explains how to retrieve hardware information using both Visual Basic.NET and VBScript. Read more...

Saturday, January 14, 2006

Sending Emails Asynchronously in C#

We've been experimenting with different ways to send out a large number of emails to subscribers. Since the SMTP class does not expose an asynchronous version of the SmtpMail.Send(Message) method, (e.g. BeginSend / EndSend) we either have to use a commercial or open source component that does, or roll our own. Read on...

ASP.NET: Long Running Tasks with Page Feedback

We often get questions about how to provide feedback in an ASP.NET page when something is going on in the background. A lot of times developers get confused about the difference between running a task asynchronously and running a task on a background thread. Read on...

Wednesday, January 11, 2006

Generate Thumbnail Images from PDF Documents

This article, from Jonathan Hodgson, presents VB.NET code to create thumbnail images from a directory of Adobe Acrobat PDF documents. Read on...

The Perfect Service by Ambrose

In his article, Ambrose illustrates how to use a drag-n-drop/xcopy .NET Windows services manager that can make your life a lot easier if you find yourself needing to implement multiple Windows services in your enterprise. Read on...

Sunday, January 08, 2006

Automate routine tasks with .NET's Windows Services

You can create a service as a Microsoft Visual Studio .NET project, defining code within it that controls what commands are sent to the service and what actions should be taken when those commands are received. Commands sent to a service include starting, pausing, resuming, and stopping the service, and executing custom commands. read more...

Using DTS to transfer XML Data

It is possible to recover the XML that is processed by DTS, but may require some post processing. An elegant, purely ActiveX script based answer gleaned from an Internet link is also described. read more...

Wednesday, December 28, 2005

VB and Voice Recognition

Microsoft has been quietly developing VRS technology and integrating it into Windows. There are many downloads available on the Microsoft Web site that add VRS to your desktop, but very little on how to add this to your applications. This is a short tutorial on how to add voice commands to your application. Read more...

Sunday, December 11, 2005

Glimpse into the next generation of enterprise development using XML

This tutor is intended for anyone who wants a glimpse into the next generation of enterprise development. If you want to develop an understanding of Extensible Markup Language (XML) and learn how to use XML for business-to-business (B2B) communications, learn what the Simple Object Access Protocol (SOAP) and BizTalk extensions are, and learn how to use Microsoft Internet Explorer 5 with XML, this book will provide the information you need. You are assumed to have a basic understanding of Microsoft Visual Basic and the Visual Basic Integrated Development Environment (IDE).

Developers will find code samples, a discussion of the Internet Explorer 5 document object model, and many more topics. Web developers will find material on using XML to build Web pages. Senior developers and managers will find discus-sions on how XML can be integrated into the enterprise. Some of the World Wide Web Consortium (W3C) specifications discussed in this book are not final, and they are changing constantly. It is recommended that you visit the W3C Web site at http://www.w3.org often for the updated specifications. Start reading...

Building `Drag-and-Drop` DIVs: Developing a Basic Script

Alejandro Gervasio explains in detail to show how to build a Draggable-n-Droppable DIV in his article here...

Highlighting Multiple Search Keywords in ASP.NET

Commonly we program to highlight the search word as a whole including spaces between them and not taking to highlight each word of the search expression into the input. Dimitrios Markatos discusses how we could bring about searching individual words and highlighting them in his article here...

Wednesday, December 07, 2005

Virtual Web Services Through Pattern Matching

Assume a situation in which a website is providing a free web service of weather reports. We can consume that service and display these weather reports in our website. One fine day, they have had enough and stop the web service permanently. They are still displaying the weather report in their website. You want to capture that information and display it in your website. Now this virtual web service comes into the picture. Read more...

Tuesday, December 06, 2005

Practice for Designing Web Applications

This article gives some very basic approach for designing a scalable, maintainable, and extensible Web application using ASP.NET and OOP approach. Read more...

Friday, December 02, 2005

Introduction to the .NET Speech SDK

Even though the .NET Speech SDK is still in beta (2), exploring it will show what Microsoft has in store for us in the full release. To run the SDK, the .NET Framework SDK and the .NET Speech SDK beta must be installed. This entire article uses Visual Studio .NET 2002 (VS .NET) for application development. First, this article will cover Speech Application Language Tags (SALT), the foundation of this SDK. read more...

Visual Studio Add-Ins Every Developer Should Download Now

Visual Studio provides a rich extensibility model that developers at Microsoft and in the community have taken advantage of to provide a host of quality add-ins. Some add-ins contribute significant how-did-I-live-without-this functionality, while others just help you automate that small redundant task you constantly find yourself performing. The add-ins are available free and to know more or to get them follow this link...