Tuesday, December 18, 2012

How to get HTML Table cell value on click event?


In some of the cases we want to access the value of HTML table cell value when we click on particular cell, this can be simply done using client side code only.

Here I am giving simple code to access HTML table cell value.

 <script type="text/javascript">
        $(document).ready(function () {
            $('table[id$=TableName] tr>td').click(function () {
                alert($(this).parent()[0].cells[0].innerText);
            });
        });
 </script>

This is JavaScript code; here I have used JQuery to get value. Here first I have integrated one function with table cell. This function will be executed when

we will click on cell. To get cell value I have written this line of code-

 alert($(this).parent()[0].cells[0].innerText);

This alert() will display value of cell.



Thanks

Wednesday, November 28, 2012

How to implement data annotation in MVC Razor?


Validation  :

Validation is most important process for any of the application. This process prevents wrong input to the application. For generating the meaningful output it is must that input should be meaningful because based on input only application generates output.

Like other application we can also implement validation process for our MVC application also, in this article, I am explaining – How to implement validation using data annotation in MVC application.

To implement validation I have used Data annotation, for this first we need to use “System.ComponentModel.DataAnnotations” namespace in our application. Here I am giving step by step implementation.

Step1:

Create one simple MVC Application, for this open Visual Studio and select “New Project” option then select “Asp.Net MVC Application Template”.

After creating new application you will find default MVC folder structure.

Step2:

Now right click on “Models” folder and add one Class, I have added by named- “EmployeeModels.cs”.

Here I have declared some properties like this-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;  

namespace DataAnnotationArticle.Models
{
    public class EmployeeModels
    {
        public int ID { get; set; }
        

       //Validation for empty input
        [Required(ErrorMessage ="First Name can't be empty.")]
        public string FisrtName { get; set; }



       //Validation for length of string
        [StringLength(10, ErrorMessage = "Last Name length can't be greater than 10.")]
        public string LastName{ get; set; }
       
    }
}
 

As you can see that I have added reference of  “System.ComponentModel.DataAnnotations” Namespace which will help us to implement validation over data using data annotation.

For this I have set some validation over properties like this-

        [Required(ErrorMessage ="First Name can't be empty.")]
        public string FisrtName { get; set; }

        [StringLength(10, ErrorMessage = "Last Name length can't be greater than 10.")]
        public string LastName{ get; set; }


We have other properties also based on our need we can implement other validation.

Step3:

Now add one controller, for this right click on “Controller” folder and click on “Add Controller” option, I have added by named- “EmployeeController.cs”. I have written controller code like this-

public ActionResult EmployeeView()
        {
            return View();
        }


Now we have to bind this ActionResult with one View.

Step4

To bind this ActionResult with View, Just right click on “EmployeeView()“ and you will get menu list here click on “Add View …” option after that you will get one dialog, like this-


View


Fill the details here like I have given Now Finally say “OK”, then View will be created automatically with following lines of code-

@model DataAnnotationArticle.Models.EmployeeModels

@{
    ViewBag.Title = "EmployeeView";
}

<h2>EmployeeView</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>EmployeeModels</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.FisrtName )
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.FisrtName )
            @Html.ValidationMessageFor(model => model.FisrtName )
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.LastName )
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.LastName )
            @Html.ValidationMessageFor(model => model.LastName )
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>


Here we can see that, one user input form is generated with validation. This is because of “Create” option which we have set at the time of view creation.   For validating user input code is already written, this code will perform user validation based on this JavaScript files-

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>


Finally our solution explorer structure will be like this-



MVC


Now you are done, to test the application just run your application and give some invalid input to the control like I have given , Here we can see the output-




MVCDataAnnotation



Here we can see that the validation which we have given in EmployeeModels.CS that is taking place for wrong input. Like this we can validation other controls also.




Thanks


Tuesday, November 27, 2012

How to add ToolTip for DropDownList Items?

  
ToolTip-

ToolTip is a small piece of information, which is used to show some idea or information about control and control's functionality.  This is most important when we are using icons for performing the operations. In every application it plays very important role either for web applications or windows applications.

Generally it is invisible but when we put mouse over any control then related ToolTip automatically gets visible.

In this article, I am explaining - How to add ToolTip for DropDownList Items?

Generally DropDownList doesn't have any direct property or method to set ToopTip for DropDowbList items; here I am giving simple code to add ToopTip for DropDownList items.

Write this code in Page_Load() event-

 protected void Page_Load(object sender, EventArgs e)
    {
        foreach (ListItem  item in DropDownList1.Items)
        {
            //Adding ToolTip for each item of DropDownList
              item.Attributes.Add("title", "item - "+ item.Text );
        }
    }


In above code, I have used foreach loop to iterate each item of DropDownList. Here insidse loop, I am using Attributes.Add() method to add title (ToopTip) to each item.
    
    //Adding ToolTip for each item of DropDownList
   item.Attributes.Add("title", "item - "+ item.Text );


 Here "title" is client side property of controls, using this property ToolTip can be added for any controls.  Using Attributes.Add() method we can also add any other client side method to any control.
 
The output of this code will be this this-


ToolTip

Thanks


How to disable back button of browser?


This is common requirement for all the web application to disable back button of browser after log-out. But there is no direct method or property to disable back button of browser. This only depends on browser cache or history, if browser contains any history or cache then back button will be active after log-out also.

Here I am explaining - How to disable back button of browser?

This can be possible using only after clearing history or cache of browser.
or
Don't allow browser to keep history or cache.

For this we can add this code for all the pages to which we don't want to allow cache.

Here is code-

  protected void Page_Load(object sender, EventArgs e)
        {
            Response.Buffer = true;
            Response.ExpiresAbsolute = DateTime.Now.AddDays(-1d);
            Response.Expires = -1000;
            Response.CacheControl = "no-cache";
        }



 In this code, I am written code to disallowing browser to cache the page. So that even after browsing the page browser will not keep page as cache or history.

This code should be included for all the pages.


Thanks

Friday, November 2, 2012

How to change NewDataSet xml root name while creating xml using WriteXml() method of Dataset?


This is default behavior of WriteXml() method when we create xml then it adds  <NewDataSet> node as root xml node and <Table> as child node. In this article, I am explaining- How to change <NewDataSet> xml root name while creating xml using WriteXml() method of Dataset?

Let first see the default case-

Suppose you we have one DataSet object ds and we are filling it will data source, like this-

Dataset ds= new DataSet();
ds= datasource;


After that we are using WriteXml() method to create XML, like this-

ds.WriteXml("FileName");

Then in this case output will be like this-

<NewDataSet>
  <Table>
    <Emp_ID>717</Emp_ID>
    <Emp_Name>Jitendra Faye</Emp_Name>
    <Salary>35000</Salary>
  </Table>
----------
----------
----------
</NewDataSet>


Here we can see that <NewDataSet> and   <Table> is default tag here.

Now to change these default tag follow this code, Here I am changing <NewDataSet> tag as <EmployeeRecords> tag and <Table> tag as <Employee> tag.

Here is code-

Dataset ds= new DataSet();
ds= datasource;


//Giving Name to DataSet, which will be displayed as root tag

ds.DataSetName="EmployeeRecords";

//Giving Name to DataTable, which will be displayed as child tag

ds.Tables[0].TableName = "Employee";

//Creating XML file
ds.WriteXml("FilePath");


Now after executing this above code generated XML file will be like this-

<EmployeeRecords>
  <Employee>
    <Emp_ID>717</Emp_ID>
    <Emp_Name>Jitendra Faye</Emp_Name>
    <Salary>35000</Salary>
  </Employee>
----------
----------
----------
</EmployeeRecords>



Here we can see that DataSet name is coming as root tag and DataTable name is coming as child tag.

Note-

Before giving name to DataTable (ds.Tables[0].TableName) first check that it should not be null otherwise it will cause an error.



Thanks


Thursday, November 1, 2012

How to edit word document using Asp.Net?


Problem -
 

Editing word document is not an easy task in ASP.Net, because we don't have any direct option to open server copy of word document. When we open any word document from server machine then first that document is downloaded to client machine's temp folder and then it is displayed. So if we will make any changes to that opened document then that changes will be saved in only client machine not in server machine.
 

Means the changes will not be reflected directly to server copy of word document.   
 

I have done some RND in this problem and came with one workaround. Hope this solution will help you.


Workaround-

There are some steps for this workaround.

Step 1: Store your document in any server folder.

Step 2: Read that document from server and convert to HTML Document.

Step 3: Now load converted HTML document to any HTML editor, for this you can use any free editor, there are lot of free editors are available in the market you can use anyone.

See this link for free HTML editors -

http://www.techsupportalert.com/best-free-html-editor.htm
Step4: Start editing document which is displayed in HTML editor using HTML editor ToolBox.

Step 5: After editing document get updated data from HTML editor and load to MemoryStream object.

Step 6: Finally again convert that MemoryStream object data to word file.

By following these steps you can edit word document online for this there is no need to use any paid third party controls.

Code Implementation-

For this implementation, I am using following tools-

1. Aspose DLL –   For converting Word document to HTML document and vice versa.
(I am using evaluation copy)

2. nicEditor HTML Editor - for showing and editing converted HTML document.
(It is free)

Now I have designed .aspx page like this-

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="EditDocument.aspx.cs" Inherits="OnlineEdit.EditDocument"
    ValidateRequest="false" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script src="NicScript/nicEdit.js" type="text/javascript"></script>
    <script type="text/javascript">
        bkLib.onDomLoaded(function () {
            new nicEditor({ fullPanel: true, iconsPath: 'NicScript/nicEditorIcons.gif' }).panelInstance('docArea');
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table border="1">
            <tr>
                 <td>
                     <textarea cols="100" rows="20" id="docArea" runat="server"></textarea>
               </td>
            </tr>
            <tr>
                 <td align="center">
                   <asp:Button ID="btnLoad" runat="server" Text="Load Doc" Width="70px" OnClick="btnLoad_Click" />
                        
                   <asp:Button ID="btnSave" runat="server" Text="Save" Width="70px" OnClick="btnSave_Click" />
                 </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>



Note-   Set ValidateRequest="false"


Here I have taken one TextArea control by named – docArea. This will be used for showing and editing Word document. For this I have bounded nicEditor editor with TextArea. Using these lines of code-

    <script type="text/javascript">
        bkLib.onDomLoaded(function () {
            new nicEditor({ fullPanel: true, iconsPath: 'NicScript/nicEditorIcons.gif' }).panelInstance('docArea');
        });
    </script>


Pictorial representation will be like this-

Edit word document using ASP.Net


Now write following code in code behind-

protected void btnLoad_Click(object sender, EventArgs e)
        {
            string strFileName = Server.MapPath("docs\\" + "Eggheadcafe.doc");
            
             //Loading word document to HTML editor
            LoadDoc(strFileName);
        }

Here, I am reading Word document from docs directory (which is present in my solution structure) and passing to LoadDoc () function.

//Function to convert word document to HTML document after that loading into HTML editor
        private void LoadDoc(string strFileName)
        {
            //Loading  doc file using Document class of Aspose DLL
            Document doc = new Document(strFileName);

             //SaveOptions for image which is present in Word document
            HtmlSaveOptions options = new HtmlSaveOptions(SaveFormat.Html);
            string strImagePath = Server.MapPath("docs\\");

             //Location to save images which is included in word document
            options.ImagesFolder = strImagePath;
            options.ImagesFolderAlias = "docs\\";

           //Setting SaveFormat to save as HTML document
            options.SaveFormat = SaveFormat.Html;

           //Saving  file as HTML document
            doc.Save(strFileName + ".html", options);

             //Reading converted HTML file in Editor
            StreamReader sr = new StreamReader(strFileName + ".html");
            string strValue = sr.ReadToEnd();
            docArea.Value = strValue;
             sr.Close();
            sr.Dispose();
        }



In above function I have used Document class of Aspose dll to load Word document.
            Document doc = new Document(strFileName);

After loading document, we need to set the path for saving images which is included in Word document, for this I have used HtmlSaveOptions class.
       
            HtmlSaveOptions options = new HtmlSaveOptions(SaveFormat.Html);
            string strImagePath = Server.MapPath("docs\\");

//Location to save images which is included in word document
            options.ImagesFolder = strImagePath;
            options.ImagesFolderAlias = "docs\\";


Finally to save Word document as HTML document we need to set SaveFormat

            options.SaveFormat = SaveFormat.Html;
            doc.Save(strFileName + ".html", options);


Once these lines of code will be executed Word document will be converted to HTML document. Now we can load this HTML document to HTML editor.

             //Reading converted HTML file in Editor
            StreamReader sr = new StreamReader(strFileName + ".html");
            string strValue = sr.ReadToEnd();
            docArea.Value = strValue;
             sr.Close();
            sr.Dispose();


Output will be like this, when we will click on Load() button-

Edit word document using ASP.Net


Now to save edited document use the following code-

    protected void btnSave_Click(object sender, EventArgs e)
         {
             //Getting Text of HTML editor and writing into memorystream class object
            MemoryStream storeStream = new MemoryStream();
            StreamWriter sw = new StreamWriter(storeStream);
             sw.Write(docArea.Value);
             sw.Flush();

             //Again saving edited document with same name
            string strFileName = Server.MapPath("docs\\" + "Eggheadcafe.doc");
            Document doc = new Document(storeStream);
             doc.Save(strFileName, SaveFormat.Doc);
            storeStream.Close();
            storeStream.Dispose();
            sw.Close();
            sw.Dispose();
        }



In above code, first I am getting all the text of TextArea and writing to MemoryStream class object.

//Getting Text of HTML editor and writing into memorystream class object    
           MemoryStream storeStream = new MemoryStream();
            StreamWriter sw = new StreamWriter(storeStream);
            sw.Write(docArea.Value);
            sw.Flush();


After storing data into MemoryStream class object, I am using Document class of Aspose dll to write that data into same word file.

             //Again saving edited document with same name
            string strFileName = Server.MapPath("docs\\" + "Eggheadcafe.doc");
            Document doc = new Document(storeStream);
             doc.Save(strFileName, SaveFormat.Doc);
            storeStream.Close();
            storeStream.Dispose();
            sw.Close();
            sw.Dispose();


Now you are done.  We can test edited word document by going to same location where we have stored Word document.

Limitations-

1. One Extra HTML document will be created

2. You need to explicitly delete that HTML document after editing.

3. Time taking process because first you need to convert word doc to HTML doc and after editing again you have to create word doc.

4. Formatting can be lost, it depends on HTML editor.


Thanks


Wednesday, October 24, 2012

How to get client machine Outlook username using Asp.Net ?


If we want to get server Outlook user name then it is easy to get because for this we can simply use “Microsoft.Office.Interop.Outlook” Namespace, and after creating the object of “Microsoft.Office.Interop.Outlook.Application“ Class we can get server Outlook user name.

But we face the problem when we want to get Client side (Client machine) Outlook user name, because “Microsoft.Office.Interop.Outlook” Namespace targets to server side machine. In this article, I am explaining - How to get client machine Outlook username?

As we want to get client machine Outlook user name so we have to write code which will target to client machine, so I have used JavaScript for this. Using JavaScript I am dealing with ActiveX object so it is must that our browser should allow ActiveX control.

For this we need to set following setting for our browser-
1. Open Internet Explorer
2. Go to "Internet Options Settings"
3. Open "Security Tab"
4. Mark as enable for "Initialize and script ActiveX controls option"

Like this-



Internet options


This setting will help to deal with client machine Outlook object.

Now use following code -

 protected void btnGetOutlookUser_Click(object sender, EventArgs e)
    {
       string script = " <script  type ='text/javascript' >";
       script = script + " try {";
       script = script + "obj = GetObject('', 'Outlook.Application');";
       script = script + "alert(obj.Session.CurrentUser.Address);";
       script = script + "}";
       script = script + "catch (e) {";
       script = script + "alert(e.Message + ' Not Supported');";
       script = script + "}; ";
       script = script + "</script>";
       ClientScript .RegisterClientScriptBlock(this.GetType(),"key", script);
    }



In this code, I have used JavaScript code. Using GetObject() method I am creating object for Outlook Application that will target to client machine Outlook object.

obj = GetObject('', 'Outlook.Application');

Now to get the Client Session, I am using Session property of this object (obj), using this Session property we can deal with all options of Outlook for client machine.
Like I have used, to get user name, I have used this code-

obj.Session.CurrentUser.Address

Here Address will point to Outlook user name of Client machine, for different client machine this line of code will give different user name based on outlook user name.

Output will be like this-



Outlook Username



Note- This example will work only with Internet Explorer.


Thanks
     

Monday, October 22, 2012

How to wrap Label text in asp.net?


If you don't wrap Label text in page, then it will disturb display settings of page controls, because Label displays text in single line.

To solve your problem just wrap the Label, using word-break CSS.

For this follow these steps-

Step1.  On top of the page, define this CSS in style section.

<style type="text/css">
        .clsWrap
        {
            word-break: break-all;
        }
</style>


Step2.  Now set this CSS to Label control using CssClass Property.

<asp:Label ID="lblMessage" runat ="server" CssClass="clsWrap"  width="100px"></asp:Label>


Now done, after crossing 100 PX length of Label text will be in next line. Same code you can use for GridView Label control also, means if you are putting Label control inside GridView Template then use same solution.



Thanks



Monday, October 15, 2012

How to add custom action to Windows Installer using C# ?


Visual Studio Package and Development wizard provides facility to create setup of your .Net Application. But in some cases we want to control the installation steps using custom action, means we want to add some custom functionality while installing the application.

Using custom action we can handle functionalities like-

-    Setting registry value while installation
-    Reading registry value while installation
-    Serial key implementation

Etc.

In this article, I am explaining - How to add custom action to Windows Installer in C#?

Here I am giving complete steps with pictorial representation. Follow these steps -

Step1: First, develop your application with required functionality.

Step2: For performing your custom action while installing application, we need to add "Installer Class" in application.  Add one "Installer Class" using "Add New Item" to the project like this-



Installer


Step 3: After adding Installer Class to the project , add your custom functionality , Here I am adding some code in "MyInstaller.cs" file-


//Code to perform at the time of installing application
public override void Install(System.Collections.IDictionary stateSaver)
        {
            System.Windows.Forms.MessageBox.Show("Installing Application...");
        }

//Code to perform at the time of uninstalling application
        public override void Uninstall(System.Collections.IDictionary savedState)
        {
            System.Windows.Forms.MessageBox.Show("Uninstalling Application...");
        }



Here I have added to events, this is for custom functionality, you can write your own code which you want to perform at the time of Installing and uninstalling application.

Step 4: Now set your application in "Release Mode" and build it.

Step 5: Now we have to add setup project for developed application, so right click on "Solution Explorer" and click on "Add -> New Project option".

Here you will get Project Templates dialog, Select "Visual Studio Installer" from "Other Project Types" option.

See this Image-


Setup


Step 6: After adding Setup project to solution, set project output for Setup project. For this right click on setup project and click on "Add -> Project Output"

you will get "Add project Output Group Dialog”, Here you need to set some setting like this-



Add Project Group


After setting click on "OK" button.

Step 7: Now to add custom action, again right click on "Setup project" and click on "View -> Custom Actions".


Custom Action



Now to set Custom action for installation right  click on "Install" click on "Add Custom Action",

Here double click on "Application folder" and select Primary output from Myproject and click on "OK" button.


Primary Output



Step 8: Repeat same for UN-installation process also.

Step 9: Finally your solution structure will be like this-


Solution Explorer

 

Step 10: Now build setup project and finally build the solution. Now you are done.

To test the complete process just try to install your application now, while installing application you will get message like this-



Installing Application



This is the same message which we have given in Install () event. Means whatever the action or code we will write in this event that will be perform at the time of installing application.

//Code to perform at the time of installing applicationpublic override void Install(System.Collections.IDictionary stateSaver)
        {
            System.Windows.Forms.MessageBox.Show("Installing Application...");
        }

And when you will uninstall application you will get message like this-


Uninstalling Application

 Here also we can see that the code which we have written in Uninstall () event that is executing.
Like Install () event we can handle Uninstall () event also.


//Code to perform at the time of uninstalling application
        public override void Uninstall(System.Collections.IDictionary savedState)
        {
            System.Windows.Forms.MessageBox.Show("Uninstalling Application...");
        }



These complete helps you to handle custom action while installation or uninstallation, Using these step we can implement serial key for application, means while installing application we can set expiration time for application and while uninstallation we can delete application related registry settings.



Thanks



Sunday, October 14, 2012

How to maintain selected JQuery tab during post-back?


JQuery -

JQuery is java-script file which provides built-in client side functionality. By including JQuery plug-in to page we can use these built-in functionality. It is just like a Header files in C, means to use JQuery functionality it is must that first we need to include JQuery plug-in to the page.

In this article, I am explaining - How to maintain selected JQuery  tab during post-back?

While using JQuery tab if we are making any post-back then JQuery tab doesn't maintain selected tab. Her I am giving code to maintain JQuery selected tab in post-back.

For this, I have used HiddenField variable to maintain the value of selected tab index. To explain this, I have designed .aspx page like this-

 <head runat="server">
    <link href="Css/JQuery -ui-1.8.20.custom.css" rel="stylesheet" type="text/css" />
    <title>hi</title>
    <script src="Scripts/JQuery -1.4.1.min.js" type="text/javascript"></script>
    <script src="Scripts/JQuery -ui-1.8.20.custom.min.js" type="text/javascript"></script>
    <script type="text/javascript">

         $(document).ready(function () {
            $('#tabProfile').tabs({ selected: $("#<%= hdnTabIndex.ClientID %>").val() });
        });
      
       function funHoldValue(index) {
            $("#<%= hdnTabIndex.ClientID %>").val(index);
        }
    </script>
</head>

<body>
    <form id="form1" runat="server">
    <asp:HiddenField ID="hdnTabIndex" runat="server" Value="0" />
    <div id="tabProfile" style="width: 50%;">
        <ul>
            <li><a href="#tabsGeneralProfile">General profile</a></li>
            <li><a href="#tabsEduProfile">Educational profile</a></li>
            <li><a href="#tabsProfProfile">Professional profile</a></li>
        </ul>
        <div id="tabsGeneralProfile" style="text-align: center;">
            General Profile
            <br />
            <asp:Button ID="btnGeneral" runat="server" Text="OK" OnClientClick="funHoldValue(0);" OnClick="btnGeneral_Click" />
         </div>
        <div id="tabsEduProfile" style="text-align: center;">
            Educational Profile
            <br />
            <asp:Button ID="btnEducation" runat="server" Text="OK" OnClientClick="funHoldValue(1);" OnClick="btnEducation_Click" />
        </div>
        <div id="tabsProfProfile" style="text-align: center;">
            Professional Profile
            <br />
            <asp:Button ID="btnProfession" runat="server" Text="OK" OnClientClick="funHoldValue(2);" OnClick="btnProfession_Click" />
        </div>
    </div>
    </form>
</body>
 

Here we can see that, I have taken one HiddenField variable by named- hdnTabIndex.
In this code I my holding value of selected tab using this variable. I have declared one client side function by named- funHoldValue(). 

Using funHoldValue () function, I am setting selected tab value to  HiddenField variable. In this example I have designed 3 tabs, and for holding selected tab value I am using code like this-

  <asp:Button ID="btnGeneral" runat="server" Text="OK" OnClientClick="funHoldValue(0);" OnClick="btnGeneral_Click" />

Here I am passing the index for setting to HiddenField, like this-

 OnClientClick="funHoldValue(0);" 
 OnClientClick="funHoldValue(1);"   
 OnClientClick="funHoldValue(2);"   

 After setting value to HiddenField we have to set selected tab while post-back for that I have used this code-

$(document).ready(function () {
            $('#tabProfile').tabs({ selected: $("#<%= hdnTabIndex.ClientID %>").val() });
        });

This code will get value from HiddenField and set that value or index as selected tab index in JQuery tab. Here output will be like this-


JQuery Tabs




Thanks


Tuesday, October 9, 2012

How to refresh page automatically? - 4 different ways


Some of the sites those work on the basis of updated data like - Cricket score updates, Share market data, For those kind of sites it is required that to update or refresh the page automatically. In this article, I am  explaining - How to refresh page automatically?

Here I am showing 4 different ways to update or refresh the page automatically. This can be done using following ways-

1. Client side code
2. Server side code

Client side code-

In client side we have following options for this-

A. Using meta tag-

By setting the attributes value in meta tag you can auto refresh the page.

Like this-

<head runat="server">
 <meta  http-equiv="REFRESH" content="1">
</head>
 

B. Using reload() -

reload() function refresh the page explicitly, So use this function inside  setTimeout() function and give interval for setTimeout().

Like this-

<script type="text/javascript">
        function RefreshPage(time) {
            setTimeout("location.reload(true);", time);
        }
</script>


Now call this function on body load() event.

<body onload="RefreshPage(1000);">


Here 1000 is time to refresh the page after particular interval, you can change this time.

Server side code-

In server side we have following options for this-

A. Using Response.AddHeader()

you can set value for refreshing the page in Page_Load() event.

Like this-

protected void Page_Load(object sender, EventArgs e)
{
   Response.AddHeader("Refresh", "1000");
}


B. Using Timer control.

By setting the Interval and Enabled property you can refresh the page.

Like this-

first set Enabled property of Timer control= true
now set Interval property of Timer control= 1000 (your desired value)

last  you need to implement Tick() event for Timer Control-

protected void TimerControl1_Tick(object sender, EventArgs e)
{
    //Your code
}



Now done, these are some possible ways for auto refreshing the page; you can use any of these.



Thanks


Monday, October 8, 2012

How to compare DataTables?


Data Tables can be easily compared. This comparison can be done using Merge () and GetChanges() methods of DataTable class object.

In this article, I am taking 3 DataTable class object- dataTable1, dataTable2 and dataTable3
Here dataTable3 will hold the comparison result of dataTable1 and dataTable2.

Here is simple code-

//Merging datatable2 to data table 
dataTable1.Merge(dataTable2);

//Getting changes in dataTable3

 DataTable dataTable3= dataTable2.GetChanges();


In above lines of code, first I am merging datatTable1 and dataTable2 and combined result will be stored in dataTable1. Finally to get changes I am using GetChanges() method of dataTable1 object.

DataTable dataTable3= dataTable2.GetChanges();

Here GetChanges() method will return one DataTable class object and  returned result will be stored in dataTable3 object.



Thanks

How to pass more than one values from one page to another page using javasctipt?


There is lot of methods for passing data from one page to another page, but here I am explaining, 
How to pass more than one values from one page to another page using java-script?

I have created one example for showing this process, here is code-
Source page code (SourcePage.aspx)-

This is client side Function-
        
 <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        function TransferData() {
            var value= new Object();
            value.item1 = $('input[id$=txtItem1]').val();
            value.item2 = $('input[id$=txtItem2]').val();
            showModalDialog('SecondPage.aspx', value);
            return false;
        }
    </script>


In above JavaScript code, I have created one function called- TransferData(). In this function, first I have created one var type as object using this line-

var value= new Object();

Now, using JQuery I am getting control's values and assigning to "value" variable, here "item1" and "item2" are dynamic properties for value variable.

       value.item1 = $('input[id$=txtItem1]').val();
       value.item2 = $('input[id$=txtItem2]').val();


After that using showDialog() , I am passing value variable to next page.

   showModalDialog('SecondPage.aspx', value);

All these value can be accessed in next page using same properties.

Body Part-

  <div>
        <table align="center">
            <tr>
                <td>
                    Value1
                </td>
                <td>
                    <asp:TextBox ID="txtItem1" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Value2
                </td>
                <td>
                    <asp:TextBox ID="txtItem2" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td colspan="2" align="center">
                    <asp:Button ID="btnSend" runat="server" Text="Pass Data" OnClientClick="return TransferData();" />
                </td>
            </tr>
        </table>
    </div>



Now to pass data of this page to another page, I have called TransferData() function in onClientClick() event of Button.

Now SecondPage code (SecondPage.aspx)-

This is client side Function- 

 <script type="text/javascript">
        function FetchValues() {
            var value= window.dialogArguments;
            if (value!= null) {
                var item1 = value.item1 ;
                var item2 = value.item2;
                alert('item1 =' + item1 + ', item2 =' + item2 );
            }
            return false;
        }
    </script>


To get passes data from source page, I have written one client side function FetchValues(). In this function, I am getting passed data variable using this code-

var value= window.dialogArguments;

Now to get values, first I am checking for null and then accessing value like this-

   if (value!= null) {
                var item1 = value.item1 ;
                var item2 = value.item2;
                alert('item1 =' + item1 + ', item2 =' + item2 );
            }


Body Part-

<body onload="FetchValues();">
    <form id="form1" runat="server">
    <div>
    </div>
    </form>
</body>


I have called FetchValues() function in onload() event of body, based on our need this function can be called anywhere.

Note-
In this code I have used JQuery, so don't forget to include JQuery plug-in in your page.


Thanks


Sunday, September 9, 2012

How to delete nth row of the table in SQL Server?


If database table contains any primary key value then performing update and delete operations are not big task. But generally we face problem when we don’t have any primary key in table, on that case we can’t target to any particular column for deleting or updating records because that column can contain duplicate values.

In this article, I am explaining –

How to delete record based on row number? 
Or
How to delete nth row of the table?           
Or
How to delete record without primary key?           
 
                             
To perform this operation we have to use ROW_NUMBER() function of SQL Server. This function will help us to get nth row which we want to delete from table.

ROW_NUMBER()- 

ROW_NUMBER() is function in SQL Server which return sequential number for each record in result set. This returned number can be used as an identity for each record which is present in result set. When we don’t have any primary key in table then it is very useful to identify the record in result set. Using this sequential number we can perform operation like delete and update even we don’t have primary key for table.

Here is syntax to delete nth row from the table-

Syntax-

DELETE  Record
FROM    (
        SELECT  rowno = ROW_NUMBER() OVER (ORDER BY (Column_Name))
        FROM    Table_ame
        Where Condition
        ) AS Record
WHERE   Record.rowno = RowIndex


Here RowIndex is an index of the row which you want to delete from table. Here inner query will return result set including sequential number for each record and this will be ordered based on column_name which will be passed in ORDER BY clause. Finally outer query will perform delete operation based on given condition . 

Example-

Suppose if we want to delete 5th row of the Employee table then query will be like this-

DELETE  Record
FROM    (
        SELECT  rowno = ROW_NUMBER() OVER (ORDER BY (EmpName))
        FROM    Employee
        ) AS Record
WHERE   Record.rowno = 5


In above query, First inner query will be executed, which will generate result set over Employee table including row number over EmpName. Finally outer query will perform delete operation over result of inner query with given condition-

WHERE   Record.rowno = 5

This condition will detect 5th row from inner result and delete record from the table. In this example I didn't put any condition for inner query but if we have requirement then we have put where condition also to get result set like I have written in given syntax.


Thanks

Tuesday, September 4, 2012

How to change sort order of crystal report by using code?



Crystal report -

Crystal report is a tool which provides facility to display data in reporting format. It also support functionality like sorting of data based on sort field. This sorting can be done in design time and run-time also.


Sorting data using sort field is easy while design time but if we want to sort data in run-time then some time it can generate error. The most common error for run-time sorting is-


"The sorting already exists"


In this article, I will explain -
How to change sort order of crystal report by using code?

First I will tell what the reason for this error is and how we can solve this error.


Reason-


This error comes when we are trying for setting sort field for crystal report using code and that particular sort-field is already added as sort order field for crystal report in design time.


Example-


Suppose we want set "Name" as sort order field and this field ("Name") is already present as sort order in design time then it will generate error.


Workaround-


Simple workaround for this problem is that swapping of sort order fields.

Suppose you have added two fields (firstName and lastName) as sort fields for report in design time
And present sort field is firstName now if you want to changes sort field to lastName then will generate error. So here we have a trick – Take any column from table which is not present in sort field which you have added in design time.

Design time –

Sort field (0) - firstName
Sort field (1)-lastName

In code set like this-

Sort field (0) - firstName
Sort field (1) - address (any field of table which is not in sort field)

Now again swap between firstName and lastName. This time it will successful because now currently we don’t have lastName as sort field in report. 

Here I am going to explain how we can solve this problem? Here is sample code to solve this problem-

String SortField="yourSortField";

bool fieldPresent = false;

 //CHECKING SORT FIELD PRESENT IN THE REPORT IF YES THEN SWAP THE POSITION //TO ZERO

    for (int i = 0; i <= Report100.DataDefinition.SortFields.Count - 1; i++)
  {
       if (Report100.DataDefinition.SortFields[i].Field.FormulaName == SortField)
        {
            fieldPresent = true;
            FieldDefinition tempDef = New FieldDefinition;
            FieldDefinition currentDef =New FieldDefinition;

            //HOLDING CURRENT [0'TH] SORT FIELD

            currentDef = Report100.DataDefinition.SortFields[0].Field;

            //HOLDING FOUND SORT FIELD

            tempDef = Report100.DataDefinition.SortFields[i].Field;

            //REPLACING FOUND FIELD  DEFINITION WITH OTHER FIELD DEFINITION EXCEPT (Already Present SortField in design time) BECAUSE THESE SORT FIELDS ARE ALREADY IN REPORT SO GENERATE ERROR


            Report100.DataDefinition.SortFields[i].Field = Report100.Database.Tables[0].Fields[5];


            //SWAPPING THE CURRENT SORT FIELD WITH FOUND SORT FIELD

            Report100.DataDefinition.SortFields[0].Field = tempDef;
            Report100.DataDefinition.SortFields[i].Field = currentDef;

            break;

        }
    }

    //IF SORT FIELD IS NOT PRESENT THEN REPLACE THE CURRENT FIELD DEFINITION


    if (fieldPresent == false)

    {
        FieldDefinition FieldDef = New FieldDefinition;
        FieldDef = Report100.Database.Tables[0].Fields[SortField];
        Report100.DataDefinition.SortFields[0].Field = FieldDef;
    }

Report100.DataDefinition.SortFields[0].SortDirection = CrystalDecisions.Shared.SortDirection.AscendingOrder;



In above code, I am setting sort order field, Here this I am swapping sort field orders but we can’t swap sort field directly because if field is present as sort field then it will generate error, for this I have written code to identify that sort field is present or not.


If sort field is not present then I am directly setting given field ("SortField") as sort field. Otherwise to set sort order field I am implementing swapping concept.


For this I have take two objects of  FieldDefinition class.


FieldDefinition tempDef = New FieldDefinition;
FieldDefinition currentDef =New FieldDefinition;


Using this first, I am replacing present sort order field  with different (which is not present in sort order field ) sort order field . Finally I am changing the sort order like this-

 //SWAPPING THE CURRENT SORT FIELD WITH FOUND SORT FIELD


Report100.DataDefinition.SortFields[0].Field = tempDef;

Report100.DataDefinition.SortFields[i].Field = currentDef;


Now done, try this code, I have successfully implemented this code.



Thanks


Friday, July 13, 2012

Dot Net Interview questions for 2+ years experience


Hi All,

If you have 2+ years of experience then you should be ready for more paper work instead of oral in interview because there you have to prove yourself in-front of interviewer.

I have collected some interview questions those have attended by me and my friends.

In this article, I am giving you some Dot Net Interview questions for 2+ experiences.

---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------

1. Tell about your technical profile.
2. What was your role in your project?
3. In which module you have worked explain?
4. Describe GridView events (Paper).
5. How to change Label's color based on Label's value  (Paper)?
6. Write the code to perform edit and delete operations using  GridView (Paper).
7. What are the Validation controls in ASP.Net?
8. How you will implement Custom Validator Control functionality (Paper)?
9. What are Generics?
10. What is the  difference between HashTable and Dictionary?
11. What is Ajax and  Jquery?
12. Which control have you used in AJAX?
13. What is the use of ModalPopUpExtender (Paper)?
14. WCF Basics (Types of binding)
15. What are Database Constraints?
16. Difference between Primary and Unique key?
17. Difference between Function and Procedure?
18. Can we store DataSet in View State?
19. When we will store DataSet in Session then which memory will be filled client side or server side?
20. Difference between reference and out parameter?
21. How to execute stored procedure?

-----------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------

1. What is View State?
2. Where is View State is saved and how View State value is retained between Post Back. (Practical)?
3. Form Authentication Process (Using Web.Config file and Database in paper).
4. If View State value is "X" and I have changed it to "Y" in Page_Load then what will be the final value of View State?
5. Page Life cycle with use.
6. Performance Analyzer tool.
7. How to declare unique key?
8. Diff. between Equi join and Right outer join (Paper)?
9. Define Caching types.
10. How to implement SQL Cache (Paper)?
11. How to call Web service using AJAX (Paper)?
12. How to change Color of Label using Jquery (Paper)?
13. What is Table Object/Variable?
14. How to call stored procedure using Entity Framework?
15. What is the difference between Overloading and Overriding?
16. What is the difference between ExecuteScalar() and ExecuteNonQuery()?
17. What if I will pass Select * in ExecuteScalar()?

---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------

1. Tell me about projects.
2. Your role in project.
3. Which performance tool you have used?
4. Define abstract class and interface?
5. Why to use static members?
6. What is partial class and advantages?
7. GridView and DataList differences.
8. State Management type.
9. What is view state and use?
10. Caching techniques.
11. WCF and Web service differences.
12. Define WCF contracts.
13. Define design pattern.
14. What is facade pattern?
15. Triggers use and types.
16. Define cursor.
17. Difference between clustered and non-clustered index.
18. How many clustered index can be declared for a table.
19. What is view?
20. What is AJAX and Update-panel?
21. If you have 2 Update-panel then how to update one update panel from second?

---------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------

1. Define your Technical skills.
2. Your Role in project.
3. Define features of OOPS.
4. How you will replace the functionality of parent class function in child class.(Paper)
5. Difference between Interface and abstract class (Use).
6. Functions of CLR.
7. Where you will use Cookie, Session and View State.
8. What are InProc and OutProc Session?
9. If you will save session in OutProc then where it will be saved and when it will be expired.
10. Difference between Web service and WCF
11. Design pattern.
12. Write sequence of select query-

 [ WITH ]
SELECT select_list [ INTO new_table ]
 [ FROM table_source ]
 [ WHERE search_condition ]
[ GROUP BY group_by_expression ]
[ HAVING search_condition ]
[ ORDER BY order_expression [ ASC | DESC ] ]

The UNION, EXCEPT and INTERSECT operators can be used between queries
to combine or compare their results into one result set.

13. What is ROW_NUMBER () in SQL Server?
14.  Difference between Union and Join.
15. Return value for ExecuteNonQuery().
16. Can we execute DML command in ExecuteScalar()?
17. Difference between DataSet and DataReader.
18. If provider is given OracleClient then can we connect with SQL Server?
19. Where you have used JQuery in your project?
20. Namespace for web-part (SharePoint)    - System.Web.UI.WebControls.WebParts Namespace
21. For creating a site what are the main concepts you need to consider in UL layer, middle-ware and Database Layer.

--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------

1. Explain different versions of .Net Framework.
2. What is OPPS and explain concept of OPPs?
3. What is static members and where you have used static members in your project?
4. What is difference between Constant  and ReadOnly?
5. Explain different Access Specifier.
6. What is Entity Framework? Explain difference between LINQ and Entity Framework.
7. Explain Page life cycle.
8. Explain Membership provider.
9. What is WCF?
10. Explain different types of WCF Binding and where you will use which binding?
11. Explain Index in SQL Server. Have you created any index for your project?
12. What is difference between Primary key  and Unique key?
13. What is Stored procedure and it's advantages?

--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------

1. What is difference between ArrayList and HastTable?
2. Where we have to use static members?
3. What is constants?
4. What is difference between Interface and Abstract class?
5. How you will handle error in C#?
6. What is the use of Virtual?
7. What is App Domain?
8. What is Session and Cache object?
9. What is Worker Process?
10. Write syntax for stored procedure.
11. How to handle error in Stored Procedure?
12. Explain Binding in WCF.
13. Explain Contract in WCF.
14. How you will host WCF service?
15. How to handle Error in WCF service?
    
--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------

1. Explain your Projects
2. What is Generics?
3. What is Delegate and Events?
4. What is difference between Protected and Protected Internal?
5. What is Entity Framework?
6. Explain Page Life Cycle.
7. Explain Session and Application object.
8. What is Worker Process?
9. What is ISAPI?
10. Use of Global.asax?
11. What us JQuery and How you will use JQuery in your application?
12. What is ISNAN?
13. Have you used Telerik controls in your Project?
14. What is stored procedure?
15. How to call Stored Procedure using .Net code?
16. What is Delete and Truncate?
17. How you will insert Bulk records in database?

--------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------


These are the questions those have attended by me and my friends in different companies; here we can see that most of the questions are same. I hope these questions will help you all to attend the interviews.


Thanks