Thursday, 30 October 2014

Some Content Type for Downloading File

Here are some of the most common content types:

.htm, .html     Response.ContentType = "text/HTML";
.txt    Response.ContentType = "text/plain";
.doc, .rtf, .docx    Response.ContentType = "Application/msword";
.xls, .xlsx    Response.ContentType = "Application/x-msexcel";
.jpg, .jpeg    Response.ContentType = "image/jpeg";
.gif    Response.ContentType =  "image/GIF";
.pdf    Response.ContentType = "application/pdf";

State Management in ASP.NET

State Management in ASP.NET

State management is the process by which you maintain state and page information over multiple requests for the same or different pages.

Types of State Management

There are 2 types State Management:

1. Client Side State Management

This stores information on the client's computer by embedding the information into a Web page, a uniform resource locator(url), or a cookie. The techniques available to store the state information at the client end are listed down below:


View State

Asp.Net uses View State to track the values in the Controls. You can add custom values to the view state. It is used by the Asp.net page framework to automatically save the values of the page and of each control just prior to rendering to the page. When the page is posted, one of the first tasks performed by page processing is to restore view state.


Sample Code

//To Save Information in View State

ViewState.Add("Name", "Sujoy Santra");

//Retrieving View state

Label1.Text = (string)ViewState["Name"];


Control State

If you create a custom control that requires view state to work properly, you should use control state to ensure other developers don̢۪t break your control by disabling view state.



Hidden fields 


Like view state, hidden fields store data in an HTML form without displaying it in the user's browser. The data is available only when the form is processed.



Sample Code



//Declaring a hidden variable

HtmlInputHidden hidName = null;

//Populating hidden variable

hidName.Value = "Sujoy Santra";

//Retrieving value stored in hidden field.

Label1.Text = hidName.Value;

Cookies

Cookies store a value in the user's browser that the browser sends with every page request to the same server. Cookies are the best way to store state data that must be available for multiple Web pages on a web site.

Sample Code

//Storing value in cookie

HttpCookie cookie = new HttpCookie("Name");

cookie.Value = "Sujoy Santra";

Request.Cookies.Add(cookie);

//Retrieving value in cookie

if (Request.Cookies.Count > 0 && Request.Cookies["Name"] != null)

    Label1.Text = "Welcome" + Request.Cookies["Name"].ToString();

else

    Label1.Text = "Welcome Guest";

Query Strings

Query strings store values in the URL that are visible to the user. Use query strings when you want a user to be able to e-mail or instant message state data with a URL.

Sample Code

//Storing value in query(url)

Response.Redirect("Default.aspx?name=Sujoy ");

//Retrieving from query string

Label1.Text = Request.QueryString["name"].ToString();

2. Server Side State Management

ASP.NET offers you a variety of ways to maintain state information on the server, rather than persisting information on the client.



Application State


Application State information is available to all pages, regardless of which user requests a page.



Sample Code



//Stroing information in application state

lock (this)

{

    Application["Name"] = "Sujoy";

}

//Retrieving value from application state

lock (this)

{

    string str = Application["Name"].ToString();

}

Session State

Session State information is available to all pages opened by a user during a single visit.

Both application state and session state information is lost when the application restarts. To persist user data between application restarts, you can store it using profile properties.

Sample Code

//Storing informaton in session state

Session["Name"] = "Sujoy Santra";

//Retrieving information from session state

Label1.Text = Session["Name"].ToString();


Profile Properties

ASP.NET provides a feature called profile properties, which allows you to store user-specific data. This feature is similar to session state, except that the profile data is not lost when a user's session expires. The profile-properties feature uses an ASP.NET profile, which is stored in a persistent format and associated with an individual user. The ASP.NET profile allows you to easily manage user information without requiring you to create and maintain your own database.


Advantages

Advantages of Client Side State Management:


1. Better Scalability:


With server-side state management, each client that connects to the Web server consumes memory on the Web server. If a Web site has hundreds or thousands of simultaneous users, the memory consumed by storing state management information can become a limiting factor. Pushing this burden to the clients removes that potential bottleneck.



2. Supports multiple Web servers:


With client-side state management, you can distribute incoming requests across multiple Web servers with no changes to your application because the client provides all the information the Web server needs to process the request. With server-side state management, if a client switches servers in the middle of the session, the new server does not necessarily have access to the client̢۪s state information. You can use multiple servers with server-side state management, but you need either intelligent load-balancing (to always forward requests from a client to the same server) or centralized state management (where state is stored in a central database that all Web servers access).


Advantages of Server Side State Management:


1. Better security:


Client-side state management information can be captured (either in transit or while it is stored on the client) or maliciously modified. Therefore, you should never use client-side state management to store confidential information, such as a password, authorization level, or authentication status.



2. Reduced bandwidth:


If you store large amounts of state management information, sending that information back and forth to the client can increase bandwidth utilization and page load times, potentially increasing your costs and reducing scalability. The increased bandwidth usage affects mobile clients most of all, because they often have very slow connections. Instead, you should store large amounts of state management data (say, more than 1 KB) on the server.

Wednesday, 29 October 2014

Master page with Menu Control in Asp.net C# with Example

Master page with Menu Control in Asp.net C# with Example

Here I will explain how to create master page with menu in asp.net example or how to use asp.net menu control in master page to create menu and submenus. Here I will use sitemap and sitemapdatasource control to bind asp.net menu in master page.


Right click on website >> select Add New Item >> Select SiteMap >> Click OK
Once SiteMAP added to website open SiteMAP and write the following code

 <?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
<siteMapNode url="" title=""  description="">
<siteMapNode url="Default.aspx" title="Home"  description="Home Page"/>
<siteMapNode url="Forums.aspx" title="Forums"  description="Forums Page"/>
<siteMapNode url="Careers.aspx" title="Careers"  description="Careers Page" >
<siteMapNode url="Jobs.aspx" title="Jobs"  description="Jobs Page" />
<siteMapNode url="upload.aspx" title="Upload"  description="Upload Page" />
</siteMapNode>
<siteMapNode url="ContactUs.aspx" title="Contact US"  description="ContacUs Page" />
</siteMapNode>
</siteMap>

Same way we can add master page Right click on website >> Select Add New item >> Select Master Page >> Click OK
Now open Masterpage and write the following code
 <html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Master Page with Menu control in asp.net with example</title>
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
<style type="text/css">
.parent_menu
{
width: 110px;
background-color: #8AE0F2;
color: #000;
text-align: center;
height: 30px;
margin-right: 5px;
}
.child_menu
{
width: 110px;
background-color: #000;
color: #fff;
text-align: center;
height: 30px;
line-height: 30px;

}
.sub_menu
{
width: 110px;
background-color: #000;
color: #fff;
text-align: center;
height: 30px;
line-height: 30px;
margin-top: 5px;
}
.selected_menu
{
background-color: #FF6600;
}
.hover_menu
{
background-color: #990000;
color:#fff;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" ShowStartingNode="false" />
<asp:Menu ID="Menu1" runat="server" DataSourceID="SiteMapDataSource1" Orientation="Horizontal">
<LevelMenuItemStyles>
<asp:MenuItemStyle CssClass="parent_menu" />
</LevelMenuItemStyles>
<LevelSelectedStyles>
<asp:MenuItemStyle CssClass="child_menu" />
</LevelSelectedStyles>
<DynamicMenuItemStyle CssClass="sub_menu" />
<DynamicHoverStyle CssClass="hover_menu" />
<StaticSelectedStyle CssClass="selected_menu" />
<StaticHoverStyle CssClass="hover_menu" />
</asp:Menu>
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>

Now open Default.aspx page and add master page like as shown below 

 <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" MasterPageFile="~/MasterPage.master" %>
<asp:Content ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
</asp:Content>

Asp.net Display List of Files from Server Folder in Gridview

Asp.net Display List of Files from Server Folder in Gridview using C#

To display files from folder in Gridview we need to write the code like as shown below


 first create new web application and write the following code in aspx page.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Get files from folder & bind to gridview in c#.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnGetFiles" Text="Get Files From Folder" runat="server" onclick="btnGetFiles_Click" />
<asp:GridView ID="gvDetails" CellPadding="5" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Text" HeaderText="FileName" />
</Columns>
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
</asp:GridView>
</div>
</form>
</body>

</html>

 
 Once you add namespaces write the following code in code behind
C# Code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Web.UI.WebControls;

 // insert files in folder
protected void btnGetFiles_Click(object sender, EventArgs e)
{
BindGridview();
}
// Bind Data to Gridview
protected void BindGridview()
{
string[] filesPath = Directory.GetFiles(Server.MapPath("~/SampleFiles/"));
List<ListItem> files = new List<ListItem>();
foreach (string path in filesPath)
{
files.Add(new ListItem(Path.GetFileName(path)));
}
gvDetails.DataSource = files;
gvDetails.DataBind();
}

Get Asp.net Gridview Selected Row Values on Button click in C#

Get Asp.net Gridview Selected Row Values on Button click in C# 

Here I will explain how to add checkboxe in asp.net gridview and get gridview selected rows data on button click in asp.net and get checked rows data on button click and how to work with those checked rows in asp.net using c#.

First create one new web application and open your Default.aspx and write the following code .

 <html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Get Checkbox Selected Rows in Asp.net Gridview</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView AutoGenerateColumns="false" ID="gvDetails" CellPadding="5" runat="server">
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkDetails" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UserId">
<ItemTemplate>
<asp:Label id="lblUserid" runat="server" Text='<%#Eval("UserId") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UserName">
<ItemTemplate>
<asp:Label id="lblUsername" runat="server" Text='<%#Eval("Username") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Education">
<ItemTemplate>
<asp:Label id="lblEducation" runat="server" Text='<%#Eval("Education") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<asp:Button ID="btngetdetails" Text="Get Selected Checkboxes" runat="server"
onclick="btngetdetails_Click" />
<br />
<b>Selected Values are:</b><asp:Label ID="lblselected" runat="server" />
</form>
</body>
</html>

 Now in code behind file write the code like as shown below
 using System;
using System.Data;
using System.Web.UI.WebControls;
public partial class BindGridviewwithCheckboxes : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindGridviewData();
}
}
protected void BindGridviewData()
{
        DataTable dt = new DataTable();
        dt.Columns.Add("UserId", typeof(Int32));
        dt.Columns.Add("UserName", typeof(string));
        dt.Columns.Add("Education", typeof(string));
        dt.Rows.Add(1, "Sumit Kemar Sen", "B.Tech");
        dt.Rows.Add(2, "Soumi Santra", "MA");
        dt.Rows.Add(3, "Sujoy Santra", "MCA");
        dt.Rows.Add(4, "Pradipta Chowdhury", "MCA");
        dt.Rows.Add(6, "Sourav Mukherjee", "B.Tech");
        dt.Rows.Add(7, "Sandipan Maji", "B.Tech");
        dt.Rows.Add(8, "Mithun Patra", "MCA");
        gvDetails.DataSource = dt;
        gvDetails.DataBind();
}
protected void btngetdetails_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
string str = "";
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("UserId"), new DataColumn("Status") });
foreach (GridViewRow row in gvDetails.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox bf = (row.Cells[3].FindControl("chkDetails") as CheckBox);
string id = (row.Cells[0].FindControl("lblUserid") as Label).Text;
if (bf.Checked)
{
str = str+ id + ",";
}
}
}
str = str.Remove(str.Length - 1, 1);
lblselected.Text = str;
}
}

Sorting Columns in Repeater Control by ASP.NET,C#

Sorting Columns in Repeater Control

Here I will explain how to implement sorting in repeater control in asp.net using c#.
To implement sorting in repeater control first create new web application and write the following code in aspx page.

 <html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Repeater Sorting Example in ASP.NET,C#</title>
<style type="text/css">
.hrefclass
{
color:White;
font-weight:bold;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Repeater ID="rptUserData" runat="server" OnItemCommand="rptUserData_ItemCommand">
<HeaderTemplate>
<table style="width:500px; border-collapse: collapse;" border="1" cellpadding="5" cellspacing="0" >
<tr style="background-color: #df5015; height: 30px;"
align="left">
<th>
<asp:LinkButton ID="lnkUserId" runat="server" CommandName="UserId" CssClass="hrefclass">UserId</asp:LinkButton></th>
<th>
<asp:LinkButton ID="lnkUserName" runat="server" CommandName="UserName" CssClass="hrefclass">UserName</asp:LinkButton></thalign>
<th>
<asp:LinkButton ID="lnkEducation" runat="server" CommandName="Education" CssClass="hrefclass">Education</asp:LinkButton></th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr style="height: 25px;">
<td >
<%#Eval("UserId").ToString()%>
</td>
<td >
<%#Eval("UserName").ToString()%>
</td>
<td>
<%#Eval("Education").ToString()%>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</div>
</form>
</body>
</html>

Now open code behind file and write following code

 using System;
using System.Data;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //Set View State Value for Initial Sort Order
            ViewState["Column"] = "UserId";
            ViewState["Sortorder"] = "ASC";
            BindRepeater();
        }
    }
    private void BindRepeater()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("UserId", typeof(Int32));
        dt.Columns.Add("UserName", typeof(string));
        dt.Columns.Add("Education", typeof(string));
        dt.Rows.Add(1, "Sumit Kemar Sen", "B.Tech");
        dt.Rows.Add(2, "Soumi Santra", "MA");
        dt.Rows.Add(3, "Sujoy Santra", "MCA");
        dt.Rows.Add(4, "Pradipta Chowdhury", "MCA");
        dt.Rows.Add(6, "Sourav Mukherjee", "B.Tech");
        dt.Rows.Add(7, "Sandipan Maji", "B.Tech");
        dt.Rows.Add(8, "Mithun Patra", "MCA");
        DataView dvData = new DataView(dt);
        //Sorting Filter
        dvData.Sort = ViewState["Column"] + " " + ViewState["Sortorder"];
        rptUserData.DataSource = dvData;
        rptUserData.DataBind();
    }
    protected void rptUserData_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (e.CommandName == ViewState["Column"].ToString())
        {
            if (ViewState["Sortorder"].ToString() == "ASC")
                ViewState["Sortorder"] = "DESC";
            else
                ViewState["Sortorder"] = "ASC";
        }
        else
        {
            ViewState["Column"] = e.CommandName;
            ViewState["Sortorder"] = "ASC";
        }
        BindRepeater();
    }
}

Monday, 27 October 2014

Grid Decoration By Row Created

 Protected Sub grdData_created(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdData.RowCreated
        e.Row.Cells(0).HorizontalAlign = HorizontalAlign.Left
        e.Row.Cells(1).HorizontalAlign = HorizontalAlign.Left
        e.Row.Cells(2).HorizontalAlign = HorizontalAlign.Left
        e.Row.Cells(3).HorizontalAlign = HorizontalAlign.Left
        e.Row.Cells(4).HorizontalAlign = HorizontalAlign.Left
        e.Row.Cells(1).VerticalAlign = VerticalAlign.Top
        If (e.Row.RowType = DataControlRowType.Header) Then
            ' e.Row.ForeColor = System.Drawing.Color.Black
        Else
            e.Row.Cells(2).ForeColor = Drawing.Color.DarkBlue
            e.Row.Cells(3).ForeColor = Drawing.Color.DarkCyan
            e.Row.Cells(4).ForeColor = Drawing.Color.DarkViolet
            e.Row.Cells(7).ForeColor = Drawing.Color.DarkGreen
        End If
    End Sub

Tuesday, 21 October 2014

CHAR VS VARCHAR:


 CHAR VS VARCHAR:

CHAR
  1. Used to store character string value of fixed length.
  2. The maximum no. of characters the data type can hold is 255 characters.
  3. It's 50% faster than VARCHAR.
  4. Uses static memory allocation.
VARCHAR
  1. Used to store variable length alphanumeric data.
  2. The maximum this data type can hold is up to 4000 characters.
  3. It's slower than CHAR.
  4. Uses dynamic memory allocation

Monday, 20 October 2014

Check for a column exists in SQL Table

Check for a column exists in SQL Table

select * from Information_SCHEMA.columns
where Table_name='Your Table Name' and column_name='Your Column Name'

Tuesday, 14 October 2014

How to return Output parameter from Stored Procedure in ASP.Net using C#

How to return Output parameter from Stored Procedure in ASP.Net using C# :

In this article I will explain how to use and return value from Stored Procedure using Output Parameter in ASP.Net.
 For this article I a Table named Fruits is used which contains FruitId and FruitName columns. The name of the Fruit is fetched using Output Parameter in SQL Server Stored Procedure in ASP.Net

CREATE PROCEDURE [dbo].[GetFruitName]
      @FruitId INT,
      @FruitName VARCHAR(30) OUTPUT
AS
BEGIN
      SET NOCOUNT ON;
     
      SELECT @FruitName = FruitName
      FROM Fruits
      WHERE FruitId = @FruitId
END

ASPX Code:

Enter FruitId:
<asp:TextBox ID="txtFruitId" runat="server" />
<asp:Button ID="btnSubmit" OnClick="Submit" Text="Submit" runat="server" />
<br />
<br />
<asp:Label ID="lblFruitName" runat="server" />
C#:
 
protected void Submit(object sender, EventArgs e)
{
    string constring = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constring))
    {
        using (SqlCommand cmd = new SqlCommand("GetFruitName", con))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@FruitId", int.Parse(txtFruitId.Text.Trim()));
            cmd.Parameters.Add("@FruitName", SqlDbType.VarChar, 30);
            cmd.Parameters["@FruitName"].Direction = ParameterDirection.Output;
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
            lblFruitName.Text = "Fruit Name: " + cmd.Parameters["@FruitName"].Value.ToString();
        }
    }
}

 

Friday, 10 October 2014

Digital Clock Using JavaScript

Digital Clock Using JavaScript:
Java Script:
-------------------
<script>
               function digclock() {
                   var d = new Date()
                   var t = d.toLocaleTimeString()

                   var hr = t.substring(0, 2)
                   var min = t.substring(3, 5)
                   var sec = t.substring(6, 8)

                   var time
                   if (hr >= 12) {
                       time = (hr - 12) + ':' + min + ':' + sec + ' ' + 'PM'
                   }
                   else {
                       time = hr + ':' + min + ':' + sec + ' ' + 'AM'
                   }

                   document.getElementById('<%= divTimer.ClientID%>').innerHTML = time
               }

               setInterval(function () { digclock() }, 1000)

</script>


HTML:
----------
<div id="divTimer" runat="server" style="font-size:small; color:white;" ></div>