Tuesday, 3 May 2011

Asp.net Remote objects

Asp.net Remote objects:

Any object outside the application domain of the caller application should be considered remote
Remote objects are accessed through Channels ,two existing channels TcpChannel and HttpChannel

Types of .Net remotable objects
  • Single Call=Single Call objects service one and only one request coming in.
  • Single Call objects are usually not required to store state information.
  • Singleton Objects =Singleton objects are those objects that service multiple clients, and hence share data by storing state information between client invocations
  • Client Activated Objects are server-side objects that are activated upon request from
    client . When the client submits a request for a server object using a "new" operator, an activation request message is sent to the remote application. The server then creates an instance of the requested class, and returns an ObjRef back to the client application that invoked it

What is CIL in asp.net ?

Let�s examine CIL code, type metadata, and the assembly manifest in a bit more detail. CIL is a language
that sits above any particular platform-specific instruction set. For example, the following C#
code models a trivial calculator. Don�t concern yourself with the exact syntax for now, but do notice


the format of the Add() method in the Calc class:


// Calc.cs
using System;
namespace CalculatorExample
{
// This class contains the app's entry point.
class Program
{
static void Main()
{
Calc c = new Calc();
int ans = c.Add(10, 84);
Console.WriteLine("10 + 84 is {0}.", ans);
// Wait for user to press the Enter key before shutting down.
Console.ReadLine();
}
}
// The C# calculator.
class Calc
{
public int Add(int x, int y)
{ return x + y; }
}
}
Once you compile this code file using the C# compiler (csc.exe), you end up with a single-file
*.exe assembly that contains a manifest, CIL instructions, and metadata describing each aspect of
the Calc and Program classes.
nNote Chapter 2 examines the details of compiling code using the C# compiler, as well as the use of graphical
IDEs such as Visual Studio, Visual C# Express, and SharpDevelop.
For example, if you were to open this assembly using ildasm.exe (examined a little later in this
chapter), you would find that the Add() method is represented using CIL such as the following:
.method public hidebysig instance int32 Add(int32 x,
int32 y) cil managed
{
// Code size 9 (0x9)
.maxstack 2
.locals init (int32 V_0)
IL_0000: nop
IL_0001: ldarg.1
IL_0002: ldarg.2
IL_0003: add
IL_0004: stloc.0
CHAPTER 1 n THE PHILOSOPHY OF .NET 13
IL_0005: br.s IL_0007
IL_0007: ldloc.0
IL_0008: ret
} // end of method Calc::Add
Don�t worry if you are unable to make heads or tails of the resulting CIL for this method�
Chapter 19 will describe the basics of the CIL programming language. The point to concentrate on
is that the C# compiler emits CIL, not platform-specific instructions.
Now, recall that this is true of all .NET-aware compilers. To illustrate, assume you created this
same application using Visual Basic .NET, rather than C#:
' Calc.vb
Imports System
Namespace CalculatorExample
' A VB "Module" is a class that contains only
' static members.
Module Program
Sub Main()
Dim c As New Calc
Dim ans As Integer = c.Add(10, 84)
Console.WriteLine("10 + 84 is {0}.", ans)
Console.ReadLine()
End Sub
End Module
Class Calc
Public Function Add(ByVal x As Integer, ByVal y As Integer) As Integer
Return x + y
End Function
End Class
End Namespace
If you examine the CIL for the Add() method, you find similar instructions (slightly tweaked by
the VB .NET compiler, vbc.exe):
.method public instance int32 Add(int32 x,
int32 y) cil managed
{
// Code size 8 (0x8)
.maxstack 2
.locals init (int32 V_0)
IL_0000: ldarg.1
IL_0001: ldarg.2
IL_0002: add.ovf
IL_0003: stloc.0
IL_0004: br.s IL_0006
IL_0006: ldloc.0
IL_0007: ret
} // end of method Calc::Add

Asp.net class library

The .NET Framework class library is a collection of reusable types that tightly integrate with the common language runtime. The class library is object oriented, providing types from which your own managed code can derive functionality. This not only makes the .NET Framework types easy to use, but also reduces the time associated with learning new features of the .NET Framework. In addition, third-party components can integrate seamlessly with classes in the .NET Framework.

class library in asp.net


The .NET Framework class library is a collection of reusable types that tightly integrate with the common language runtime. The class library is object oriented, providing types from which your own managed code can derive functionality. This not only makes the .NET Framework types easy to use, but also reduces the time associated with learning new features of the .NET Framework. In addition, third-party components can integrate seamlessly with classes in the .NET Framework.

Common Language Runtime in asp.net

Common Language Runtime (CLR) is a run-time environment that manages the execution of .NET code and provides services like memory management, debugging, security, etc. The CLR is also known as Virtual Execution System (VES). The CLR is a multi-language execution environment. There are currently over 15 compilers being built by Microsoft and other companies that produce code that will execute in the CLR.
The Common Language Runtime (CLR) provides a solid foundation for developers to build various types of applications. Whether you're writing an ASP.Net application , a Windows Forms application, a Web Service, a mobile code application, a distributed application, or an application that combines several of these application models,

CLR provides the following benefits for application developers:

� Vastly simplified development
� Seamless integration of code written in various languages
� Evidence-based security with code identity
� Assembly-based deployment that eliminates DLL Hell
� Side-by-side versioning of reusable components
� Code reuse through implementation inheritance
� Automatic object lifetime management
� Self describing objects

Common Language Specification.

Common Language Specification.

This is a subset of the CTS which all .NET languages are expected to support. The idea is that any program which uses CLS-compliant types can interoperate with any .NET program written in any language.In theory this allows very tight interop between different .NET languages -

 for example allowing a C# class to inherit from a VB class.

Common Type System in asp.net

Common Type System.

  • Asp.net support a multi language . so asp.net provide a Common Type System for all language  (CTS)

  • This is the range of types that the .NET runtime understands, and therefore that .NET applications can use.

  • The CTS is a superset of the CLS.

  •  Note :that not all .NET languages will support all the types in the CTS.

Namespace in asp.net

  • Namespace  is a collection of classes  and  interfaces Namespace is a logical naming scheme for group related types.

  •  A namespace can span multiple assemblies, and an assembly can define multiple namespaces. When the compiler needs the definition for a class type, it tracks through each of the different imported namespaces to the type name and searches each referenced assembly until it is found.

  • Namespaces can be nested. This is very similar to packages in Java as far as scoping is concerned.

Garbage Collection in asp.net

Short  :
  1. Garbage collection is a CLR feature which automatically release the  memory from the application .
  2. Programmers forget to release the objects while coding. CLR automatically releases objects when they are no longer referenced and in use. CLR runs on non-deterministic to see the unused objects and cleans them.
  3. The garbage collector (GC) completely absolves the developer from tracking memory usage and knowing when to free memory.
 ------------------------------------------------------------------------------------
Breifly :
Every program uses resources of one sort or another -- memory buffers, network connections, database resources and so on. In fact, in an object-oriented environment, every type identifies some resource available for a program's use. To use any of these resources, memory must be allocated to represent the type.

The steps required to access a resource are as follows:
1. Allocate memory for the type that represents the resource.
2. Initialize the memory to set the initial state of the resource and to make the resource usable.
3. Use the resource by accessing the instance members of the type (repeat as necessary).
4. Tear down the state of the resource to clean up.
5. Free the memory.

What is MSIL?

Intermediate Language. Also known as MSIL (Microsoft Intermediate Language) or CIL (Common Intermediate Language). All .NET source code (of any language) is compiled to MSIL.

When compiling the source code to managed code, the compiler translates the source into Microsoft intermediate language (MSIL). This is a CPU-independent set of instructions that can efficiently be converted to native code. Microsoft intermediate language (MSIL) is a translation used as the output of a number of compilers. It is the input to a just-in-time (JIT) compiler. The Common Language Runtime includes a JIT compiler for the conversion of MSIL to native code.

Before Microsoft Intermediate Language (MSIL) can be executed it, must be converted by the .NET Framework just-in-time (JIT) compiler to native code. This is CPU-specific code that runs on the same computer architecture as the JIT compiler. Rather than using time and memory to convert all of the MSIL in a portable executable (PE) file to native code. It converts the MSIL as needed whilst executing, then caches the resulting native code so its accessible for any subsequent calls.

What�s the difference between private and shared assembly?


Private assembly is used inside an application only and does not have to be identified by a strong name.


Shared assembly can be used by multiple applications and has to have a strong name.

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.
 

Thursday, 31 March 2011

SQL replication

SQL replication is a process for sharing/distributing data between different databases and synchronizing between those databases. You can use SQL replication to distribute data to a variety of network points like other database servers, mobile users, etc. You can perform the replication over many different kinds of networks and this won�t affect the end result.
In every SQL replication there are 2 main players called Publisher and Subscriber. The Publisher is the replication end point that supplies the data and the replication Subscriber is the replication end point that uses the data from the Publisher. Depending on the replication architecture a replication can have one or more Publishers and of course any replication will have one or more Subscribers.
MS SQL Server offers several main replication types. The Transactional replication is usually used when there�s need to integrate data from several different locations, offloading batch processing, and in data warehousing scenarios.
Another replication type is the Snapshot replication. The Snapshot replication is commonly performed when a full database refresh is appropriate or as a starting point for transactional or merge replications.
The third important SQL replication type is the Merge replication. The Merge replication is used whenever there is a possibility for a data conflicts across distributed server applications.

SQL NOT IN

SELECT * FROM Employees
WHERE [Last Name] NOT IN (N'Anderson', N'Shepherd');

SQL String Functions

String Functions

Some of the String Functions comes very handy at times. Let us discuss them one by one.

ASCII()

Returns the ASCII code value of the leftmost character of a character expression.

Syntax
ASCII ( character_expression ) 


SELECT ASCII('A'

SET TEXTSIZE 0
SET NOCOUNT ON
-- Create the variables for the current character string position
-- and for the character string.
DECLARE @position int, @string char(15)
-- Initialize the variables.
SET @position = 1
SET @string = 'The Csharp'
WHILE @position <= DATALENGTH(@string)
   BEGIN
   SELECT ASCII(SUBSTRING(@string, @position, 1)),
      CHAR(ASCII(SUBSTRING(@string, @position, 1)))
    SET @position = @position + 1
   END
SET NOCOUNT OFF



Output:
-----------
65
----------- ----
84 T
----------- ----
104 h
----------- ----
101 e
----------- ----
and so on.....