Monday, March 26, 2007

Add to Favorite in Firefox and IE

      I was looking for the javascript to add the link in favorite. I have tried window.external.AddFavorite(location.href, document.title) which is working only in IE. I need to do that for firefox also. After spending few mnutes on google, I found the code working in both.

<script type="text/javascript">
function bookmarksite()
         if (document.all)
             // For IE
             window.external.AddFavorite(location.href, document.title);
        else if (window.sidebar)
             // For Firefox
             window.sidebar.addPanel(document.title, location.href, "");
< /script>

< a href="javascript:bookmarksite();"> Add to favorites< /a>

Happy Programming !!

Saturday, March 24, 2007

Default button in ASP.NET

           I was creating a search page and I require that when user press enter key, by default search button's click event should be fire. I look around for the solution and find the easiest one. You just need to write below line in page load of  your code behind file.

Form.DefaultButton = btnSubmit.UniqueID;

           Here btnSubmit is the name of button.

Happy Programming!!!!

Monday, March 19, 2007

Nullable datatypes in C#

       In C# 2.0 there is a special datatypes called Nullable datatypes. You can assign null to them. Here is some basic information regarding Nullable data types.

        You can make any value types to nullable data types by writing as shown below.

public int? intA = null;

Fig - (1) Declaring integer data types so it can have null as value.

        Fig (1) shows how to declare data types do that it can have null as value. Now to check that if intA has non null value or it is null, you can use HasValue property.        

// Check HasValue method
if (intA.HasValue)
          Console.WriteLine("intA is not null");
          Console.WriteLine("intA is null.");

Fig - (2) Check that nullable type has non null value.

         As desribe above HasValue property returnd true if nullable types has non null value else returns false. To access the value of nullable types, "value" property is used as shown here, intA.Value. You can use nullable types in arithematic operation in same manner you are using integer (or any) types. If you are using them in Summation and if any of nullable type has value null than you will get null as result regardless of other variables value.

        Operator ?? is used check nullable value against null as shown below,

// Check ?? operator
int d = intA ?? -1;

Fig - (3) Check against null using ??.

       If  intA is null than d = -1, else d = value of intA which is intA.Value. So for default assignment you can use ?? instead of checking by HasValue property.

      I looked in to the IL for nullable data types and simple data types and here is what i found.

.field public int32 intB

Fig - (4) IL generated for simple integer.

.field public valuetype [mscorlib]System.Nullable`1<int32> intA

Fig - (5) IL generated for nullable integer.

      You can see in IL that "Nullable`1" attributes is added so that CLR can identify the nullable datatypes.

     I further look in to the Boxing of Nullable types.

int? i = 44;
// Boxing
object iBoxed = i; // iBoxed contains a boxed int.
// UnBoxing
int? i2 = (int?)iBoxed;

Fig - (6) Boxing and UnBoxing for Nullable types.

           One interested thing here is, Objects based on nullable types are only boxed if the object is non-null. If HasValue is false, then, instead of boxing, the object reference is simply assigned to null. The boxed object for nullable types and non nullable types are exactly same.

Happy Programming!

Friday, March 16, 2007

Remove/Delete element from page using JavaScript working in FireFox,IE,Opera

        Few days ago, I was recalling my Java script skill. I was generating Grid using java script script. Instead of using Display property ('none' or 'block') to show or hide the control, I was creating and removing element each time. Creating element is not a big deal. However the script for removing element is different in IE and Firefox.

       In IE, we can remove the element using, however this will not work in Firefox.


Fig -(1) Script to remove element in IE.

      In Firefox, you have to use,

var Node1 = document.getElementById("ParentControlID");

Fig -(2) Script to remove element in Firefox.

  Below is the sample code for the same.

      var Node1 = document.getElementById("Parent"); 
      var len = Node1.childNodes.length;
       for(var i = 0; i < len; i++)
            if(Node1.childNodes[i].id == "Child")

Fig -(3) Script to remove child element in Firefox.

Happy Programming !

Thursday, March 15, 2007

Create Serial Number Column using SQL Server

       There is a common requirement to show records with serial number in Grid.  The common scenario is, we take template field and label in Item Template. In Row_DataBound we can generate serial number using variable which is increamnted each time. The another approach is to genarate this column in SQL itself. Yes you can do that..! Here is a Query for that.

SELECT ROW_NUMBER()  OVER (ORDER BY  ColumnName1) As SrNo, ColumnName1,  ColumnName2 FROM  TableName

Fig- (1) Query to display Serial Number Column using SQL Server 

Happy Programming !

Sunday, March 11, 2007

Call parent window's javascript function from child window OR passing data from child window to parent window in javascript

                Hi, I was working on small application and I had a requirement as described here. I was creating a page in wjich user can add multiple cotact detail for him. The page has facility for add, delete and edit the contact. I was storing all these information in view state and finally on Save All button adding them to database. Afte the page is completed client has requested that user can have option to select contacts from database also. So I have to open a popup from which user can select multiple contacts and once user click on "Select" button on popup all the selected contacts should be available in grid on main page along with the contacts user has added manually.

               To achieve this I need have added hidden field on parent page and on child page I access that hidden field to set the IDs of selected contacts. Once the selected IDs are available on parent window, I need to postback the page so that I can take all the data for those IDs from database and add it to grid for edit or save.

              I was knowing that I can set "locationhref"  of parent window in child window and then close child window. However this will redirecr the parent page to new location (here new location is same page) but we loose viewstate data. This solution does not work in my case.

             One of my friend (we call him SP (Sehul the PRO) ) suggested me two ways to solve my problem. First, I can call "Click" event of parent window's button in child window so that parent window will post back and the code behind I had written for that button's click had;ler will be executed. Yes this is possible !!   Second, I can call javascript function written on parent window from child window. This function use ajax and execute server side code once I get selected contact IDs in hidden field.  

               Lets implement First logic. Below is the javascript to raise button click event on parent window from child window.

// Set parent window's hidden field value from child window
window.opener.document.getElementById(Client ID of Hidden Field).value = Selected IDs;

// raise button click event of parent window
window.opener.document.getElementById(Client ID Of Button).click();

// Close the child window

Fig - (1) Javascript on child window to raise button click event on parent window

           I had written this script on child page. Tis will raise button click event and in post back I wrote the logic of retrieving data from database for IDs set in hidden field and displayed them in grid.

          Now the second way, call javascript function of parent window from child window.

<script language="Javascript" type="text/javascript">
function CallAlert()
alert("This is parent window's alert function.");

Fig - (2) Javascript on parent window.

<script language="Javascript" type="text/javascript">

function SetParentWindowsHiddenFieldValue()
window.opener.document.getElementById("HiddenField1").value = document.getElementById("TextBox1").value;
return false;

function CallParentWindowFunction()
return false;

Fig - (3) Javascript on child window.

          Take two buttons on child window. C all "SetParentWindowsHiddenFieldValue" on click of one button and call "CallParentWindowFunction" on click of second button and see the result.

Happy Programming.

Tuesday, March 06, 2007

Storing and Retrieving Image in SQL Server

           Hi, I saw many developers are asking this questions in different forums. Recently I saw this question on MSDN forum and I thought let me write a blog on this. I know many of us found this too easy however for new bees its bit hard.

            In this article, I had used SQL Server 2005 as back end and C# as front end. SQL Server has "Image" data type to store the image. In Oracle and some other database you can use a data type which is used to store binary value (may be BLOB). I have created a simple aspx which has File upload control and a button. When user selects a file to upload, I am checking it for valid image type and converting it to array of Bytes. Then I will store that byte array into database. Below is the code,


if (objFileUpload.PostedFile !=null)
          if (objFileUpload.PostedFile.ContentLength > 0)
                  // Get Posted File.
                  HttpPostedFile objHttpPostedFile = objFileUpload.PostedFile;

                  // Check valid Image type. Create this function according to your need
                  if (CheckValidFileType(objHttpPostedFile.FileName))
                        // Find its length and convert it to byte array
 int intContentlength = objHttpPostedFile.ContentLength;

                       // Create Byte Array 
                        Byte[] bytImage =new Byte[intContentlength];
                        // Read Uploaded file in Byte Array
                        objHttpPostedFile.InputStream.Read(bytImage, 0, 

Fig -  (1)  Read Uploaded file (here Image) in Byte Array


       Pass this Byte array to you DAL and use it for storing image in database. I am using Enterprise Library as DAL so my code will look like,


Database db =DatabaseFactory.CreateDatabase();

string sqlCommand ="StoredProcedureName";

DbCommand dbCommandWrapper = db.GetStoredProcCommand(sqlCommand);

bytImage );

catch {throw; }

Fig -  (2)  Insert Image in to database


      This is how you can store the Image in database. Retrieving the image is the same process. Write a SP which will return your image. Store this value in a Byte Array. Once you get the image in Byte array, you just have to write it on form as shown below,


Byte[] bytImage =Byte array retrieved from database.
if (bytImage !=null)
          Response.ContentType ="image/jpeg";
          Response.Expires = 0; Response.Buffer =true;

Fig -  (3)  Code to display Byte array as Image on form.


        To use this at multiple places in your application, you create a page to which you can pass ID of Image and it will retrieve image from database and create image. To do this copy paste above code in aspx.cs file. Now on every page you require to show this image  take <asp:Image> on that page and set its ImageURL property to the path of newly created user control. See the code below,

<asp:Image ID="ViewImage" runat="server" />

Fig -  (4) Image control on any aspx page (Lets say Sample.aspx).

string strURL ="~/ViewImage.aspx?ID= 1 " ;
ViewImage.ImageUrl = strURL;

Fig -  (5)  Set Image URL for image control on code behind (Sample.aspx.cs)


       You can see the image will be displayed in your page where you had put Image tag.

Happy Programing.


Thursday, March 01, 2007

Impersonation using Code

      I was reading about impersonation and delegation. The most common way I found for impersonation is to write  a tag "<impersonate = "true" username="Name" password ="password" />"  in web.config file.  This will impersoname specific user to each request. I want to impersonate network user for only one request.

     In my project I have to create a directory which is shared on network and has rights set to network user. If I use impersonation in web.config file, all the request of my application executes under the rights of that network user ehich can be a security threat. I need to impersonate the user for a single request in which I need to create a directory on network shared location.

     Below is the code that impersonate the "Anonymous" (is explained in paragraph below code" user for perticular request.


HttpContext context = HttpContext.Current;   
// Get the service provider from the context           
 IServiceProvider iServiceProvider = context as IServiceProvider;
//Get a Type which represents an HttpContext           
Type httpWorkerRequestType = typeof(HttpWorkerRequest);
 // Get the HttpWorkerRequest service from the service provider           
// NOTE: When trying to get a HttpWorkerRequest type from the HttpContext           
// unmanaged code permission is demanded.           
HttpWorkerRequest httpWorkerRequest =
            iServiceProvider.GetService(httpWorkerRequestType) as HttpWorkerRequest;
 // Get the token passed by IIS           
IntPtr ptrUserToken = httpWorkerRequest.GetUserToken();
// Create a WindowsIdentity from the token           
WindowsIdentity winIdentity = new WindowsIdentity(ptrUserToken);           
Response.Write("Before impersonation: " + WindowsIdentity.GetCurrent().Name + "<br>");
// Impersonate the user           
WindowsImpersonationContext impContext = winIdentity.Impersonate();
Response.Write("Impersonating: " + WindowsIdentity.GetCurrent().Name + "<br>");
// Place resource access code here     
// Stop impersonating           
Response.Write("After Impersonating: " + WindowsIdentity.GetCurrent().Name + "<br>");

Fig - (1) Impersonate user using code.

     By saying  "Anonymous" user,  the user which is set for Anonymous account in IIS. By default this will be "IUser_MachineName".  Change this to Network user (or user you want to impersonate) by entering username and password and uncheck "Allow IIS to control password" check box.

   To do this click on "Start --> Run " and write " inetmgr". It will show IIS. Right click on virtual directory of your application and select property. Click on "Directory Security" tab. Click "Edit" button at "Anonymous Access and Authentication Cotrol" panel. Here you can change user name and password.

Happy programming.