Monday, January 24, 2011

Insert value from one Database Table to another Database Table


In this post i have explained how to insert value from one database to another database table.

i have created two tables one in master database another one in sample database
in master table EmpId is identity column,

Here i am getting identity(EmpId) value from Employee table of master database.
Here is the query.

use master
declare @EmpID int
insert into Employee(EmpName,DeptId) values('AAA',1)
set @EmpID=@@Identity
use sample
insert into EmpDetails(EmpId,Location,Email) Values(@EmpID,'Hyderabad','aaa@gmail.com')

Access Remote sql server’s database table

For accessing Remote SqlServer we need to add remote sqlserver to sys.servers

Syntax for accessing Remote SqlServer: 

select * from Servername.Databasename.dbo.Tablename

it will give following error

“Msg 7202, Level 11, State 2, Line 1
Could not find server 'ServerName' in sysservers. Execute sp_addlinkedserver to add the server to sysservers.
”

The syntax to add a remote sql server to sys.servers is:

execute sp_addlinkedserver sqlserverName
If you add your remote server to sys.servers then you can access remote server using following simple query.

select * from servername.databasename.dbo.tablename


If you try to access remote SqlServer without adding remote server to sys.servers

Sunday, January 23, 2011

State Management Techniques in asp.net


Generally web application depends on stateless Http protocol for user requests.
But http protocol can’t retain the information about user requests. In typical client and server communication using HTTP protocol, page is created each time the page is requested.

We have state management techniques to maintain state for the Http protocol; we have two types of state managements like client side and server side.

Client Side State management

ASP.NET provides various client side state management options like Cookies, Query Strings (URL), Hidden fields, View State and Control state.

Cookie:

A cookie is a small piece of text stored on user's computer. Usually, information is stored as name-value pairs. Cookies are used by websites to keep track of visitors. Every time a user visits a website, cookies are retrieved from user machine and help identify the user. 

Hidden Fields 

Hidden fields are used to store data at the page level. As its name says, these fields are not rendered by the browser. It's just like a standard control for which you can set its properties. Whenever a page is submitted to server, hidden fields values are also posted to server along with other controls on the page

View State:
View State can be used to store state information for a single user. View State is a built in feature in web controls to persist data between page post backs. You can set View State on/off for each control using EnableViewState property. By default, EnableViewState property will be set to true. View state mechanism poses performance overhead. View state information of all the controls on the page will be submitted to server on each post back. To reduce performance penalty, disable View State for all the controls for which you don't need state. (Data grid usually doesn't need to maintain state). You can also disable View State for the entire page by adding EnableViewState=false to @page directive. 


Query strings:
 
Query strings are usually used to send information from one page to another page. They are passed along with URL in clear text

Control State:


Control state can be used to store critical, private information across post backs. Control state is another type of state container reserved for controls to maintain their core behavioral functionality whereas View State only contains state to maintain control's contents (UI).

Server Side State management:
 
State information will be maintained on the server. Application, Session, Cache and Database are different mechanisms for storing state on the server. 



Application object:



Application object is used to store data which is visible across entire application and shared across multiple user sessions. Data which needs to be persisted for entire life of application should be stored in application object.
In classic ASP, application object is used to store connection strings. It's a great place to store data which changes infrequently. We should write to application variable only in application_Onstart event (global.asax) or application.lock event to avoid data conflicts. Below code sample gives idea 

Session object:
 
Session object is used to store state specific information per client basis. It is specific to particular user. Session data persists for the duration of user session you can store session's data on web server in different ways. Session state can be configured using the <session State> section in the application's web.config file.  

Configuration information:
<sessionState mode = <"inproc" | "sqlserver" | "stateserver">
 cookieless = <"true" | "false">
 timeout = <positive integer indicating the session timeout in minutes>
 sqlconnectionstring = <SQL connection string that is only used in the SQLServer mode>
 server = <The server name that is only required when the mode is State Server>
 port = <The
port number that is only required when the mode is State Server>
      
You can disable session for a page using EnableSessionState attribute. You can set off session for entire application by setting mode=off in web.config file to reduce overhead for the entire application.
Session state in ASP.NET can be configured in different ways based on various parameters including scalability, maintainability and availability
  • In process mode (in-memory)- State information is stored in memory of web server
  • Out-of-process mode- session state is held in a process called aspnet_state.exe that runs as a windows service.
  • Database mode session state is maintained on a SQL Server database.

Finally selecting between client side and server side state management is based on application Requirement and resources. Both have their own advantages and disadvantages.

For more information 

http://msdn.microsoft.com/en-us/library/75x4ha6s.aspx

Beginning ASP.NET 4: in C# and VB (Wrox Programmer to Programmer) 




Saturday, January 22, 2011

Finding CheckBoxes in gridview


Follow these steps to find the checkboxes in gridview 

StringBuilder str = new StringBuilder();
        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
            bool ischecked = ((CheckBox)GridView1.Rows[i].FindControl("Chk1")).Checked;
            if (ischecked)
            {
                str.Append(GridView1.Rows[i].Cells[1].Text);
            }
        }
        Response.Write(str.ToString());

Interfaces and Abstract classes in C-Sharp


What is an Interface?

An interface is a reference type containing only abstract members. These can be events, indexers, methods or properties, but only the member declarations. A class implementing an interface must provide the implementation of the interface members. An interface cannot contain constants, constructors, data fields, destructors, static members or other interfaces. Interface member declarations are implicitly public.

The attributes is optional and is used to hold additional declarative information.
The modifier is optional. The allowed modifiers are public and internal, unless nested inside a class, then the allowed modifiers are public, protected, private and internal. If no modifier is supplied then a default of internal is used.
The keyword interface must be followed by an identifier that names the interface.
The base-type of an interface can be zero or more interfaces. When more than one base-type is used, then this is a comma-separated list of base-types.

What is an Abstract Class?

Like an interface, you cannot implement an instance of an abstract class, however you can implement methods, fields, and properties in the abstract class that can be used by the child class.

The override keyword tells the compiler that this method was defined in the base class.

There are some similarities and differences between an interface and an abstract class that I have arranged in a table for easier comparison:
FeatureInterfaceAbstract class
Multiple inheritanceA class may inherit several interfaces.A class may inherit only one abstract class.
Default implementationAn interface cannot provide any code, just the signature.An abstract class can provide complete, default code and/or just the details that have to be overridden.
Access Modfiers
An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public
An abstract class can contain access modifiers for the subs, functions, properties
Core VS PeripheralInterfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface.An abstract class defines the core identity of a class and there it is used for objects of the same type.
HomogeneityIf various implementations only share method signatures then it is better to use Interfaces.If various implementations are of the same kind and use common behaviour or status then abstract class is better to use.
SpeedRequires more time to find the actual method in the corresponding classes.Fast
Adding functionality (Versioning)If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
Fields and Constants
No fields can be defined in interfaces
An abstract class can have fields and constrants defined


Some important syntaxes:

1. You can inherent one abstract class and one interface to the same class, but first you have to inherit abstract class and next inherit Interface.

   public interface Iclass
    {
    }
    public abstract class Abstract
    {
    }
    public class Class3 : Abstract, Iclass //Correct
    {  
    }
2. You can’t inherit multiple base classes to the one class

   public  class Class1
    {
    }
    public class Class2
    {
    }
    public class Class3 : Class1,Class2 //Error
    {
    }
3. You can inherit intermediate base class

    public  class Class1
    {
    }
    public class Class2 : Class1
    {
    }
    public class Class3 : Class2
    {
    }

Summery:
  • An Interface cannot implement methods.
  • An abstract class can implement methods.
  • An Interface can only inherit from another Interface.
  • An abstract class can inherit from a class and one or more interfaces.
Example:
    public interface Iclass
    {
    }
    public interface Iclass1:Iclass
    {
    }
    public abstract class Abstract:Iclass ,Iclass1
    {
    }
  • An Interface cannot contain fields.
  • An abstract class can contain fields.
  • An Interface can contain property definitions.
  • An abstract class can implement a property.
  • An Interface cannot contain constructors or destructors.
  • An abstract class can contain constructors or destructors.
  • An Interface can be inherited from by structures.
  • An abstract class cannot be inherited from by structures.
  • An Interface can support multiple inheritance.
  • An abstract class cannot support multiple inheritance.
Example:
    public class Class3 : Iclass1 , Iclass
    {
    }
    Public abstract class Class3 : class1 ,class //Error
    {
    }