16 September, 2010

Complete use of RequiredFieldValidator

It's very common to use asp:RequiredFieldValidator to validate form data before submission. Using this for a TextBox is very straight forward, but Today, I came to know that the same can be used effectively to validate asp:DropDownList and asp:RadioButtonsList too. Lets know, how this can be done.

First of all, the usage depends on the Binding of List Items. If all the Items are static and added with <asp:ListItem> as below

<asp:DropDownList ID="ddlAddress" Width="150" runat="server">

Here first item is optional and used for DropDownList in general. Now, the RequiredFieldValidator for this dropdownlist will be as following:
<asp:RequiredFieldValidator ID="rfvaAddress" InitialValue="0" ControlToValidate="ddlAddress" runat="server" ErrorMessage="*" CssClass="Note" />
Here InitialValue is an optional property which is used to mention the Item, which should be selected by default.

But in general the dropdowns are binded in code-behind. If we have an initial item with select text, the value for that select item should be string.Empty. If you don't have this default item, the first item will be selected by default and there is no use of RequiredFieldValidator.

10 August, 2010

Flash Detection Javascript

This is the simple javascript code to detect whether flash installed on the machine or not!

//Look for a version of Internet Explorer that supports ActiveX (i.e., one that's
//running on a platform other than Mac or Windows 3.1) or a browser that supports
//the plugin property of the navigator object and that has Flash Player 2.0
//The Check for Internet Explorer is needed as it can play native swf files.

var flashSupported;

if (
     (navigator.appName == "Microsoft Internet Explorer" 
          && navigator.appVersion.indexOf("Mac") == -1 
          && navigator.appVersion.indexOf("3.1") == -1) 
     || (navigator.plugins && navigator.plugins["Shockwave Flash"]) 
     || navigator.plugins["Shockwave Flash 2.0"]){
     flashSupported = true;
else {
     flashSupported = false;

31 July, 2010

Detect IPad Javascript

In my current project I am working on IPad and there are some specific things need to be applied on IPad. We can detect end user's browser and environment information from the navigator using the following code.

var isIPad = navigator.userAgent.match(/iPad/i) != null;

Bandwidth detection with javascript

In one of my current projects, I came across a scenario to play a video based on the users downloading bandwidth. The detection should be done with javascript. There is a technique, to load an image of known size and calculating the bandwidth on basis of time taken to load that image. Though this technique is not 100% reliable, this will give an approximate estimate of bandwidth.

Here is the javascript code to find users bandwidth:

var userBandwidth = 0;
var startTime;
var endTime;
var imgSize = 39842;
var loadTimeInSec;

function GetUserBandwidth() {
var testImage = new Image();
testImage.src = "bwtest.jpg";
startTime = (new Date()).getTime();
testImage.onload = CreateDelegate(testImage, DoneWithTest);

function DoneWithTest() {
endTime = (new Date()).getTime();
loadTimeInSec = (endTime - startTime) / 1000;
userBandwidth = (imgSize / loadTimeInSec) / 1024;

Here we are loading an image of size 38Kb and added a delegate on image loaded event. In the call back function, we calculate end time, with that we can calculate the bandwidth of the user.

Check my previous post to add delegate in javascript.

Delegate in Javascript

Before going to the topic, lets know brief about "Delegate":
A delegate is like a function pointer, which stores reference of a method. It specifies a method to call and optionally an object to call the method on. They are used, among other things, to implement callbacks and event listeners.

We can create and define delegates in Javascript to perform some specific tasks on an object. The following is the code to define delegate.

function CreateDelegate(contextObject, delegateMethod)
return function()
return delegateMethod.apply(contextObject, arguments);

Let us take a simple example and use the delegate in that. Here is the scenario, there is a large image to be loaded on a web page and we need to display the height and width of that image after loading. Delegate method will be very handy in this situation.

var image = new Image();
image.src = "test.jpg";
image.onload = CreateDelegate(image, ImageLoaded);

function ImageLoaded()
alert(this.width +" X "+ this.height);

We are creating a delegate on image loaded event, which will call method 'ImageLoaded'. This delegate automatically pass the object on which the delegate is defined, to the method. We can refer the actual image object using 'this' in the method.

Pre load images with Javascript

In all UI Rich web applications, it is very common to pre-load images. General method to do this is to use Javascript. We can load images by creating client side images before page gets loaded. It is a simple technique and can be done with 2 lines of code.

var testImage = new Image();
testImage.src = "test.jpg";

With the above lines of code test.jpg will loaded in the DOM. As the images are cached by browsers, whenever we send a new request for test.jpg, the image will be loaded immediately from cache. With this pre-loading technique there wont be any time lag in getting the image also no display lag for the user. This can be used in the scenarios like displaying image gallery with all the thumbnails loaded on first load of the page, image change on hovering/click of some links.

We can do this preloading in html page using an image tag with height and width set to zero or wrapping the dynamic image in a hidden div. But, advantage with this approach is the imag wont be loaded to the page.

03 May, 2010

Solution Array for List in WCF

Here is another common problem encounters with WCF Service in initial days. Suppose there is a method which returns a List of Objects the proxy will be generated as method which returns an array of objects.
This problem is due to the default interpretation of collections. While generating proxy for the service all the collections are by default interpreted as arrays. That is why all the lists will be converted to arrays.
If you are generating proxy by adding service reference from visual studio directly, there will be a 'advanced' button. Click that button and select the System.Generic.List as your Collection. This will resolve the problem.
If you are generating proxy with svcutil here is the command to do the job.
svcutil.exe http://ServerName/ServiceName/Servic.svc?wsdl /collectionType:System.Collections.Generic.List`1
or in short svcutil http://ServerName/ServiceName/Servic.svc?wsdl /ct:System.Collections.Generic.List`1

for more information go through this link http://msdn.microsoft.com/en-us/library/aa347733.aspx
Here is a post which describes the basics of creating wcf service http://sivakrishnakuchi.blogspot.com/2010/05/how-to-create-wcf-service-application.html

Troubleshoot WCF service returning object with null fields

When you are working with WCF service for the first time, generally you will get this error for some reason. Here is the description of the error:
WebServiceReference.ServiceClient client = new WebServiceReference.ServiceClient();
WebServiceReference.ImplementationRequest req = new WebServiceReference.ImplementationRequest();
req =

Here the Method GetRequest will return an object of ImplementationRequest. Everything will run without any error but the req object will contain all null fields/ majority null fields.

Those nulls are due to error in generating the proxy for the Data Contract defined by the service. Verify that [DataMember] attribute tag is given for all the data fields and [DataContract] for the Class. If those attributes are missing, the object will be generated with null values. If all fields have the tags but the issue is not resolved, then the service reference should be re-added and the proxy should be re-generated. Then the problem will be resolved.

Here is a post which describes basics of creating a WCF service.

How to create a WCF Service Application

WCF is a buzz word now a days. Full form of WCF is 'Windows Communication Foundation'. Though it is not that much difficult to create a wcf service, sometimes its a bit tricky to configure the service correctly. I want to share simple steps to create and configure a WCF service here. But before to that we should go through some important terms of WCF.
  1. EndPoint: A service must have atleast one EndPoint. It is the component of the service that communicates with the client and provides the service operations.
  2. Address: This is the address of EndPoint. It may look like general Web URL.
  3. Bindings: Bindings are what define how an endpoint communicates with the outside world. Each endpoint must have a binding. The binding, which is simply a set of properties, defines things like the transport pattern, the security pattern, and the message pattern. Though most of these things are optional, binding should specify transport at least.
  4. Contracts: Contracts define format and structure of the message, also behavior of the service. Service contracts are well-formed XML documents, typically found in the format of WSDL or XSD. WCF supports the following three types of contracts.
  • Service Contract: It define the operations that a service will perform when executed. They tell about the service such as message data types, operation locations, the protocols the client will need in order to communicate with the service, and the operations the service provides.
  • Message Contract: Message contracts allow the control of SOAP messages that are produced and consumed by WCF.
  • Data Contract: Data contracts specifically define the data that is being exchanged between a client and service. The client and the service must agree on the data contract in order for the exchange of data to take place.
Now we are ready to create a wcf service application. Here are the steps to follow:
  1. Create a solution and add a new 'WCF Service Application' to that.
  2. This by default will add two important files Service1.svc and IService1.cs along with web.config file. Out of these IService1.cs is the interface to write all the signatures of our service and in Service1.svc.cs will have the actual implementation of the methods.
  3. In IService1.cs file we can check the default/ example contracts defined already.
  4. While adding a new method we need to declare that as [OperationContract] so that method can be accessed over service.
  5. All the classes, which need to be exchanged between server and client, should be declared as [DataContract] and all the members with [DataMember]. If these are skipped we will get null objects in the client end.
  6. Method complete implementation should be written in Service1.svc.cs. The logic to fetch or send the data objects will be here in this file.
  7. Deploy this service on IIS.
  8. This service can be used in any application with the url. To use the service methods, We need to generate proxy for this service. This can be done automatically through visual studio or manually with svcutil tool.
  9. To generate proxy automatically we need to add the service reference in our application. Whenever there is change in the service we need to update the service reference.
  10. With 'svcutil.exe http://<hostname>/<servicename>?wsdl' command the proxy will be generated manually. We can add the generated proxy in our application and use the service methods. Even here whenever there is a change in service, we need to change the file manually or the proxy file should be recreted.
  11. While using we need to create ServiceClient Object and through that object we can access all the methods in the service.
These are all the basic steps for creating and accessing a WCF service. All these will be available in any starter guide in a scattered manner. I just want to group all those to one place here.

21 April, 2010

How to Use Visual Studio Profiler

Recently I came to know that there is a inbuilt profiler in Visual Studio 2008, with which we can know the performance of our application. This can be started from VS Analyze tab.
Here are the simple steps to use this profiler.
  1. Open the project in visual studio and go to analyze tab -> profiler -> new performance session
  2. Performance Explorer will be added to the application. In that explorer click Launch performance wizard.
  3. A wizard will be opened with the application selected by default and three simple steps to set up new performance target
  4. Click on Launch with profiling button on the Performance Explorer. This will run the application, just like we run in debug mode.
  5. Go through the scenario, in which you want to know the performance one by one. But going for One at a time is suggestible.
  6. Once the scenario ends, Click on Stop profiler icon. This will automatically generates a report.
  7. Report provides various view of data. We can use functions view to check which functions taking so much time.
Using this profiler is very simple. But understanding the report generated by this is a bit difficult and needs some basic information on what is shown in the report. More details can be found at http://msdn.microsoft.com/en-us/magazine/cc337887.aspx

extendedProtectionPolicy tag problem: Workaround

When one use Windows7 to generate a WCF configuration file/ proxy that will generate some extra lines of code which will cause the problems in running the application.
The extra lines generated are not supported in Silverlight/WPF environment.
Those lines will look like
    <extendedprotectionpolicy policyenforcement="Never" />
There are some limitations for silverlight & WPF to use custombinding. You can read an article related to this at

Those extra tags can be deleted or commented to run the application.

17 April, 2010

Sys.InvalidOperationException: InitializeError Error #2104

I started development in silverlight recently. When everything is installed, i just started with a test application and on running the site i got the following exception.

Microsoft JScript runtime error: Sys.InvalidOperationException: InitializeError error #2104 in control 'Xaml1': Could not download the Silverlight application. Check web server settings

I am surprised to see this error as all the required things are installed. But I missed one small thing. That is to add silverlight application MIME type to the web server(IIS). After adding this MIME type, my application run without any error.

Steps to add MIME type in IIS6:
1) Goto the silverlight web application/ website properties.
2) Open HTTP Headers Tab and find MIME types region.
3) Click MIME Type button and add new MIME type
4) Type .xap and application/x-silverlight-app as extension and MIME types respectively.
5) Save your settings. This will add silverlight mime type to the sever, so that our application run without any error.

07 April, 2010

Linq: Query for multiple join conditions in Linq to SQL

This is common to join a table with another on multiple conditions, Like

Select * from Customer c
Join Invoice i on c.CustomerID = i.CustomerID and c.CustomerTypeID = i.CustomerTypeID

I need to write a Linq to SQL query for the same scenario. But the syntax for this query is a bit different to expect. The Linq query is as follows:

From c in DataContext.Customers
Join i in DataContext.Invoices on new { c.CustomerID, c.CustomerTypeID } equals new { i.CustomerID, i.CustomerTypeID }

*DataContext in the above query should be replaced with actual datacontext name.

30 March, 2010

C# DataFormatStrings

It is common practice to show data in GridViews in so many applications. Some times we have to format the incoming data such as currency, decimals and dates. To achieve this, we need to use "DataFormatString" property for GridColumn. There are some predefined format codes. They are as follows:

1. This will display a text Price: followed by the numeric text in currency format
Data Format String value : Price:
Applied to numeric and decimal data types.
The currency format is according to the culture info set in the web config file.

2. Integers are displayed in a zero-padded field four characters wide.
Data Format String value :
Applied to integer datatype only.

3. To show two decimal places
Data Format String value :
Applied to integer datatype only.

4. To round the numbers to one decimal place and are zero padded for numbers less than three digits.
Data Format String value :
Applied to numeric and decimal datatype only.

5. Long Date format
Data Format String value :
Applied to date and datetime datatype only.

6. Short Date format
Data Format String value : {0:d}
Applied to date and datetime datatype only.

7. Numeric Date format
Data Format String value :
Applied to date and datetime datatype only.

01 February, 2010

How to: show dynamic columns in SQL server Reporting services

How to display dynamic columns in Reports?
Let me explain what I mean dynamic here. I have a stored procedure which return some columns depending on User choice. In that case I dont have any clue about the columns which are in the report.

In plain english, whatever dataset is coming from database, I need to display that information in a table or matrix. The dataset may contain 2columns or 25 columns. How to achieve this?
After so much search I found an interesting property in SQL Server Reporting services for all Fields. There will be a property 'IsMissing' for each Field in the Dataset we defined in the report. To achieve dynamic behavior, I Created a table with all possible columns and toggled the visibility of the columns depending on their IsMissing status.

For each column in the table there will be a Visibility Expression set on Hide Property. For Example, say the column is binded to a column 'Name' the details cell will have text Fields!Name.Value. The visibility expression for this column will be =IIF(Fields!Name.IsMissing,true,false). Now the report will show the columns selected in the stored procedure only.

One Important thing to remember: When we are binding a dynamic dataset, SSRS dont have capability to detect the Fields present in the dataset. For this we need to specify the all possible fields in the Dataset, To do this follow the steps:
  • Goto Data tab in the report and open the dataset which returns dynamic columns
  • Click on the ... button besides the dataset to edit the dataset
  • A pop-up window for dataset will appear, in that window go to Fields tab
  • There we have to write all possible fields in the Dataset
  • Click OK and Preview your report
(If there are so many fields in the dataset it is very difficult to enter each column in the tab manually. I did face this, One shortcut way to do this is write dataset query so that it return all the required columns. The fields will be automatically filled. Now open the .rdl file in any text editor and change the Query part to actual query which return dynamic columns)

31 January, 2010

SSRS: Vertical Headings

This is one of the common requirement for most of the report developers. Many times we need to display table header vertically. When I came across this, I did a bit googling. But no where it is documented properly. Then I checked all the properies available for the Text box.
Vertical text with reports can be done with one small property change. There will be a property called 'WritingMode'. By default the writing mode will be lr-tb. If we change that to tb-lr the text in that text box will be written vertically.
Follow the steps to get vertical headers:
  • Go to the Textbox in which you need Vertical Text
  • Press F4 or Goto Properties Window
  • Search for WritingMode Property and change the value to 'tb-lr'
You can check your report preview for the changes.
Happy reporting!!