Powered by Blogger.

Working with enterprise library for data access in asp.net Part-3

To work with enterprise library you have to download required from this URL. Here we will use Enterprise Library 5.0 version. We need to give reference in Bin folder to the following dlls: Microsoft.Practices.EnterpriseLibrary.Common.dll Microsoft.Practices.EnterpriseLibrary.Configuration.Design.dll

Asp.Net MVC4 sample application

we will make a sample application using Asp.Net MVC4. Open Visual Studio 2010, then go to File -> New Project. This will open the New Project dialog box. From there make sure .Net Framework 4 is selected. Then select the Visual C# -> Web templates list. From the web template lists, Select ASP.NET MVC 4 Web Application and give a name.

Object Oriented Programming (OOP) concepts in .Net

Mainly there are 3 things in OOPs concept. 1- Inheritance 2- Abstraction 3- Polimorphism Inheritance is one of the key feature of oops concept and C# supports inheritance. Inheritance is a process of deriving the new class from already existing class. It allows you to reuse existing code.

Tutorial on MVVM with WPF

MVVM is nothing but Model view and viewModel.This is the best architecture for WPF. VIEW: A View is defined in XAML and should not have any logic in the code-behind. It binds to the view-model by only using data binding. The View contains the visual controls that will be shown to the user.This is the UI.

WCF tutorial and example in C#.Net

We will discuss how to create a WCF service and how we can consume the WCF service. Open Visual Studio 2010, then go to File -> New -> Project. Then from the New Project dialog box, From the Installed Templates Select WCF from the left hand site, And then Choose WCF Service Library and Give a proper name and Click on OK.

Thursday, February 27, 2014

How to disable right click by using jQuery in asp.net?

In this post we will discuss how we can disable right click in .aspx page in Asp.Net. We will use jQuery for this.

Also check out:

- Add Primary Key Constraint to existing table in sql server 2008

- ExecuteNonQuery(), ExecuteReader() and ExecuteScalar() in Ado.Net

- C#.Net basic interview questions and answers

Follow below steps to disable right click:

1st Step:
Give reference to the jQuery library.

Here we will give referece to jQuery library like below:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>

2nd Step:
Write the jQuery function:

Below is the jQuery function that will disable right click on a page:

<script type="text/javascript" language="javascript">
$(function () {
$(this).bind("contextmenu", function () {
return false
});
});
</script>

Remember in .aspx page we have to write the above code inside the <head> </head> tag.

How to open hyperlink in new tab using jQuery or JavaScript?

In this post we will discuss how to open hyperlinks in new tab using jQuery. Also you can check my previous post on:

- How to use If else in sql server 2008?

- Bind dropdownlist using arraylist or hashtable in C#.Net

- Convert first letter to uppercase in C#.Net

Follow below steps to open hyperlink in new tab using jquery:

1st Step:
Add .js file to page as like below:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>

2nd Step:
Write the script like below:

<script type="text/javascript">
       $('.divclassname a').live('mouseover', function () {
           $(this).attr('target', '_blank');
       });
    </script>

Follow below steps to open hyperlink in new tab using JavaScript:

<script type="text/javascript">
        $(function () {
            $("a").attr("target", "_blank");
        });
    </script>

Rememeber we have to write the above code inside <head> </head> tag in our .aspx page

Simple JavaScript textbox validation example in Asp.Net

In this post we will discuss about a simple textbox required field validation in Asp.Net using JavaScript.

Also you can check my previous articles on:

- Sql Server 2008 joins tutorial

- How to download file in C#.Net?

- RequiredFieldValidator example in Asp.Net

Here in this exapmle when ever a user clicks on the submit button without entering anything in the textbox, one alert message will be shown as "Enter Name".

We have written the JavaScript function and calling that function in the OnClientClick property of the button.

Below is the full code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="JavaScriptValidation.aspx.cs"
    Inherits="JavaScriptValidation" %>

<!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>Simple JavaScript validation example</title>
    <script language="javascript" type="text/javascript">
        function validateName() {
            if (document.getElementById("txtName").value == "") {
                document.getElementById("txtName").focus();
                alert('Enter Name');
                return false;
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Enter Name:<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
        <br />
        <asp:Button ID="btnTest" runat="server" Text="Click to Validate" OnClick="btnTest_Click"
            OnClientClick="return validateName();" />
    </div>
    </form>
</body>
</html>

The output will be like as shown in the figure below:

How to validate user input for mobile number using Regular Expression in Javascript?

In this post we will discuss about how to validate user input for mobile number using Regular Expression in Javascript?

Also check out:

- SET XACT_ABORT ON in sql server

- RangeValidator example in Asp.Net

- Interfaces in C#.Net

The below Html code explains the client side validation for mobile number using Regular Expressions.  

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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>Untitled Page</title>
    <script language="ecmascript" type="text/ecmascript">
              function validateMobileNo() {
                var p1 = /^([0-9]{10})$/;
                var mobile_no = form1.Text1.value;
                var x1 = mobile_no.match(p1);
                if (x1 == null) {
                    alert("Invalid User Input");
                    return false;
                }
                return true;
            }    
    </script>

  </head><body>
    <form id="form1" runat="server">
    <div>
        Enter Mobile Number:
        <input id="Text1"    name="txt1"  type="text" /><br />
        <br />
         
        <asp:Button ID="Button2"   OnClientClick ="return validateMobileNo();" Text="MobileNoCheck"  runat="server" />
     
    </div>
  </form>
</body>
</html>

How to validate user input to accept only 10 character using Regulat expressions in Javascript?

In this post we will discuss about how to validate user input to accept only 10 character using Regulat expressions in Javascript?

Also check out:

- Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements

- Common Language Runtime in C#.Net

- How to Count number of times website visited and online users in asp.net using C#.net?

The below  Html code explains the validation for name which accepts only lower case and upper case alphabets using Regular Expressions.

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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>Untitled Page</title>
    <script language="ecmascript" type="text/ecmascript">
        function validateEmpName() {
               
            var name = document.getElementById(" <%=empName.ClientID%>").value;
           // Reg Exp to accept only A-Z and a-z
            var p1 = /^([A-z])+$/;
            var x1 = name.match(p1);
            if (x1 == null) {
                document.getElementById("empName").style.color = "red";  
                alert("Employee name is not in the corrrect format");
                document.getElementById("<%=empName.ClientID%>").focus;
                return false;
            }
            return true;
          }
     </script>
 </head><body>
    <form id="form1" runat="server">
    <div>
         Enter Employee Name:
        <asp:TextBox ID="empName"  runat="server" Width="132px"></asp:TextBox>
         <asp:Button ID="Button1" runat="server" Text="Check Name"
            OnClientClick = "return validateEmpName();"   />
    </div>
    </form>
</body>
</html>

Remove hyperlink outline on IE

In this post we will discuss about how to remove hyperlink outline on IE.

Also check out:

- Rename table name or column name in sql server 2008

- Working with enterprise library for data access in asp.net Part-3

- C#.Net interview questions and answers

There are two ways to remove link border or outline.

1. Using simple CSS
  * : focus { outline: none; }

2. Using Jquery
    $("a").each(function() {
       $(this).attr("hideFocus", "true").css("outline", "none");
     });

Date validation using JavaScript

In this post we will discuss about date validation using JavaScript. Also check out:

- Create a database by command in sql server 2008

- RegularExpressionValidator example in Asp.Net

- Export Data Of DataGridview To Excel using C# Windows Appllication

Here is a date validation through JavaScript that will give an alert message if you try to give a date less than today. It will always take the future date.

Below is the full HTML code:

 <head runat="server">
 <script language="javascript" type="text/javascript">
     function validateDate() {
         var expDate = document.getElementById('txtDate').value;
         var date = expDate.substring(0, 2);
         var month = expDate.substring(3, 5);
         var year = expDate.substring(6, 10);
         var myDate = new Date(year, month - 1, date);
         var today = new Date();

         if (myDate > today) {
         }
         else {
             alert('Please enter a date greater than today !');
             return false;
         }
     }
    </script>
    <title>JavaScript date validation</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtDate" runat="server"></asp:TextBox><br />
        <asp:Button ID="btnValidate" runat="server" Text="Click to Validate" OnClientClick="return validateDate();" />
    </div>
    </form>
</body>

Check the figure below for more information:

Show hide div using jQuery in asp.net

In this article we will discuss about how we can show or hide a div using jQuery in our asp.net application.

You can also check my previous posts on:

- Data files and Log files in sql server 2008

- Delegates in C#.Net

- How to Generate a Strong Name for the Assembly and How to Build the Assembly and Add it to the Global Assembly Cache?

First we have to give reference to the jQuery library like below:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>

Then we need to write the function. Below is the full .aspx code.
.aspx code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ShowHideDiv.aspx.cs" Inherits="ShowHideDiv" %>

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

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>

<title>Show hide div using jQuery</title>

<script type="text/javascript">

$(document).ready(function (){

$(".mydiv").hide();
$(".show_hide").show();
$('.show_hide').click(function () {
$(".mydiv").slideToggle();
});
});

</script>
</head>
<body>
<form id="form1" runat="server">
<div><a href="#" class="show_hide">Show/hide</a>
<div class="mydiv">This div will behave like show or hide !!!</div>
</div>
</form>
</body>
</html>

Split javascript string

In this article we will discuss about how to split a JavaScript string. Also you can check my previous posts on:

- Identity in sql server 2008

- The App_Code Folder in Asp.Net

- Constructor and Destructors in C#.Net

Here is the string:

var strMainString = new String();

strMainString = "AspDotNetHelp.com|SharePointDotNet.com|EnjoySharePoint.com|Fewlines4Biju.com";

Now we can split the string with separator "|" and we will store in an array.

var arr = new Array();

arr = myString.split("|");

Now we can retrieve the items from the array by using a for loop statement like below:

for(var i=0; i < arr.length; i++)
{
alert ( arr[i] );
}

alert() method examples in JavaScript

In this post we will discuss some examples of alert() method in javascript. Also you can also check out my previous posts on:

- Triggers in sql server 2008

- What is difference between machine.config and web.config file in Asp.Net?

- Encrypt and Decrypt a file in C#.Net

Below are some examples:

Example-1:
 <script language="JavaScript" type="text/javascript">
        alert("Javascript dialog example");
    </script>
Example-2:
In this example we can see how we can show message in dialog box in multiple lines.

<script language="JavaScript" type="text/javascript">
        alert("JavaScript Alert\n Multiple Line Example");
    </script>


Example-3:
In this example we will see how we can show message from variables in a dialog box.

 <script language="JavaScript" type="text/javascript">
        var firstmsg = "This is the first message! ";
        var secondmsg = "This is the second message! ";
        alert(firstmsg + secondmsg);
    </script>

Confirm box example in JavaScript

In this post we will discuss about Confirm box example in JavaScript. Also you can check out my previous posts on:

- Error functions in sql server

- How To Call a Button Click From Another Button in C#.Net?

- Post form data to 3rd party URL in Asp.Net

The confirm dialog box is used to confirm a user's answer to a question. A question mark will appear in the box with an OK button and a Cancel button. If the user presses the OK button, true is returned; if he presses the Cancel button, false is returned.

Example:
<script language="JavaScript" type="text/javascript">
        if (confirm("Are you sure you want to do this?") == true) {
            alert("You have clicked OK !!!");
        }
        else {
            alert("You have clicked Cancel !!!");
        }
    </script>

When run this, the window will appear like below:

If you click on OK, the alert will come like below:


And if you click on Cancel, the alert will come like below:

If Else statements in JavaScript Example

In this post we will discuss how to use if else statement in javascript. Also you can check my previous posts  on:

- Transaction in SQL Server 2008

- Display Favicon in Asp.Net web site

- How To Call a Button Click From Another Button in C#.Net?

Syntax of if else statement:

if (condition) {
    statements1;
}
else if (condition)  {
    statements2;
}
else if (condition)  {
    statements3;
}
else{
    statements4;
}

Example:

Below is an example of if else statement:

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

        var age = eval(prompt("How much you scored?", ""));

        if (age >= 60) {
            alert("First Division");
        }
        else if (age > 50 && age < 60) {
            alert("Second Division");
        }
        else if (age >= 30 && age < 50) {
            alert("Third Division");
        }
        else {
            alert("Fail");
        }

    </script>

Here in this example it will first prompt use to enter a value and according to the condition it will alert the message. See fig below:


Once you enter the value it will show alert box according to the condition like below:

JavaScript Functions example

In this post we will discuss about JavaScript functions, how to create as well as how we can call a function. Also you can check my previous posts on:

- Constraints in SQL Server 2008

- Generics tutorial in C#.Net

- Creating a New ASP.NET 4 Web Site

A function is a block of statements that can performs some task as well it can also return some value. A function is independent of your program and not executed until called.

Functions must be declared before they can be used. Normally functions are placed in the <head> tag of the HTML document to ensure that they are defined before used.

In JavaScript, we can define a function by using the function keyword. Also a function can take some parameters.

Syntax:

function function_name ()
{
statement 1;
statement 2;
}

function function_name (parameter1, parameter 2)
{
statement 1;
statement 2;
}

Example:
Here in this example, we write a method inside the <head> </head> tag,  which will give an alert message. And in a hyperlink we are calling that method in the body like below:

<head runat="server">
    <title>JavaScript Function Example</title>
    <script language="JavaScript" type="text/javascript">
        function HelloWord() {
            alert('Hello World !!!')
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <a href="javascript:HelloWord()">Click here </a>
    </div>
    </form>
</body>

see fig below:

simiarly if you want to call the javascript methos in a asp button control, then you can call the method in the OnClientClick event like below:

<asp:Button ID="btnCall" runat="server" Text="Call JavaScript Function" OnClientClick="HelloWord();" />

How to create dropdown menu for login and signup using jQuery in asp.net ?

Here in this article, we will discuss how to create drop down menu for login and signup using jQuery.
You can also check my previous posts on:

- How to find the difference in retrieving data with and without using index in sql server 2008?

- Collections in C#.Net

- Page.IsPostBack Property in Asp.Net

Implementation: 
Let's see an example to see the menu in working.
In the <Head> tag of the design page(.aspx) add the jQuery reference and  function.

 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>

    <script type="text/javascript">
    $(document).ready(function(){
        $('#login-trigger').click(function () {
                                $(this).next('#login-content').slideToggle();
                                $(this).toggleClass('active');                                                                  
                             
                                if ($(this).hasClass('active')) $(this).find('span').html('&#x25B2;')
                                                else $(this).find('span').html('&#x25BC;')
                                })
});
</script>

In the <form> tag of the design page(.aspx) design the page as:

<div>
    <nav>
         <ul>
            <li id="login">
                 <a id="login-trigger" href="#">
                                Log in <span>?</span>
                                  </a>
                                  <div id="login-content">
                             
                                     <fieldset id="inputs">                                                                                
      <asp:TextBox ID="txtUserName" runat="server" placeholder="Your email address" type="email" required></asp:TextBox>                                                                                      
       <asp:TextBox ID="txtPwd" runat="server" TextMode="Password" placeholder="Password" required></asp:TextBox>
                                      </fieldset>
                                      <fieldset id="actions">                                                                              
                        <asp:Button ID="btnLogin" runat="server" Text="Login" CssClass="submit"
                            onclick="btnLogin_Click"></asp:Button>                                                                          
                 <asp:CheckBox ID="chkRemember" runat="server" Checked="true"></asp:CheckBox>Remember me
                                                  </fieldset>
                 <a href="#" style="float:right;">Forgot password?</a>
                                </div>  
                   
                                </li>
                                <li id="signup">
                               <a href="#">Sign up</a>
                                </li>  
              </ul>
                   </nav>
                           </div>

You can also add some style sheets to this application.

jQuery or validation controls? which should be used for validation?

In this post we will discuss about which type of validation we should use in our Asp.Net applications. Whether we should use jQuery or JavaScript validation or we should use our inbuilt Asp.Net validation controls.

Also you can check out some of my articles on:

- Change authentication mode after installation of SQL Server

- Different ways to encrypt or decrypt password in asp.net

- Functions and Subroutines in C#.Net

- It depends on how rich client you want to build and It's entirely a performance optimization. A client validation (jQuery/javascript) failure saves a round trip to your server, helping to scale and allowing to reduce the response time for users. But some cases validation work must take place server-side (For example : Date Validation).

- If you want to make a secure application, validation has to be done on both sides, client and server. Remember client side, especially javascript can always be hacked from the browsers by a user.

- Also it depends on how much control you have over the entire page content. JavaScript can not only be hacked, but easily broken by content that another developer or dynamic content adds to the page. In addition, JQuery is still seen as a technical skill that many web developers do not possess (unfortunately) which will make it more difficult to maintain.

- ASP.Net validation controls help you automate the server-side validation and keep it in sync with the client, while jQuery still requires you to write the server-side logic separately.

- ASP.Net validation controls help you automate the server-side validation and keep it in sync with the client, while jQuery still requires you to write the server-side logic separately.

- Validation should be done on client side and server side for added security, protecting the application from undesired data. Some in this forum think that JQuery is a skill or its hard. To simply put it, JQuery is a framework that has been around a few years, and it wraps DOM object manipulation that is browser safe. JQuery's biggest challenge is the selector, once you master that, you are ready to take on the world.

Show confirmation dialogbox using JavaScript in Asp.Net

In this post we will discuss how we can show confirmation message on button click using JavaScript in Asp.Net.

Also you can check out my previous posts on:

- Query to get records between two dates in sql server 2008

- Properties in C#.Net

- Get user control value in aspx page in asp.net

We can show confirmation message on button click by using JavaScript.

First we will write the JavaScript function like below inside the </head> tag and then we will put the button inside the form tag. So our code will be like below:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function deleteConfirmation() {
            if (confirm("Are you sure you want to delete this record?") == true)
                return true;
            else
                return false;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Button ID="btnDelete" runat="server" Text="Delete" OnClick="btnDelete_Click"/>
        </div>
    </form>
</body>
</html>

Then we can register the JavaScript to the button in the Page_Load like below:

btnDelete.Attributes.Add("onclick", "return deleteConfirmation();");

So the full code will be like below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default10 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        btnDelete.Attributes.Add("onclick", "return deleteConfirmation();");
    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {

    }
}

When user clicks on the button the confirmation message will come like below:

When user click on OK then the server side OnClick (btnDelete_Click) will excute. If user click on Cancel, then the server side OnClick will not execute.

How to get body height using jQuery in Asp.Net?

In this post we will discuss how we can find the body height using jQuery. Also you can check out my previous posts on:

- Single stored procedure to insert update and delete in sql server 2008

- Adding meta tags to aspx pages in asp.net

- Constants in C#.Net

We can get the body height by using the  $(document).height()  or by using the $(window).height() method.

Below is the full code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default13.aspx.cs" Inherits="Default13" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>get body height using jQuery in Asp.Net</title>
   <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            var pageheight = $(document).height() + "px";
            alert(pageheight);

            var windowheight = $(window).height() + "px";
            alert(windowheight);
        });
        </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    </div>
    </form>
</body>
</html>
After this it will appear like below:

Redirect to different page using jQuery in Asp.Net

In this post we will discuss how to redirect to a different page using jQuery. Also you can check out my previous posts on:

- stored procedure to update record in sql server 2008

- Anonymous Types in C#.Net

- GAC in Asp.Net

We can redirect to a different page by using window.location.replace("");

Below is the jQuery code, once you will run the page it will redirect to http://www.aspdotnethelp.com page.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default14.aspx.cs" Inherits="Default14" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Redirect to different page using jQuery</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            window.location.replace("http://www.aspdotnethelp.com");
        });
        </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    </div>
    </form>
</body>
</html>

Search for Text inside Strings in javascript

Here in this article, we will discuss how we can Search for Text inside Strings in javascript.

Also check out:

- Get nth highest lowest salary in SQL Server 2008

- Constructor and Destructors in C#.Net

- Bind dropdownlist from enum in Asp.Net

When working with text strings, sometimes you need to determine if a string contains some specific substring, and if it does, you need to determine where in the string that substring occurs.

The following task searches for a substring in another string stored in a variable and displays the position where that substring is found:

1. Open a new HTML document in your preferred HTML or text editor.

2. Create the body of the document with opening and closing body tags:

<body>

</body>

3. Insert a script block in the body of the document:

<script language="JavaScript">
<!--
// -->
</script>

4. Create a variable named myVariable and assign the value "Hello Raj" to it:

var myVariable = "Hello Raj";

5. Create a second variable named therePlace and assign the results of searching for "Raj" to it:

var rajPlace = myVariable.search("Raj");

6. Display the results of the search so that the final page looks like below.

<body>
<script language="JavaScript">
<!--
var myVariable = "Hello Raj";
var therePlace = myVariable.search("Raj");
document.write(rajPlace);
// -->
</script>
</body>

7. Save the file and close it.

8. Open the file in a browser. You should see the number 6 displayed in the browser.

Replace Text in Strings in javascript

Here in this article we will discuss about how we can replace some text in Strings in javascript.

Also check out:

- Encrypt and Decrypt a file in C#.Net

- How to add Eval for hyperlink in gridview in asp.net?

- Get all tables and stored procedures in sql server 2008

The string object provides the replace method for just such purposes.

The following process creates a variable and assigns text to it, replaces that text with
new text, and then displays the results in a browser:

1. Open a new HTML document in your preferred HTML or text editor.

2. Create the body of the document with opening and closing body tags:

<body>
</body>

3. Insert a script block in the body of the document:
<script language="JavaScript">
<!--
// -->
</script>

4. Create a variable named myVariable and assign the value "Hello there" to it:

var myVariable = "Hello there";

5. Create a second variable named newVariable and assign the results of replacing "there" with "Raj" to it:

var newVariable =
myVariable.replace("there","Raj");

6. Display the results of the search and replace so the final page looks like below.

<body>
<script language="JavaScript">
<!--
var myVariable = "Hello there";
var newVariable =
myVariable.replace("there","Raj");
document.write(newVariable);
// -->
</script>
</body>

7. Save the file and close it.

8. Open the file in a browser. You should see the text "Hello Raj" displayed in the browser.

Wednesday, February 26, 2014

Asp.Net job openings with US based Startup Company in Bangalore

Here is a job openings with US based Startup Company in Bangalore.

Job Description:
Experience: 7-9 yrs

Requires Skill Sets : ASP.Net, C#.Net, WCF, SQL Server

Role: IC Role (Individual Contributor)

Role Description:
1. Atleast 3 years of experience in .Net
2. Atleast 3 years of experience in C#.Net
3. Atleast3 years of experience in ASP.Net
4. Atleast 4 years of experience in Ajax/Jquery
5. Atleast 4 years of experience in Javascript
6. Atleast 4 years of experience in Web Services (Including WCF)
7. Atleast 3 years of experience in SQL, SQL Server or Oracle Database
8. Atleast 3 years of experience in Stored Procedure
9. Atleast 3 years of experience in ADO.Net/Entity Framework
10. Expertise on Report writing, SharePoint Development and K2 Development should be A Plus

If you are interested for this position, send your updated profile to chaitanya.zyoin@gmail.com

Monday, February 24, 2014

Redirect users to different web site in Asp.Net using JavaScript

In this post we will discuss how to redirect users to different web sites in Asp.Net using JavaScript. Also you can check out my previous posts on:

- Get database server name in sql server 2008

- Virtual methods in C#.Net

- Difference between web application and web site in Asp.Net

In some situations you need to redirect users to different web site. In the below example whenever a user open the page, he will redirect to www.aspdotnethelp.com.

Below is the JavaScript code:
<head runat="server">
    <title>Redirect users to different web site in Asp.Net using JavaScript</title>
     <script type="text/javascript">
         location.replace("http://www.aspdotnethelp.com");
    </script>
</head>

Call JavaScript function from code behind file in Asp.Net

In this post we will discuss how to call a JavaScript function from a code behind file in Asp.Net. Also you can check out my previous posts on:

- Increase column size in sql server 2008

- The underlying provider failed on Open error in Asp.Net Entity framework

- Sealed class and Sealed method in C#.Net

In this example, we will call a JavaScript method from a button click.

.Aspx Code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default18.aspx.cs" Inherits="Default18" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Call JavaScript method from code behind file</title>
     <script type="text/javascript">
         function JavaScritFromCodeBehind() {
             alert('Welcome to JavaScript Call from Code Behind file');
         }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="btnClick" runat="server" Text="Click to call JavaScript Function" OnClick="btnClick_Click" />
    </div>
    </form>
</body>
</html>

.cs Code:
protected void btnClick_Click(object sender, EventArgs e)
    {
        Page.ClientScript.RegisterStartupScript(this.GetType(),
            "Welcome", "JavaScritFromCodeBehind();", true);
    }
or if you are using AJAX, then you can try like this:
 ScriptManager.RegisterStartupScript(this, this.GetType(), "CallMyFunction", "JavaScriptFunctioName();", true);

Now when you run the code and click on the button.

Create Array in javascript

Here in this article, we will discuss about Creating Arrays in javascript. Also you can check out some posts on:

- Delete all stored procedures at once in SQL Server database

- Static Keyword in C#.Net

- How to implement FileUpload Control in Update Panel using asp.net?

JavaScript supports a more complicated data type known as an array. An array is a collection of individual values grouped together. An array essentially contains a series of numbered containers into which you can place values. Each container can contain a string, a number, or any other data type.

To create a new array, you create a new instance of the Array object:

var arrayName = new Array(number of elements);

The number of elements is just the initial number of elements in the array; you can add more on the fly as you work with the array, but it is a good idea to initialize the array with the likely number of elements you will use.

1. Open a new HTML document in your preferred HTML or text editor.

2. Create the head of the document with opening and closing head
tags:
<head>

</head>

3. Insert a script block in the head of the document:

<head>
        <script language="JavaScript">
<!--
// -->
        </script>
    </head>

4. Create a variable named myArray and initialize it as a new array with five elements:

<body>
        <script language="JavaScript">
<!--
            var myArray = new Array(5);
// -->
        </script>
    </body>

5. Save the file and close it.

Concatenate Strings in javascript

Here we will discuss about Concatenating Strings in javascript. Also you can check out:

- C#.Net interview questions and answers

- Working with enterprise library for data access in asp.net Part-3

- Get nth highest lowest salary in SQL Server 2008

Concatenation refers to the act of combining two text strings into one longer text string.

1. Open a new HTML document in your preferred HTML or text editor.

2. Create the body of the document with opening and closing body tags:
<body>
</body>

3. Insert a script block in the body of the document:
<script language="JavaScript">
<!--
// -->
</script>

4. Create a variable named myVariable and assign the value "Hello" to it:

var myVariable = "Hello";

5. Create a second variable named anotherVariable and assign the value "there" to it:

var anotherVariable = "AspDotNetHelp";

6. Concatenate the values of myVariable and anotherVariable, along with a space between them, and assign the results to a third
variable named finalResults:

var finalResults = myVariable + " " + anotherVariable;

7. Display the results so that the final page looks like below

<body>
<script language="JavaScript" type="text/javascript">
<!--
    var myVariable = "Hello";
    var anotherVariable = "AspDotNetHelp";
    var finalResults = myVariable + " " + anotherVariable;
    document.write(finalResults);
// -->
</script>
</body>

8. Save the file and close it.

9. Open the file in a browser. You should see the string "Hello AspDotNetHelp" displayed in the browser.

C#.Net interview questions and answers

Here are some C#.Net interview questions. Also check WCF interview questions and answers in C#.Net.

Also check some posts on:

- Working with enterprise library for data access in asp.net Part-1

- Common Language Runtime in C#.Net

- List all Stored Procedure Created and Modified in Last N Days in SQL Server 2008

What is a CLR?
What is the difference betweenmanaged and unmanaged code?
What is GAC?
What is CTS and CLS in C#.Net?
What are boxing and unboxing in C#.Net?
What are generics?
What is Abstraction, encapsulation, inheritance and polymorphism?
What is difference between abstract class and interface?
What is difference between NameSpace and Assembly?
What is the use of strong names?
What is the difference between Convert.toString and .toString () method?
What is the difference between arraylist and list?
Where are the types of arrays in C#?
What are the types of access modifiers in C#?
What is the difference between const and readonly in C#?
What is the difference between out and ref in C#?
What are hashtable in C#.Net?
What are hashtable collections?
What are Constructors and destuctors?
What is a delegate?
How can we create a delegate?
What is a multicast delegate?
What are Events?
What is the difference between delegate and events?
What is shadowing?
What is the difference between Shadowing and Overriding?
What does virtual keyword mean?
What is Enum?
What is Indexer?
Can we have static indexer in C#?
What is .NET Remoting?
What is a Web Service?
What’s the difference between web services and remoting?
What is UDDI?
What is DISCO?
What is WSDL?
What are the steps to create a web service and consume it?
How do we secure a web service?
What’s the difference between WCF and Web services?
What are end point, contract, address, and bindings in WCF?
What is a service contract, operation contract and Data Contract in WCF?
What are the various ways of hosting a WCF service?
How do we host a WCF service in IIS?

WCF interview questions and answers in C#.Net

Here are some C#.Net WCF interview questions and answers. Also check out Ajax interview questions and answers.

Also check some posts on:

- Working with enterprise library for data access in asp.net Part-3

- Logging In Users Programmatically in Asp.Net

- Get all tables and stored procedures in sql server 2008

What is WCF?

What is the advantages of WCF over web service in C#.Net?

What are the main components of WCF?

What are  address, bindings and contract in WCF?

What are end point in WCF?

What is a service contract, operation contract and Data Contract?

What are different bindings supported by WCF?

What is the difference between BasicHttpBinding and WsHttpBinding?

What are the various ways of hosting a WCF service?

How to host WCF in IIS?

How to do self-hosting a wcf service?

How to host a WCF service in windows service in C#.Net?

How can we generate WCF proxy using SVCUtil.exe?

What is the work of SvcUtil.exe?

What are the advantages of hosting WCF Services in IIS as compared to self-hosting?

How can we enable debugging and tracing on WCF services?

How are exceptions thrown in WCF?

What is the difference between WCF fault exceptions and .NET exceptions?

Ajax interview questions and answers

Here are some AJAX interview questions and answers. Also check some posts on:

- Delete all stored procedures at once in SQL Server database

- Constructor and Destructors in C#.Net

- Get control value using JavaScript with master page in Asp.Net

What is Ajax?

How do we use XMLHttpRequest object in JavaScript?

How to use AJAX in Asp.Net?

What is the work of Scriptmanager control in AJAX?

What is the use of update panel in Ajax?

What is the work of  triggers in UpdatePanel control?

How can you do validations in Ajax?

How do we do exception handling in Ajax?

What is Full form of JSON? And What exactly does this JSON do?

What are extener controls and how can we use extender controls in Asp.Net?

Can we put multiple scriptmanager control in a page?

Can we put multiple updatepanel control in a page?

How can we put ScriptManager control in master page?

What is the difference between synchronous postback and asynchronous postback?

What are the new features of ASP.NET AJAX 4.0?

What is the role of a ScriptManagerProxy?

Can we nest the UpdatePanel controls?

Also check out:
- Asp.Net interview questions

- C#.Net basic interview questions and answers

- C#.Net WindowsForm interview questions and answers

- Asp.Net MVC interview questions and answers

Asp.Net interview questions

Also check some posts on:

- Call stored procedure in Asp.Net using C#.Net

- Bind gridview using datareader in asp.net

- How to download file in C#.Net?

1. What is State management?

2. What is WCF?

3. Difference between Arraylist n Hash Table?

4. Why we use Jquery?

5. What is Join and types of join?

6. Types of state management?

7. What is view state?

8. Difference between Data reader n Dataset?

9. Connected and dissconnected Architecture?

10. What is Executenonqury?

11. How we handle error?

12. What is Return type of Executenonquery?

13. jquery syntax?

14. What is .Net framework?

15. Difference between stored procedure and inline quries?

16. What is foreign key?

17. What is dataset?

18. How to manage session?

19. What is Garbage Collector?

20. What are Collection Classes in Dotnet?

21. What is Stackstrace?

22. How we debug our code?

23. What is finally block?

24. In which event controls are fully loaded?

25. What are page life cycle in asp.net?

26. What is abstaction?

27. What is overloading?

28. What is class?

29. What is object?

30. What is interface?

31. What is API?

32. What is difference between string and string builder?

33. What is sql injection?

34. What is difference between procedure and function?

35. What is lilmitation of arraylist?

36. How to access 1D array and multidimensional array?

37. What is difference between union and union all?

38. What is Ajax?

39. What is difference between javascript and jquery?

40. What are jquery selectors?

41. How to call abstract class methods?

42. How to fetch data from datatable store in string variable?

C#.Net basic interview questions and answers

In this post we will discuss some of the C#.Net basic interview questions and answers.

Also check some posts on:

- Working with enterprise library for data access in asp.net Part-1

- Get last modified time of a file in C#.Net

- RegularExpressionValidator example in Asp.Net

1. What is C#.Net (C-Sharp)?
 i. C# is a new language created by Microsoft and submitted to the ECMA for standardization.
ii. According Microsoft "C# is a modern, object-oriented language that enables programmers to quickly build a wide range of applications for the new Microsoft .Net platform, which provides tools and services that fully exploit both computing and communications."

2. What are the characteristics of C#.Net?
C#.Net is designed for both computing and communication is characterized by several key features. It is -
i. Simple
ii. Consitent
iii. Modern
iv. Object-oriented
v. Type-safe
vi. Versionable
vii. Compatible
viii. Interoprable
ix. Flexible

3. What is BOXING and UNBOXING in C#.Net?
BOXING in C#.Net is the conversion of a VALUE type on stack to a OBJECT type on the heap. Vice-versa the conversion from an OBJECT type back to a VALUE type is known as UNBOXING and it requires type casting.

4. In how many ways you can create new copies of an existing string in C#.Net?
There are two ways:
i. Using overloaded = operator like strings2=s1;

ii. Using the static Copy method like - string s2 = string.Copy(s1);

5. In how many ways you can create new copies of an existing string in C#.Net?
There are two ways:
1. Using overloaded = operator like strings2=s1;

2. Using the static Copy method like - string s2 = string.Copy(s1);

6. Which collection class uses the unique key for the collection?
HashTable

7. What is thread?
It is a process which executes independently.

8. Can interface have static member?
No.

9. Can constructers have access specifier ?
Yes

10. How do I launch Internet Explorer in C#.Net?
using the statement - System.Diagnostics.Process.Start("IExplore.exe",http://www.google.com);

11. Is it possible to have a static indexer in C#.Net?
No, they are not allowed in C#.Net.

12. Are constructors inherited in C#.Net?
No, constructors are not inherited.

13. How is method overriding different from method overloading?
When overriding a method, you change the behavior of the method for the derived class.

Overloading a method simply involves having another method with the same name within the class.

14. Does C#.Net do array bounds checking?
Yes. An IndexOutOfRange exception is used to signal an error.

15. What happens in memory when you Box and Unbox a value-type?
Boxing converts a value-type to a reference-type, thus storing the object on the heap.

Unboxing converts a reference-type to a value-type, thus storing the value on the stack.

16. How do you convert a value-type to a reference-type?
By Using Boxing.

Also check out C#.Net WindowsForm interview questions and answers, Asp.Net MVC interview questions and answers, asp.net state management interview questions and answers and Ado.Net interview questions in Asp.Net.

C#.Net WindowsForm interview questions and answers

Here check out some C#.Net WindowsForm interview questions and answers.
Also check some posts on:

- Working with enterprise library for data access in asp.net Part-2

- ValidationGroup example in Asp.Net

- Caching in Asp.Net

1- How to show message box in C#.Net windows application?

2- What is the difference between Debug.Write and Trace.Write in C#.Net?

3- What is difference between Show() and ShowDialog() in windows application?

4- How do we use event handlers in threading in C#.Net?

5- What's the difference between a process and a thread?

6- What are asynchronous call backs in delegates?

7- What are Multi-cast delegates in C#.Net?

8- Difference between events and delegates in C#.Net?

9- What is difference between Dispose and finalize in C#.Net?

10- What is serialization in C#.Net?

11- What are CLS and CTS in C#.Net?

12- What is difference between  Shadowing and Overriding?

13- How can I run an EXE from one application?

14- What does it mean by docking of controls in C#.Net?

15- What base class do all Winforms inherit from?

16- What is the difference between out and ref in C#.Net?

Also check out: Asp.Net MVC interview questions and answers, asp.net state management interview questions and answers and Ado.Net interview questions in Asp.Net.

Asp.Net MVC interview questions and answers

Here are some asp.net mvc interview questions and answers. Check asp.net state management interview questions and answers and Ado.Net interview questions in Asp.Net.

Also check some posts on:

- Working with enterprise library for data access in asp.net Part-3

- Bind dropdownlist using arraylist or hashtable in C#.Net

- List all Stored Procedure Created and Modified in Last N Days in SQL Server 2008

1- What is MVC? Explain about Model View and Controller.

2- What are routing in MVC?

3- How to maintain session in MVC?

4- How to do validations in MVC?

5- What is razor in MVC?

6- How to implement Ajax in MVC?

7- What is the difference between "ActionResult" and "ViewResult"?

8- What is a Filter in MVC? And what are different types of Filters in MVC?

9- What are the advantages of using Asp.Net mvc over asp.net web forms?

10- Which namespace is used for ASP.NET MVC ?

11- Is it possible to share a view across multiple controllers ?

12- What is the use of a controller in an MVC application ?

13- Explain page life cycle of Asp.Net MVC.

14- What is the difference between "ActionResult" and "ViewResult" in MVC?

15- How to implement AJAX in MVC ?

Honeywell testing interview questions

I have 4 years of experience in testing. I have given interview in Honeywell. In the interview process I have faced 3 rounds of interviews.

Technical 1(Telephonic):

1- Introduction
2- Project Details
3- What is a control system with any day to day example?
4- What is client server application & Web based application?
5- What are the techniques for Test Case design?
6- What is Boundary Value Analysis? Example
7- What is Test Plan?
8- What is a Traceability matrix? What for it is created? What all can you derive from the Traceability matrix as Tester?
9- What is wire shark? What is the purpose? How can you filter the data?
10- Test scenarios for an Interface between controller and UI?
11- What is virtualisation?
12- What is bug and defect with example?
13- How do you assign severity and priority?
14- What is Bug life cycle?
15- What do you do when you find a critical bug just before the release to a customer?
16- How do you say the Test Coverage is 100%?
17- What is firmware Testing and what all did you Test?

Technical 2:

18- There are set of 300 Test Cases. The Developer has introduced 4 new functionalities. You have to deliver by EOD.Now you have to run a test to make sure nothing has broken. What test are you going to run and what is your approach to make sure the S/W is robust?
19- Why do you want a review?
20- Traceability matrix analysis? As a Tester what all do you think should be a part of the document?
21-  What is Automation Testing? What are the advantages & disadvantages of Automation Testing? What Test Case do you automate?
22- What are the tools used for Testing?
23- How do you do Trouble shooting?
24- What is log analysis or how do you analyse a log?
25- What do you do when the developer rejects a bug raised by you but you keep finding it? What is your approach?
26- What all things you share in Dev Track(Bug Tracking tool) once you find a bug?
27- Suppose you have a piece of S/w working fine on Windows XP but it fails to run on Win7,or Vista? What is that you are going to do or your approach? What all you think might have gone wrong?
28- What is the Baseline you follow when you performed your product testing?
29- What is compatibility Testing?What all you do when you are asked to run a compatibility Test?

Managerial Round:

30- Introduction?
31- What are the functional and non-functional Test Cases/Test scenarios for www.irctc.co.in?
32-  Suppose you have a piece of S/w working fine on Windows XP but it fails to run on Win7,or Vista? What is that you are going to do or your approach? What all you think might have gone wrong?
33- What are your strength‘s and weakness?
34- Why do you like/dislike your Team Lead?
35- What is Load?
36- What is Load Testing and why do you need to run a Load Test?How different is it from Stress Testing?
37- You are given a piece of S/w which does not have a SRS.You are asked to Test the S/W and derive the Test Cases? What is your approach? Once Test cases are done what is that you are going to do?
38- What is installation testing? What all check lists comes under it?
39- An application is running fine for 2 months and suddenly it crashes? What is that you are going to do? What might be the issue? What all you are going to check?
40- What are the parameters you are going to consider when you are going to run a performance Test?
41- Task manager related questions for Memory usage and CPU utilisation?
42- What is memory leak?
43- How do you say your S/W performance is good? Whom are you going to ask regarding your app performance?
44- Web app architecture?
45- Load balancer concept? Algorithms implemented/you can implement?
46- Why do you think Google search is so fast?
47- Suppose you are coming up with you search engine.What are the things you are going to take care of ta make the search engine faster than Google?
48- What all things you take care of when you are going for virtualisation?
49- What all things can affect the performance of an application?
50- How do you say Testing is process oriented?

asp.net state management interview questions and answers

Here are few asp.net statemanagement interview questions. Also you can check Ado.Net interview questions.

Also check some posts on:

- Working with enterprise library for data access in asp.net Part-2

- How to handle exception in sql server stored procedure?

- Read and write from Text file in Asp.Net

Also check some statemanagement in asp.net articles.

What are different statemanagement techniques available in asp.net?

What are the client side statemanagement techniques ?

What are the server side statemanagement techniques ?

What is difference between client side statemanagement techinque and server side statemanagement techinque?

Where the view state data will be stored?

Is it possible to store view state in server side?

How do you enable or disable a ViewState for a control on the page?

How do you enable or disable a ViewState at the page level?

Difference between Session and Cache?

What is ViewState? What are the advantages and disadvantages of view state?

What are cookies? How many types of cookies are there?

What are advantages and disadvantages of cookies in Asp.Net?

What is the difference between Session Cookies and Persistent Cookies?

 How do you create a Cookie that never expires?

What are the limitation of query string?

What is a Session?

What is the default session timeout period? And how we can change the session timeout?

How do you end a user session?

How to store sessions in SQL server database?

What are in-proc and out-proc sessions in asp.net?

What is difference between sessions and applications?

What are cookieless session in asp.net?

What are the Session State Modes?

Ado.Net interview questions in Asp.Net

Here are some Ado.Net interview questions. Apart from this you can check out some Asp.Net interview questions.

Also check some posts on:

- Triggers in sql server 2008

- Working with enterprise library for data access in asp.net Part-3

- Encrypt and Decrypt a file in C#.Net

1- What is Ado.net?

2- What is the minimum class required to work Ado.Net in Asp.Net?

3- How to write connection string in Ado.Net Asp.Net?

4- What is the architecture of Ado.Net?

5- What is the difference between dataset and data reader in Asp.Net?

6- What is connected architecture and disconnected architecture in Ado.Net?

7- How to create data table at runtime in Ado.Net?

8- What is executescalar(), executereader() and executenonquery() in Asp.Net?

9- What is the work of data adapter in Ado.Net?

10- How to call a sql statement in Ado.Net?

11- How to call a stored procedure in Ado.Net?

12- What is dataview in Ado.Net?

13- What is the difference between DataSet.Clone() and DataSet.Copy() in Ado.Net?

14- What is connection pooling in Ado.Net? And what is the maximun pool size ?

15- How to connect to Oracle database in Ado.Net in Asp.Net?

16- What is a Gridview control in Ado.Net?

17- How to enable sorting and paging in Gridview in Ado.Net?

18- Which method of DataAdapter is used to fill DataSet in Ado.Net?

19- What is the work of command objects in Ado.Net?

20- What is Maximum Pool Size in ADO.NET Connection String?

21- How to add a new row in DataTable in Ado.Net?

22- How to filter a dataset in Ado.Net?

23- How to create a column in the DataTable?

24- Which method is used to commit all changes in the DataSet or DataTable in Ado.Net?

25- What is the difference between Typed and UnTyped DataSets?

Working with enterprise library for data access in asp.net Part-3

In this post we will discuss how to retrieve sql server table data and show in gridview using Microsoft enterprise library.

Also you can check out:

- Generics tutorial in C#.Net

- List all Stored Procedure Created and Modified in Last N Days in SQL Server 2008

- How to add Eval for hyperlink in gridview in asp.net?

In Part-1 posts we discussed about how to insert data using inline sql statement using enterprise library and in Part-2 we discussed about how to insert data using stored procedure using enterprise library.

To work with enterprise library you have to download required from this URL. Here we will use Enterprise Library 5.0 version.

We need to give reference in Bin folder to the following dlls:
Microsoft.Practices.EnterpriseLibrary.Common.dll
Microsoft.Practices.EnterpriseLibrary.Configuration.Design.dll
Microsoft.Practices.EnterpriseLibrary.Configuration.DesignTime.dll
Microsoft.Practices.EnterpriseLibrary.Data.dll
Microsoft.Practices.EnterpriseLibrary.Data.SqlCe.dll
Microsoft.Practices.ServiceLocation.dll
Microsoft.Practices.Unity.dll
Microsoft.Practices.Unity.Interception.dll

Now open the web.config file to define the connection string. If you are using Windows authentication to login to database then write like below:

<connectionStrings>
<add name="connection" providerName="System.Data.SqlClient" connectionString="Data
Source=localhost;database=TestDB;Integrated Security=SSPI"/>
</connectionStrings>

But if you are using SQL Server authentication to login to SQL Server database then you can write like below:

<connectionStrings>
<add name="connection" providerName="System.Data.SqlClient" connectionString="Data
Source=localhost;Initial Catalog=TestDB;User ID=sa;Password=aspdotnethelp;Min Pool Size=10;Max Pool Size=100;Connect Timeout=100"/>
</connectionStrings>

Below is the stored procedure:

CREATE PROCEDURE Select_Employees

AS
BEGIN
Select * from Employees
END
GO

Below is the code:
.aspx code:
  <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
    </div>
    </form>

.aspx.cs code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Practices.EnterpriseLibrary.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;
using System.Data;
using System.Configuration;

public partial class EnterpriseLibraryTest : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindEmployees();
        }
    }
    void BindEmployees()
    {
        Database db = DatabaseFactory.CreateDatabase("connection");
        DbCommand dbCommand = db.GetStoredProcCommand("Select_Employees");

        try
        {
            DataSet ds = db.ExecuteDataSet(dbCommand);
            GridView1.DataSource = ds.Tables[0].DefaultView;
            GridView1.DataBind();
        }
        catch (Exception ex)
        {

        }
    }
}

Working with enterprise library for data access in asp.net Part-2

In this post we will discuss about data access using enterprise library in Asp.net.

Also you can check out:

- How to display serial number automatically in GridView in asp.net?

- Call stored procedure in Asp.Net using C#.Net

- Constructor and Destructors in C#.Net

In the Part-1 we discussed how to insert data to database using Microsoft enterprise library using inline sql statements. Here we will check we can achieve the same thing using SQL Server.

To work with enterprise library you have to download required from this url. Here we will use Enterprise Library 5.0 version.

We need to give reference in Bin folder to the following dlls:
Microsoft.Practices.EnterpriseLibrary.Common.dll
Microsoft.Practices.EnterpriseLibrary.Configuration.Design.dll
Microsoft.Practices.EnterpriseLibrary.Configuration.DesignTime.dll
Microsoft.Practices.EnterpriseLibrary.Data.dll
Microsoft.Practices.EnterpriseLibrary.Data.SqlCe.dll
Microsoft.Practices.ServiceLocation.dll
Microsoft.Practices.Unity.dll
Microsoft.Practices.Unity.Interception.dll

Now open the web.config file to define the connection string. If you are using Windows authentication to login to database then write like below:

<connectionStrings>
<add name="connection" providerName="System.Data.SqlClient" connectionString="Data
Source=localhost;database=TestDB;Integrated Security=SSPI"/>
</connectionStrings>

But if you are using SQL Server authentication to login to SQL Server database then you can write like below:

<connectionStrings>
<add name="connection" providerName="System.Data.SqlClient" connectionString="Data
Source=localhost;Initial Catalog=TestDB;User ID=sa;Password=aspdotnethelp;Min Pool Size=10;Max Pool Size=100;Connect Timeout=100"/>
</connectionStrings>

Below is the stored procedure:

USE [TestDB]
GO

/****** Object:  StoredProcedure [dbo].[Insert_Users]    Script Date: 01/17/2013 22:05:49 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

Create PROCEDURE [dbo].[Insert_Employees]
@Name varchar(50),
@Age  int,
@Location  varchar(200)
AS
BEGIN
BEGIN TRANSACTION

BEGIN
INSERT INTO Employees (
Name,
Age,
JoiningDate,
Location
)
VALUES (
@Name,
@Age,
GETDATE(),
@Location)  
END
IF @@ERROR = 0
BEGIN
COMMIT TRANSACTION
END
ELSE
BEGIN
ROLLBACK TRANSACTION
END
END


GO


Below is the code:
.aspx code:
<form id="form1" runat="server">
    <div>
        Name:  
        <asp:TextBox ID="txtName" runat="server"></asp:TextBox><br />
        Age:    
        <asp:TextBox ID="txtAge" runat="server"></asp:TextBox><br />
        Location:
        <asp:TextBox ID="txtLocation" runat="server"></asp:TextBox><br />
        <asp:Button ID="btnSubmit" runat="server" Text="Submit"
            onclick="btnSubmit_Click" /><br />
        <asp:Label ID="lblResult" runat="server" Text=""></asp:Label>
    </div>
    </form>

.aspx.cs code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Practices.EnterpriseLibrary.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;
using System.Data;
using System.Configuration;

public partial class EnterpriseLibraryTest : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        Database db = DatabaseFactory.CreateDatabase("connection");
        DbCommand dbCommand = db.GetStoredProcCommand("Insert_Employees"); // Here Insert_Employees is the stored procedure name.
        db.AddInParameter(dbCommand, "@Name", DbType.AnsiString, txtName.Text.ToString());
        db.AddInParameter(dbCommand, "@Age", DbType.AnsiString, txtAge.Text.ToString());
        db.AddInParameter(dbCommand, "@Location", DbType.AnsiString, txtLocation.Text.ToString());
        try
        {
           int result = db.ExecuteNonQuery(dbCommand);
           if (result > 0)
           {
               lblResult.Text = "Record saved successfully!";
           }
           else
           {
               lblResult.Text = "OOPS Some error occured!";
           }
        }
        catch (Exception ex)
        {
            lblResult.Text = "OOPS Some error occured!";
        }
    }
}

Look at the using statements that we have used above.

After that the data will be save in the database.