Thursday, September 29, 2011

how to get textbox value in jquery


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="jQuery1.aspx.cs" Inherits="jQuery1" %>
<!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>How to read TextBox value using JQuery</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox runat="server" ID="txtFirst"></asp:TextBox>
        <asp:TextBox runat="server" ID="txtSecond"></asp:TextBox>
        <asp:Button runat="server" ID="btn" Text="+" />
        <asp:TextBox runat="server" ID="txtSum"></asp:TextBox>
    </div>
    </form>
</body>
</html>



<script language="javascript">
            $(document).ready(function() {        

                $('#btn').click(function() {
                    // Read First number & 2nd Number from TextBox
                    var $nFirstNum = parseInt($('#txtFirst').val())
                    var $nSecondNum = parseInt($('#txtSecond').val())
                    var $nResult = $nFirstNum+$nSecondNum               
                    // Set the result into txtSum TextBox
                    $('#txtSum').val($nResult)
                    return false;
                });
            });
    </script>


Tuesday, August 16, 2011

Automatic Backup for SQL Server


Automatic SQL Server Backup



I wanted to talk about how to setup an automatic SQL Server backup solution and also how to back it up online with SecureBackup. I am using Microsoft SQL Server 2008 Express but you should be able to use these instructions for all versions of Microsoft SQL Server 2005 and Microsoft SQL Server 2008.
In my case, the database files are located in the following directory:
C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA
As you may already know, you cannot backup the *.MDF and *.LDF database files directly because they are attached to the SQL Server. You could detach them, back them up, and then re-attach them but then your database will be offline for a period of time.
To solve this problem, we first need to create a SQL file that can be used later to automate our database backup. Here’s how we can do that:

CREATE AN SQL FILE

  1. Login to Microsoft SQL Server Management Studio.
  2. Right click on your database from the “Databases” node.
  3. Select “Tasks” -> “Back up…”
  4. You are now presented with the “Back up Database” window. In this window you can specify your backup settings. At a minimum, you need to create a destination for your backup. Click the “Add” button and specify a full path name for your database backup in the “File name” field. You will need to use this path name later, so let’s take note of it.
  5. You can choose any other backup options that are important to you. Over on the left hand side is “Options”. I would click on that and decide whether you want to use “append to an existing backup set” or “overwrite all existing backup sets”.
  6. Once you are finished with your settings, you need to create an SQL file which will be used later for the automated database backup. To create that SQL file, click on the arrow next to “Script” at the top of the window. There will be an option for “Script action to File”. Go ahead and select that option. You will then be able to save your SQL Server Script File. Take note of where you have saved this file as well.

CREATE A BATCH FILE

Now that we have created the SQL file, we need to create a batch file that can be automatically executed by the Task Scheduler. To create this file, do the following:
  1. Open Notepad and enter the following:
    sqlcmd -S .\SQLEXPRESS -i "C:\Users\Administrator\Documents\Backup.sql"
    Of course, substitute the pathname with the pathname of where you saved your SQL file.
  2. Save this file and take note of where you saved it.
  3. Now, using Windows Explorer, go to the directory of where you created this file and rename it to have a .bat filename extension instead of .txt.

SET BATCH FILE TO RUN IN WINDOWS TASK SCHEDULER

We are now ready to add the batch file to the Task Scheduler. Rather than using the Task Scheduler GUI, I prefer to do it on the command line. You can open a command prompt as Administrator or if you are already running as Administrator, you can use Start -> Run. Either way, enter the following:
schtasks /create /sc Daily /st 03:30:00 /tn "MyTask" /tr "cmd /c C:\Users\Administrator\Desktop\Backup.bat"
Again, substitute the pathname above with that of your batch file.
Also, set the time specified to something that is desirable for you. In the above example, we run this task at 3:30 AM.

SET SECUREBACKUP TO BACKUP YOUR DATABASE

The time specified in the Task Scheduler step above is important because you need have SecureBackup automatically backup the database file after the task is complete. Since the backup took place at 3:30, you can setup SecureBackup to run the backup at say, 4:00 AM. This way you will have the most recent backup.
From within the SecureBackup software, you need to create or edit an existing  Backup Job and include the location of the backup file that you chose in step 4 of “CREATE AN SQL FILE” above. If the file isn’t listed and you can’t select it from within SecureBackup, it’s because Windows Task Scheduler has not run your batch file yet. To run the batch file, simply double click on it from within Windows Explorer. It may take anywhere from 10 seconds to, possibly, a few hours depending on how large your database is. Once complete, you will have your database backup file and can select that file from within SecureBackup. You will also be able to schedule the Backup Job around how long it took for that batch file to complete.
You now have an automated backup solution for your Microsoft SQL database complete with a secure online storage solution. I hope this post was helpful to you.

Friday, July 22, 2011

.NET Language Integrated Query (LINQ)


When we use the term language integrated query to indicate that query is an integrated feature of the developer’s primary programming languages (e.g., C#, Visual Basic). Language integrated query allows query expressions to benefit from the rich metadata, compile-time syntax checking, static typing and IntelliSense that was previously available only to imperative code. Language integrated query also allows a single general purpose declarative query facility to be applied to all in-memory information, not just information from external sources.

    .NET Language Integrated Query defines a set of general purpose standard query operators that allow traversal, filter, and projection operations to be expressed in a direct yet declarative way in any .NET-based programming language. The standard query operators allow queries to be applied to any IEnumerable<T>-based information source.
     LINQ allows third parties to augment the set of standard query operators with new domain-specific operators that are appropriate for the target domain or technology. More importantly, third parties are also free to replace the standard query operators with their own implementations that provide additional services such as remote evaluation, query translation, optimization, etc. By adhering to the conventions of the LINQ pattern, such implementations enjoy the same language integration and tool support as the standard query operators.

      The extensibility of the query architecture is used in the LINQ project itself to provide implementations that work over both XML and SQL data. The query operators over XML (XLinq) use an efficient, easy-to-use in-memory XML facility to provide XPath/XQuery functionality in the host programming language. 

    The query operators over relational data (DLinq) build on the integration of SQL-based schema definitions into the CLR type system. This integration provides strong typing over relational data while retaining the expressive power of the relational model and the performance of query evaluation directly in the underlying store.

 

Wednesday, July 6, 2011

how to find the logged in user in user Authentication in asp.net

       if (User.Identity.IsAuthenticated)
        {
            Label20.Text = User.Identity.Name;           
        }

Wednesday, June 29, 2011

State Management in ASP.Net


State Management in ASP.Net
Web Pages developed in ASP.Net are HTTP based and HTTP protocol is a stateless protocol. It means that web server does not have any idea about the requests from where they coming i.e from same client or new clients. On each request web pages are created and destroyed.


So, how do we make web pages in ASP.Net which will remember about the user, would be able to distinguish b/w old clients(requests) and new clients(requests) and users previous filled information while navigating to other web pages in web site?
Solution of the above problem lies in State Management.
ASP.Net technology offers following state management techniques.
Client side State Management
  • Cookies
  • Hidden Fields
  • View State
  • Query String
Server side State Management
  • Session State
  • Application State
These state management techniques can be understood and by following simple examples and illustrations of the each techniques.
Client Side State Management
Cookies
A cookie is a small amount of data which is either stored at client side in text file or in memory of the client browser session. Cookies are always sent with the request to the web server and information can be retrieved from the cookies at the web server. In ASP.Net, HttpRequest object contains cookies collection which is nothing but list of HttpCookie objects. Cookies are generally used for tracking the user/request in ASP.Net for example, ASP.Net internally uses cookie to store session identifier to know whether request is coming from same client or not. We can also store some information like user identifier (UserName/Nick Name etc) in the cookies and retrieve them when any request is made to the web server as described in following example. It should be noted that cookies are generally used for storing only small amount of data(i.e 1-10 KB).
Code Sample

//Storing value in cookie 
HttpCookie cookie = new HttpCookie("NickName");
cookie.Value = "Balaji";
Request.Cookies.Add(cookie);
//Retrieving value in cookie 
if (Request.Cookies.Count > 0 && Request.Cookies["NickName"] != null)
         lblNickName.Text = "Welcome" + Request.Cookies["NickName"].ToString();
else
         lblNickName.Text = "Welcome Guest";
 Cookies can be permanent in nature or temporary. ASP.Net internally stores temporary cookie at the client side for storing session identifier. By default cookies are temporary and permanent cookie can be placed by setting "Expires" property of the cookie object.
Hidden Fields

A Hidden control is the control which does not render anything on the web page at client browser but can be used to store some information on the web page which can be used on the page.
HTML input control offers hidden type of control by specifying type as "hidden". Hidden control behaves like a normal control except that it is not rendered on the page. Its properties can be specified in a similar manner as you specify properties for other controls. This control will be posted to server in HttpControl collection whenever web form/page is posted to server. Any page specific information can be stored in the hidden field by specifying value property of the control.
ASP.Net provides HtmlInputControl that offers hidden field functionality.
Code Sample
//Declaring a hidden variable 
protected HtmlInputHidden hidNickName;

//Populating hidden variable
hidNickName.Value = "Page No 1";
//Retrieving value stored in hidden field.
string str = hidNickName.Value;
Note:Critical information should not be stored in hidden fields.
View State/Control State
ASP.Net technology provides View State/Control State feature to the web forms. View State is used to remember controls state when page is posted back to server. ASP.Net stores view state on client site in hidden field __ViewState in encrypted form. When page is created on web sever this hidden control is populate with state of the controls and when page is posted back to server this information is retrieved and assigned to controls. You can look at this field by looking at the source of the page (i.e by right clicking on page and selecting view source option.)
You do not need to worry about this as this is automatically handled by ASP.Net. You can enable and disable view state behaviour of page and its control by specifying 'enableViewState' property to true and false. You can also store custom information in the view state as described in following code sample. This information can be used in round trips to the web server.
Code Sample
//To Save Information in View State 
ViewState.Add ("NickName", "Balaji");

//Retrieving View state
String strNickName = ViewState ["NickName"];
Query String
Query string is the limited way to pass information to the web server while navigating from one page to another page. This information is passed in url of the request.  Following is an example of retrieving information from the query strings.
Code Sample
//Retrieving values from query string 
String nickname;

//Retrieving from query string
nickName = Request.Param["NickName"].ToString();

But remember that many browsers impose a limit of 255 characters in query strings. You need to use HTTP-Get method to post a page to server otherwise query string values will not be available.
Server Side State Management
Session State
Session state is used to store and retrieve information about the user as user navigates from one page to another page in ASP.Net web application. Session state is maintained per user basis in ASPNet runtime. It can be of two types in-memory and out of memory. In most of the cases small web applications in-memory session state is used. Out of process session state management technique is used for the high traffic web applications or large applications. It can be configured  with some configuration settings in web.conig file to store state information in ASPNetState.exe (windows service exposed in .Net or on SQL server.
In-memory Session state can be used in following manner
Code Sample
//Storing informaton in session state 
Session["NickName"] = "Ambuj";

//Retrieving information from session state
string str = Session["NickName"];
Session state is being maintained automatically by ASP.Net. A new session is started when a new user sents  first request to the server. At that time session state is created and user can use it to store information and retrieve it while navigating to different web pages in ASP.Net web application.
ASP.Net maintains session information using the session identifier which is being transacted b/w user machine and web server on each and every request either using cookies or querystring (if cookieless session is used in web application).
Application State
Application State is used to store information which is shared among users of the ASP.Net web application. Application state is stored in the memory of the windows process which is processing user requests on the web server. Application state is useful in storing small amount of often-used data. If application state is used for such data instead of frequent trips to database, then it increases the response time/performance of the web application.
In ASP.Net, application state is an instance of HttpApplicationState class and it exposes key-value pairs to store information. Its instance is automatically created when a first request is made to web application by any user and same state object is being shared across all subsequent users.
Application state can be used in similar manner as session state but it should be noted that many user might be accessing application state simultaneously so any call to application state object needs to be thread safe. This can be easily achieved in ASP.Net by using lock keyword on the statements which are accessing application state object. This lock keyword places a mutually exclusive lock on the statements and only allows a single thread to access the application state at a time. Following is an example of using application state in an application.
Code Sample
//Stroing information in application state
lock (this)
{
       Application["NickName"] = "Balaji";
} 

//Retrieving value from application state
lock (this)
{
      string str = Application["NickName"].ToString();
}
So, In the above illustrations, we understood the practical concepts of using different state management techniques in ASP.Net techonology.

Thursday, June 16, 2011

Difference between Stored Procedure and Functions


Stored Procedure:
1) have to use EXEC or EXECUTE
2) return output parameter
3) can create table but won’t return Table Variables
4) you can not join SP
5) can be used to change server configuration
6) can be used with XML FOR Clause
7) can have transaction within SP
Functions:
1) can be used with Select statement
2) Not returning output parameter but returns Table variables
3) You can join UDF
4) Cannot be used to change server configuration
5) Cannot be used with XML FOR clause
6) Cannot have transaction within function


Wednesday, June 15, 2011

How to Import Excel to Gridview:


How to Import Excel to Gridview:

In this article describes how to read data from an Excel Sheet and display them in a GridView.
step by step process to read data from Excel and display them in a GridView.  
First Step:
Create New Web site with new webpage named as Default.aspx (Following is the code contained in the Default.aspx page).

First Step:
Create New Web site with new webpage named as Default.aspx (Following is the code contained in the Default.aspx page).



<%@ 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>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="btImport" runat="server" OnClick="btImport_Click" Text="Import" />&nbsp;
        <asp:Button ID="btExport" runat="server" OnClick="btExport_Click" Text="Export" />&nbsp;
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <br />
        <br />
        <asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#E7E7FF"
            BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Horizontal">
            <FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
            <RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
            <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
            <PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />
            <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
            <AlternatingRowStyle BackColor="#F7F7F7" />
        </asp:GridView>
        <br />
   
    </div>
    </form>
</body>
</html>


Second Step :

 This  C# code of the Default.aspx.cs file:
using System;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Default: System.Web.UI.Page
{
    OleDbConnection oleconn;
    StringBuilder sb = new StringBuilder();
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        {

            string tempFileName = Guid.NewGuid().ToString("N") + "_" + FileUpload1.FileName;

            string saveLocation = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["FileUploadLocation"]);

            string SavePath = Path.Combine(saveLocation, tempFileName);

            try
            {

                FileUpload1.SaveAs(SavePath);

                string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + SavePath + "; Extended Properties=\"Excel 8.0;HDR=YES;\"";
                OleDbConnection oleconn = new OleDbConnection(connectionString);

                string strQuery = "SELECT * FROM [Sheet1$]";

                DataTable dt = new DataTable();
                OleDbCommand ocmd = new OleDbCommand(strQuery, oleconn);
                //  OleDbCommand ocmd = new OleDbCommand(strQuery, oleconn);

                oleconn.Open();

                OleDbDataReader odr = ocmd.ExecuteReader();

                if (odr.HasRows)
                {

                    dt.Load(odr);

                    GridView1.DataSource = dt;

                    GridView1.DataBind();

                }

                oleconn.Close();

                //  DeleteFile(SavePath);

            }

            catch (Exception ex)
            {

                lblerror.Text = "error : " + ex.Message;

            }


        }
    }
}