Thursday, 28 April 2011

Sql DataReader in asp.net


private static void ReadOrderData()
{
    string queryString = "SELECT OrderID, CustomerID FROM dbo.Orders;";
    using (SqlConnection connection = new SqlConnection( connectionString))
    {
        SqlCommand command = new SqlCommand( queryString, connection);
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
        try
        {
            while (reader.Read())
            {
                Console.WriteLine(String.Format("{0}, {1}",
                    reader[0], reader[1]));
            }
        }
        finally
        {
            // Always call Close when done reading.
            reader.Close();
        }
    }
}

SqlDataReader

private static void ReadOrderData()
{
    string queryString = "SELECT OrderID, CustomerID FROM dbo.Orders;";
    using (SqlConnection connection = new SqlConnection( connectionString))
    {
        SqlCommand command = new SqlCommand( queryString, connection);
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
        try
        {
            while (reader.Read())
            {
                Console.WriteLine(String.Format("{0}, {1}",
                    reader[0], reader[1]));
            }
        }
        finally
        {
            // Always call Close when done reading.
            reader.Close();
        }
    }
}

Sql Server Transactions - ADO.NET 2.0 - Commit and Rollback

SqlConnection MySqlConnection = new SqlConnection("Connection String");
MySqlConnection.Open();
SqlTransaction MyTransaction = MySqlConnection.BeginTransaction("MyTrans");

SqlCommand MyCommand = new SqlCommand();
MyCommand.Transaction = MyTransaction;
MyCommand.Connection = MySqlConnection;

try
{
MyCommand.CommandText ="Delete From Employe where Empid = 100";
MyCommand.ExecuteNonQuery();
MyCommand.CommandText ="Delete From Salary where Empid = 100";
MyCommand.ExecuteNonQuery();
MyTransaction.Commit();
}
catch
{
MyTransaction.Rollback();
}
finally
{
MySqlConnection.Close();
}

Transactions in ASP.NET

SqlConnection MySqlConnection = new SqlConnection("Connection String");
MySqlConnection.Open();
SqlTransaction MyTransaction = MySqlConnection.BeginTransaction("MyTrans");

SqlCommand MyCommand = new SqlCommand();
MyCommand.Transaction = MyTransaction;
MyCommand.Connection = MySqlConnection;

try
{
MyCommand.CommandText ="Delete From Employe where Empid = 100";
MyCommand.ExecuteNonQuery();
MyCommand.CommandText ="Delete From Salary where Empid = 100";
MyCommand.ExecuteNonQuery();
MyTransaction.Commit();
}
catch
{
MyTransaction.Rollback();
}
finally
{
MySqlConnection.Close();
}

SQL Transaction in asp.net

           SqlConnection MySqlConnection = new SqlConnection("Connection String");
            MySqlConnection.Open();
            SqlTransaction MyTransaction = MySqlConnection.BeginTransaction("MyTrans");
           
            SqlCommand MyCommand = new SqlCommand();
            MyCommand.Transaction = MyTransaction;
            MyCommand.Connection = MySqlConnection;
           
            try

            {
            MyCommand.CommandText ="Delete From Employe where Empid = 100";
            MyCommand.ExecuteNonQuery();
            MyCommand.CommandText ="Delete From Salary where Empid = 100";
            MyCommand.ExecuteNonQuery();       
            MyTransaction.Commit();
            }
            catch
            {
                MyTransaction.Rollback();
            }

finally
{
 MySqlConnection.Close();
}

Making SQL transaction in DB using ASP.NET 2.0

 SqlConnection MySqlConnection = new SqlConnection("Connection String");
            MySqlConnection.Open();
            SqlTransaction MyTransaction = MySqlConnection.BeginTransaction("MyTrans");
           
            SqlCommand MyCommand = new SqlCommand();
            MyCommand.Transaction = MyTransaction;
            MyCommand.Connection = MySqlConnection;
           
            try
           {
            MyCommand.CommandText ="Delete From Employe where Empid = 100";
            MyCommand.ExecuteNonQuery();
            MyCommand.CommandText ="Delete From Salary where Empid = 100";
            MyCommand.ExecuteNonQuery();       
            MyTransaction.Commit();
            }
            catch
            {
                MyTransaction.Rollback();
            }
    finally
 {
    MySqlConnection.Close();
}

Retrive a Data in arraylist

ArrayList arr = new ArrayList();

 arr = (ArrayList)ViewState["PriceScheme"];

foreach (string Value in arr)
{
               string str = Value.ToString();
}

Arraylist.Add


ArrayList arr = new ArrayList();
while (dtGetAllPriceScheme.Rows.Count > 0)
{
arr.Add(dtGetAllPriceScheme.Rows[i]["priceScheme"].ToString());
i++;
}
Viewstate["Arr"]=arr

Add Item into arraylist

ArrayList arr = new ArrayList();
while (dtGetAllPriceScheme.Rows.Count > 0)
{
arr.Add(dtGetAllPriceScheme.Rows[i]["priceScheme"].ToString());
i++;
}
Viewstate["Arr"]=arr

Tuesday, 26 April 2011

How to select the last inserted record from Table

CREATE PROCEDURE myProc
@param1 INT
AS
BEGIN
SET NOCOUNT ON
INSERT INTO someTable
(
intColumn
)
VALUES
(
@param1
)
SELECT NEWID = SCOPE_IDENTITY()
END

How to select the last inserted record from the identity column

SELECT @@IDENTITY FROM MyTable;

Download Attachment file


string fileName = lblOrderID.Text + ".pdf";
        string path = Server.MapPath("~/Invoice/") + fileName;
        FileInfo file = new FileInfo(path);
        if (file.Exists)
        {
            Response.ContentType = "application/pdf";
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
            Response.TransmitFile(path);
            Response.End();
        }

Download Attachenment in asp.net

string fileName = lblOrderID.Text + ".pdf";
        string path = Server.MapPath("~/Invoice/") + fileName;
        FileInfo file = new FileInfo(path);
        if (file.Exists)
        {
            Response.ContentType = "application/pdf";
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
            Response.TransmitFile(path);
            Response.End();
        }

Window.close


Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CloseThis", "<script>window.close();</script>");

Datetime format in gridview

Text='<%# Bind("expirationDate", "{0:M-dd-yy}") %>'

Specify Datetime Format in gridview

Text='<%# Bind("expirationDate", "{0:M-dd-yy}") %>'

String Split in SQL Query





CREATE FUNCTION dbo.Split(@String varchar(8000), @Delimiter char(1))
returns @temptable TABLE (items varchar(8000))
as
begin
declare @idx int
declare @slice varchar(8000)

select @idx = 1
if len(@String)<1 or @String is null return

while @idx!= 0
begin
set @idx = charindex(@Delimiter,@String)
if @idx!=0
set @slice = left(@String,@idx - 1)
else
set @slice = @String

if(len(@slice)>0)
insert into @temptable(Items) values(@slice)

set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
return
end

------------------------------Result----------------------------------------
select top 10 * from dbo.split('Chennai,Bangalore,Mumbai',',')

Chennai
Bangalore,
Mumbai

Split the string in SQL





CREATE FUNCTION dbo.Split(@String varchar(8000), @Delimiter char(1))
returns @temptable TABLE (items varchar(8000))
as
begin
declare @idx int
declare @slice varchar(8000)

select @idx = 1
if len(@String)<1 or @String is null return

while @idx!= 0
begin
set @idx = charindex(@Delimiter,@String)
if @idx!=0
set @slice = left(@String,@idx - 1)
else
set @slice = @String

if(len(@slice)>0)
insert into @temptable(Items) values(@slice)

set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
return
end

------------------------------Result----------------------------------------
select top 10 * from dbo.split('Chennai,Bangalore,Mumbai',',')

Chennai
Bangalore,
Mumbai

String Separation in SQLQuery



CREATE FUNCTION dbo.Split(@String varchar(8000), @Delimiter char(1))
returns @temptable TABLE (items varchar(8000))
as
begin
declare @idx int
declare @slice varchar(8000)

select @idx = 1
if len(@String)<1 or @String is null return

while @idx!= 0
begin
set @idx = charindex(@Delimiter,@String)
if @idx!=0
set @slice = left(@String,@idx - 1)
else
set @slice = @String

if(len(@slice)>0)
insert into @temptable(Items) values(@slice)

set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
return
end

------------------------------Result----------------------------------------
select top 10 * from dbo.split('Chennai,Bangalore,Mumbai',',')

Chennai
Bangalore,
Mumbai

How to append one DataTable to another DataTable

DataTable dtAttach = new DataTable();

DataTable dtQuantity= new DataTable();

DataTable dtPrice= new DataTable();

dtAttach = dtQuantity.Copy();
dtAttach.Merge(dtPrice, true);

how to join two datatable datas into one datatable to show in one gridview in asp.net

DataTable dtAttach = new DataTable();

DataTable dtQuantity= new DataTable();

DataTable dtPrice= new DataTable();

dtAttach = dtQuantity.Copy();
dtAttach.Merge(dtPrice, true);

IsNullOrEmpty

IsNullOrEmpty is a convenience method that enables you to simultaneously test
whether a String is null or its value is Empty. It is equivalent to the following code:

result = s == null || s == String.Empty;
--------------------------------------------------------
class Sample
{
    public static void Main()
    {
    string s1 = "abcd";
    string s2 = "";
    string s3 = null;

    Console.WriteLine("String s1 {0}.", Test(s1));
    Console.WriteLine("String s2 {0}.", Test(s2));
    Console.WriteLine("String s3 {0}.", Test(s3));
    }

    public static String Test(string s)
    {
    if (String.IsNullOrEmpty(s))
        return "is null or empty";
    else
        return String.Format("(\"{0}\") is not null or empty", s);
    }
}
// The example displays the following output:
//       String s1 ("abcd") is not null or empty.
//       String s2 is null or empty.
//       String s3 is null or empty.


 

String IsnullorEmpty


IsNullOrEmpty is a convenience method that enables you to simultaneously test
whether a String is null or its value is Empty. It is equivalent to the following code:

result = s == null || s == String.Empty;
--------------------------------------------------------
class Sample
{
    public static void Main()
    {
    string s1 = "abcd";
    string s2 = "";
    string s3 = null;

    Console.WriteLine("String s1 {0}.", Test(s1));
    Console.WriteLine("String s2 {0}.", Test(s2));
    Console.WriteLine("String s3 {0}.", Test(s3));
    }

    public static String Test(string s)
    {
    if (String.IsNullOrEmpty(s))
        return "is null or empty";
    else
        return String.Format("(\"{0}\") is not null or empty", s);
    }
}
// The example displays the following output:
//       String s1 ("abcd") is not null or empty.
//       String s2 is null or empty.
//       String s3 is null or empty.


 

Thursday, 21 April 2011

SQl NOT IN

select partno,partid from dbo.parts where partno // wil come 1-1000 records
in
(
select partno from PriceExceptions where priceSchedule =@PriceSchedule // partno 1,2
)

SQl Sub Query

select partno,partid from dbo.parts where partno // wil come 1-1000 records
in
(
select partno from PriceExceptions where priceSchedule =@PriceSchedule // partno 1,2
)

select partno,partid from dbo.parts where partno
not in
(
select partno from PriceExceptions where priceSchedule =@PriceSchedule
)

SQL IN

select partno,partid from dbo.parts where partno // wil come 1-1000 records
in
(
select partno from PriceExceptions where priceSchedule =@PriceSchedule // partno 1,2
)

transfer data from one listbox to another

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

{
if(!IsPostBack)
BindData();
}
protected void MoveRight(object sender, EventArgs e) {
while(uxListBox1.Items.Count > 0 && uxListBox1.SelectedItem != null) {
ListItem selectedItem = uxListBox1.SelectedItem;
selectedItem.Selected = false;
uxListBox2.Items.Add(selectedItem);
uxListBox1.Items.Remove(selectedItem);
}
}
protected void MoveLeft(object sender, EventArgs e) {
while(uxListBox2.Items.Count > 0 && uxListBox2.SelectedItem != null) {
ListItem selectedItem = uxListBox2.SelectedItem;
selectedItem.Selected = false;
uxListBox1.Items.Add(selectedItem);
uxListBox2.Items.Remove(selectedItem);
}
}
private void BindData() {
uxListBox1.Items.Add(new ListItem("test1", "test1"));
uxListBox1.Items.Add(new ListItem("test2", "test2"));
uxListBox1.Items.Add(new ListItem("test3", "test3"));
}
}

Default.aspx
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ListBox ID="uxListBox1" runat="server" SelectionMode="multiple" />
<asp:Button id="uxRightBtn" runat="server" OnClick="MoveRight" Text=" > " />
<asp:Button id="uxLeftBtn" runat="server" OnClick="MoveLeft" Text=" < " />
<asp:ListBox ID="uxListBox2" runat="server" SelectionMode="multiple" />
</div>
</form>
</body>
</html>

Default.aspx.cs

Moving Items from one Listbox to another

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

{
if(!IsPostBack)
BindData();
}
protected void MoveRight(object sender, EventArgs e) {
while(uxListBox1.Items.Count > 0 && uxListBox1.SelectedItem != null) {
ListItem selectedItem = uxListBox1.SelectedItem;
selectedItem.Selected = false;
uxListBox2.Items.Add(selectedItem);
uxListBox1.Items.Remove(selectedItem);
}
}
protected void MoveLeft(object sender, EventArgs e) {
while(uxListBox2.Items.Count > 0 && uxListBox2.SelectedItem != null) {
ListItem selectedItem = uxListBox2.SelectedItem;
selectedItem.Selected = false;
uxListBox1.Items.Add(selectedItem);
uxListBox2.Items.Remove(selectedItem);
}
}
private void BindData() {
uxListBox1.Items.Add(new ListItem("test1", "test1"));
uxListBox1.Items.Add(new ListItem("test2", "test2"));
uxListBox1.Items.Add(new ListItem("test3", "test3"));
}
}

Default.aspx
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ListBox ID="uxListBox1" runat="server" SelectionMode="multiple" />
<asp:Button id="uxRightBtn" runat="server" OnClick="MoveRight" Text=" > " />
<asp:Button id="uxLeftBtn" runat="server" OnClick="MoveLeft" Text=" < " />
<asp:ListBox ID="uxListBox2" runat="server" SelectionMode="multiple" />
</div>
</form>
</body>
</html>

Default.aspx.cs

List Box Add or Remove

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

{
if(!IsPostBack)
BindData();
}
protected void MoveRight(object sender, EventArgs e) {
while(uxListBox1.Items.Count > 0 && uxListBox1.SelectedItem != null) {
ListItem selectedItem = uxListBox1.SelectedItem;
selectedItem.Selected = false;
uxListBox2.Items.Add(selectedItem);
uxListBox1.Items.Remove(selectedItem);
}
}
protected void MoveLeft(object sender, EventArgs e) {
while(uxListBox2.Items.Count > 0 && uxListBox2.SelectedItem != null) {
ListItem selectedItem = uxListBox2.SelectedItem;
selectedItem.Selected = false;
uxListBox1.Items.Add(selectedItem);
uxListBox2.Items.Remove(selectedItem);
}
}
private void BindData() {
uxListBox1.Items.Add(new ListItem("test1", "test1"));
uxListBox1.Items.Add(new ListItem("test2", "test2"));
uxListBox1.Items.Add(new ListItem("test3", "test3"));
}
}

Default.aspx
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ListBox ID="uxListBox1" runat="server" SelectionMode="multiple" />
<asp:Button id="uxRightBtn" runat="server" OnClick="MoveRight" Text=" > " />
<asp:Button id="uxLeftBtn" runat="server" OnClick="MoveLeft" Text=" < " />
<asp:ListBox ID="uxListBox2" runat="server" SelectionMode="multiple" />
</div>
</form>
</body>
</html>

Default.aspx.cs

Transfer data between two ASP.NET ListBox Controls

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

{
if(!IsPostBack)
BindData();
}
protected void MoveRight(object sender, EventArgs e) {
while(uxListBox1.Items.Count > 0 && uxListBox1.SelectedItem != null) {
ListItem selectedItem = uxListBox1.SelectedItem;
selectedItem.Selected = false;
uxListBox2.Items.Add(selectedItem);
uxListBox1.Items.Remove(selectedItem);
}
}
protected void MoveLeft(object sender, EventArgs e) {
while(uxListBox2.Items.Count > 0 && uxListBox2.SelectedItem != null) {
ListItem selectedItem = uxListBox2.SelectedItem;
selectedItem.Selected = false;
uxListBox1.Items.Add(selectedItem);
uxListBox2.Items.Remove(selectedItem);
}
}
private void BindData() {
uxListBox1.Items.Add(new ListItem("test1", "test1"));
uxListBox1.Items.Add(new ListItem("test2", "test2"));
uxListBox1.Items.Add(new ListItem("test3", "test3"));
}
}

Default.aspx
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ListBox ID="uxListBox1" runat="server" SelectionMode="multiple" />
<asp:Button id="uxRightBtn" runat="server" OnClick="MoveRight" Text=" > " />
<asp:Button id="uxLeftBtn" runat="server" OnClick="MoveLeft" Text=" < " />
<asp:ListBox ID="uxListBox2" runat="server" SelectionMode="multiple" />
</div>
</form>
</body>
</html>

Tuesday, 19 April 2011

How to Implement Form Authentication in asp.net 2005

In web config File :
<authentication mode="Forms">
   <forms name="test" loginUrl="~/Login.aspx" path="/" timeout="25" protection="All" ></forms>
  </authentication>

  <!--<authorization>
   <deny users="?" />
  <allow users="*" />
  </authorization>-->
   or
    <authorization>
      <allow roles="Admin"/>
      <deny users="*"/>
    </authorization>




protected void btnSubmit_Click(object sender, EventArgs e)
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, txtUserName.Text.Trim(), DateTime.Now,
DateTime.Now.AddMinutes(25), false, strRole);
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
Response.Cookies.Add(cookie);
//FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, false); if using doesnt work
Response.Redirect("BackOfficeOption.aspx");
}

SQl Insert

SYNTAX :

INSERT INTO "table_name" ("column1", "column2", ...)

VALUES ("value1", "value2", ...)

---------------------------------------------------------------------------------------
INSERT INTO Employee (EmpName, EmpNo)

VALUES ("Sunjaiy","234");

SQL INTERSECT

Table Store_Information
store_nameSalesDate
Los Angeles$1500Jan-05-1999
San Diego$250Jan-07-1999
Los Angeles$300Jan-08-1999
Boston$700Jan-08-1999
 
Table Internet_Sales
DateSales
Jan-07-1999$250
Jan-10-1999$535
Jan-11-1999$320
Jan-12-1999$750
and we want to find out all the dates where there are both store sales and internet sales. To do so, we use the following SQL statement:

SELECT Date FROM Store_Information
INTERSECT
SELECT Date FROM Internet_Sales

Result:

Date
Jan-07-1999

GridView Row Colour Change Event

Row Data Bound Event {if (e.Row.RowType == DataControlRowType.DataRow )// Display the company name in italics
.e.Row.Cells[1].Text = "<i>" + e.Row.Cells[1].Text + "</i>";
//Display In colour
e.Row.Cells[2].BackColor = System.Drawing.Color.Aqua;
}

Define WCF

Windows Communication Foundation (WCF) is a framework for building service-oriented applications. Using WCF, you can send data as asynchronous messages from one service endpoint to another. A service endpoint can be part of a continuously available service hosted by IIS, or it can be a service hosted in an application

SQL Alter Table Modify

Syntax:

ALTER TABLE "table_name"

ALTER COLUMN "column 1" "New Data Type"

Data View Row Filter

 DataTable dtCQDeatils = BL.GetQuoteID(strCustomQuoteID);

        DataView dv= new DataView();
         dv = dtCQDeatils.DefaultView;
        dv.RowFilter = "pages=1";

GridView.Datasource=dv;
GridView.Databind();

Int32.TryParse Method

                             Int32.TryParse Method has 2 overload  list

     TryParse(String, Int32)
       TryParse(String, NumberStyles, IFormatProvider, Int32) 

 private static void TryToParse(string value)
   {
      int number;
      bool result = Int32.TryParse(value, out number);
      if (result)
      {
         Console.WriteLine("Converted '{0}' to {1}.", value, number);        
      }
      else
      {
         if (value == null) value = "";
         Console.WriteLine("Attempted conversion of '{0}' failed.", value);
      }
   }

string numericString;
      NumberStyles styles;

      numericString = "106779";
      styles = NumberStyles.Integer;
      CallTryParse(numericString, styles);

 private static void CallTryParse(string stringToConvert, NumberStyles styles)
   {
      int number;
      CultureInfo provider;

      // If currency symbol is allowed, use en-US culture.
      if ((styles & NumberStyles.AllowCurrencySymbol) > 0)
         provider = new CultureInfo("en-US");
      else
         provider = CultureInfo.InvariantCulture;

      bool result = Int32.TryParse(stringToConvert, styles,
                                   provider, out number);
      if (result)
         Console.WriteLine("Converted '{0}' to {1}.", stringToConvert, number);
      else
         Console.WriteLine("Attempted conversion of '{0}' failed.",
                           Convert.ToString(stringToConvert));
   }


DateTime.TryParseExact

DateTime.TryParseExact Method (String, String, IFormatProvider, DateTimeStyles, DateTime%)

CultureInfo enUS = new CultureInfo("en-US");
string dateString;
DateTime dateValue;

// Parse date with no style flags.
dateString = " 5/01/2009 8:30 AM";
if (DateTime.TryParseExact(dateString, "g", enUS,  DateTimeStyles.None, out dateValue))

   Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue,  dateValue.Kind);
else
   Console.WriteLine("'{0}' is not in an acceptable format.", dateString);



dateString = "5/01/2009 09:00";
if (DateTime.TryParseExact(dateString, "M/dd/yyyy hh:mm", enUS,
                           DateTimeStyles.None, out dateValue))
   Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue,
                     dateValue.Kind);
else
   Console.WriteLine("'{0}' is not in an acceptable format.", dateString);


dateString = "12/01/2010 09:00";
if (DateTime.TryParseExact(dateString, "MM/dd/yyyy hh:mm", enUS,
                        DateTimeStyles.None, out dateValue))
   Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue,
                     dateValue.Kind);
else
   Console.WriteLine("'{0}' is not in an acceptable format.", dateString);

DateTime.TryParse

using System.Globalization;

                    DateTime.TryParse has 2 Overloaded list

1.DateTime.TryParse Method (String, DateTime%)

      private bool ValidateExpirationDate()
    {
        DateTime date;
     
        if (txtExpirationDate.Text != string.Empty)  
        {
         
  if(DateTime.TryParse(txtExpirationDate.Text.Trim(),out date))
           
            {
                lblMsg.Text = "";
                return true;
            }
            else
            {
                lblMsg.Text = "Expiration date is not valid!";
                return false;
            }
        }
        lblMsg.Text = "";
        return true;

    }

2.DateTime.TryParse Method (String, IFormatProvider, DateTimeStyles, DateTime%)

   private bool ValidateExpirationDate()
    {
        DateTime date;
     
        if (txtExpirationDate.Text != string.Empty)  
        {
            if (DateTime.TryParse(txtExpirationDate.Text.Trim(), CultureInfo.CreateSpecificCulture("en-US"),DateTimeStyles.None,out date))
           
            {
                lblMsg.Text = "";
                return true;
            }
            else
            {
                lblMsg.Text = "Expiration date is not valid!";
                return false;
            }
        }
        lblMsg.Text = "";
        return true;

    }

Thursday, 14 April 2011

What is the ideal size of a ViewState?

 The ideal size of a viewstate should be not more than 25-30% of the page size.

Define WCF

Windows Communication Foundation (WCF) is a framework for building service-oriented applications. Using WCF, you can send data as asynchronous messages from one service endpoint to another. A service endpoint can be part of a continuously available service hosted by IIS, or it can be a service hosted in an application

What is WCF ?

Windows Communication Foundation (WCF) is a framework for building service-oriented applications. Using WCF, you can send data as asynchronous messages from one service endpoint to another. A service endpoint can be part of a continuously available service hosted by IIS, or it can be a service hosted in an application

Do Webservice support data reader ?


Do webservices support data reader?

No. However it does support a dataset.

What happens when you change the web.config file at run time?

What happens when you change the web.config file at run time?

ASP.NET invalidates the existing cache and assembles a new cache. Then ASP.NET automatically restarts the application to apply the changes.

How do you apply Themes to an entire application?

How do you apply Themes to an entire application?
By specifying the theme in the web.config file.


Eg: <configuration>
<system.web>
<pages theme=�BlueMoon� />
</system.web>
</configuration>

Can you change a Master Page dynamically at runtime? How?

Yes.
To change a master page, set the MasterPageFile property to point to the .master page during the PreInit page event.

What is Cross Page Posting? How is it done?

Cross Page Posting:
By default, ASP.NET submits a form to the same page. In cross-page posting, the form is submitted to a different page.
This is done by setting the �PostBackUrl� property of the button(that causes postback) to the desired page.
In the code-behind of the page to which the form has been posted, use the �FindControl� method of the �PreviousPage�
property to reference the data of the control in the first page.

Monday, 11 April 2011

How clear the session in asp.net

Remove the all keys and values from session state collection

Session.Clear();

how to kill an asp.net session for logout page??

Session.Abandon() method destroys all the objects stores in the
Session object and releases its resources.Cancel the Current Http Session

 Session.Abandon();

Monday, 4 April 2011

SQL IS NOT NULL

SQL IS NOT NULL

Look at the following "Persons" table:

P_Id
LastName
FirstName
Address
City
1HansenOla Sandnes
2SvendsonToveBorgvn 23Sandnes
3PettersenKari Stavanger



How do we select only the records with no NULL values in the "Address" column?
We will have to use the IS NOT NULL operator:

SELECT LastName,FirstName,Address FROM Persons
WHERE Address IS NOT NULL


The result-set will look like this:

LastName
FirstName
Address
SvendsonToveBorgvn 23

SQL NULL Values

SQL NULL Values

NULL values represent missing unknown data.
By default, a table column can hold NULL values.
This chapter will explain the IS NULL and IS NOT NULL operators.

SQL NULL ValuesIf a column in a table is optional, we can insert a new record or update an existing record without adding a value to this column. This means that the field will be saved with a NULL value.

NULL values are treated differently from other values.
NULL is used as a placeholder for unknown or inapplicable values.


SQL Working with NULL Values
Look at the following "Persons" table:

P_Id
LastName
FirstName
Address
City
1HansenOla Sandnes
2SvendsonToveBorgvn 23Sandnes
3PettersenKari Stavanger


Suppose that the "Address" column in the "Persons" table is optional. This means that if we insert a record with no value for the "Address" column, the "Address" column will be saved with a NULL value.

How can we test for NULL values?

It is not possible to test for NULL values with comparison operators, such as =, <, or <>.

We will have to use the IS NULL and IS NOT NULL operators instead.

SQL IS NULLHow do we select only the records with NULL values in the "Address" column?
We will have to use the IS NULL operator:

 
SELECT LastName,FirstName,Address  FROM Persons  
 
 WHERE Address IS NULL


The result-set will look like this:

LastName
FirstName
Address
HansenOla
PettersenKari
Note: It is not possible to compare NULL and 0; they are not equivalent.