Skip to main content

Posts

Showing posts from 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"> <asp:ListItem>-select-</asp:ListItem> <asp:ListItem>Item1</asp:ListItem> <asp:ListItem>Item2</asp:ListItem> </asp:DropDownList> 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="se

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 //installed. //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; }

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 a

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() { ale

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

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. Reason: 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. Solution: 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

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 = client.GetRequest(); 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. Solution: 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 t

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. 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. Address: This is the address of EndPoint. It may look like general Web URL. 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. Contracts: Contracts define format and structure of t

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. Open the project in visual studio and go to analyze tab -> profiler -> new performance session Performance Explorer will be added to the application. In that explorer click Launch performance wizard. A wizard will be opened with the application selected by default and three simple steps to set up new performance target Click on Launch with profiling button on the Performance Explorer. This will run the application, just like we run in debug mode. Go through the scenario, in which you want to know the performance one by one. But going for One at a time is suggestible. Once the scenario ends, Click on Stop profiler icon. This will automatically generates a report. Report provides various view of data. We can use functions view to check which functions taking

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 <transport>      <extendedprotectionpolicy policyenforcement = "Never" /> </transport> There are some limitations for silverlight & WPF to use custombinding. You can read an article related to this at http://msdn.microsoft.com/en-us/library/cc896571(VS.95).aspx Workaround: Those extra tags can be deleted or commented to run the application.

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 wit

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.

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: {0:C} 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 : {0:D4} Applied to integer datatype only. 3. To show two decimal places Data Format String value : {0:N2} 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 : {0:000.0} Applied to numeric and decimal datatype only. 5. Long Date format Data F

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

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!!