add

Monday, 18 June 2018

Asp.net interview Questions


 Asp.net Interviw Questions


Here I am posting the interview questions whatever i have faced in my interviews
I have searched for so many websites and gathered information from my friends to answer the questions perfectly.
i think these questions are very helpful for the people who are trying to get the job on .NET
The most common question for experience persons is

Why would you like to change the company?
1) I am looking for a more challenging career in a firm with a larger employee base such as yours.
2) Keeping in mind my career goals, the time has come for me to move onto the next rung of 
the ladder and make a mark for myself. This can be achieved in a company like this.
3) It is just a career move to enhance my knowledge in my own area of interest.
After completion of this question only interview will go for further questions

Difference between stored procedure and function

1) Procedure can return zero or n values whereas function can return one value which is mandatory.
2) Procedures can have input, output parameters for it whereas functions can have only input parameters.
3) Procedure allows select as well as DML statement in it whereas function allows only select statement in it.
4) Functions can be called from procedure whereas procedures cannot be called from function.
5) Exception can be handled by try-catch block in a procedure whereas try-catch block cannot be used in a function.
6) We can go for transaction management in procedure whereas we can't go in function.
7) Procedures cannot be utilized in a select statement whereas function can be embedded in a select statement.

Difference between Abstract and Interface

Abstract Class:

-Abstract class provides a set of rules to implement next class
-Rules will be provided through abstract methods
-Abstract method does not contain any definition
-While inheriting abstract class all abstract methods must be override
-If a class contains at least one abstract method then it must be declared as an “Abstract Class”
-Abstract classes cannot be instantiated (i.e. we cannot create objects), but a reference can be created
-Reference depends on child class object’s memory
-Abstract classes are also called as “Partial abstract classes”
-Partial abstract class may contain functions with body and functions without body
-If a class contains all functions without body then it is called as “Fully Abstract Class” (Interface)

Interface:


-If a class contains all abstract methods then that class is known as “Interface”
-Interfaces support like multiple inheritance
-In interface all methods r public abstract by default
-Interfaces r implementable
-Interfaces can be instantiated, but a reference cannot be created

Index types in SQL Server

Clustered Index
Only 1 allowed per table physically rearranges the data in the table to confirm to the index constraints for use on columns that are frequently searched for ranges of data for use on columns with low selectivity.

Non-Clustered Index
Up to 249 allowed per table creates a separate list of key values with pointers to the location of the data in the data pages For use on columns that are searched for single values 
A clustered index is a special type of index that reorders the way records in the table are physically stored. Therefore table can have only one clustered index. The leaf nodes of a clustered index contain the data pages. A non-clustered index is a special type of index in which the logical order of the index does not match the physical stored order of the rows on disk. The leaf node of a non-clustered index does not consist of the data pages. Instead, the leaf nodes contain index rows.

Included Column Index (New in SQL Server 2005) 
In SQL Server 2005, the functionality of non-clustered indexes is extended by adding non-key columns to the leaf level of the non-clustered index. Non-key columns can help to create cover indexes. By including non-key columns, you can create non-clustered indexes that cover more queries. The Database Engine does not consider non-key columns when calculating the number of index key columns or index key size. Non-key columns can be included in non-clustered index to avoid exceeding the current index size limitations of a maximum of 16 key columns and a maximum index key size of 900 bytes. Another advantage is that using non-key column in index we can have index data types not allowed as index key columns generally.
In following example column Filename is varchar(400), which will increase the size of the index key bigger than it is allowed. If we still want to include in our cover index to gain performance we can do it by using the Keyword INCLUDE.
USE AdventureWorks
GO
CREATE INDEX IX_Document_Title
ON Production.Document (Title, Revision)
INCLUDE (FileName)



Non-key columns can be included only in non-clustered indexes. Columns can’t be defined in both the key column and they INCLUDE list. Column names can’t be repeated in the INCLUDE list. Non-key columns can be dropped from a table only after the non-key index is dropped first. For Included Column Index to exist there must be at least one key column defined with a maximum of 16 key columns and 1023 included columns.
Avoid adding unnecessary columns. Adding too many index columns, key or non-key as they will affect negatively on performance. Fewer index rows will fit on a page. This could create I/O increases and reduced cache efficiency. More disk space will be required to store the index. Index maintenance may increase the time that it takes to perform modifications, inserts, updates, or deletes, to the underlying table or indexed view.

Another example to test:
Create following Index on Database AdventureWorks in SQL SERVER 2005

USE AdventureWorks
GO
CREATE NONCLUSTERED INDEX IX_Address_PostalCode
ON Person.Address (PostalCode)
INCLUDE (AddressLine1, AddressLine2, City, StateProvinceID)
GO

Test the performance of following query before and after creating Index. The performance improvement is significant.
SELECT AddressLine1, AddressLine2, City, StateProvinceID, PostalCode
FROM Person.Address
WHERE PostalCode BETWEEN '98000'
AND '99999';
GO

Interview questions 

What are differences between Array list and Hash table?
Ans: 1) Hash table store data as name, value pair. While in array only value is store.
2) To access value from hash table, you need to pass name. While in array, to access value, you need to pass index number.
3) you can store different type of data in hash table, say int, string etc. while in array you can store only similar type of data.

What are differences between system.stringbuilder and system.string?
The main difference is system.string is immutable and system.stringbuilder is a mutable. Append keyword is used in string builder but not in system.string.
Immutable means once we created we cannot modified. Suppose if we want give new value to old value simply it will discarded the old value and it will create new instance in memory to hold the new value.

What are the differences between Application object and session object?
Ans: The session object is used to maintain the session of each user. If one user enter in to the application then they get session id if he leaves from the application then the session id is deleted. If they again enter in to the application they get different session id.
But for application object the id is maintained for whole application. 

What are the different types of indexes?
Ans: Two types of indexes are there one is clustered index and non-clustered index

How many types of memories are there in .net? 
Ans: Two types of memories are there in .net stack memory and heap memory

Is it possible to set the session out time manually? 
Ans: Yes we can set the session out time manually in web.config.

What are differences between function and stored procedure?
Ans:
1) Function returns only one value but procedure returns one or more than one value.
2) Function can be utilized in select statements but that is not possible in procedure.
3) Procedure can have an input and output parameters but function has only input parameters only.
4) Exceptions can be handled by try catch block in procedures but that is not possible in function.

What are the differences between Abstract and interface?
Ans:  1) Abstract cannot be instantiated but we can inherit. Interface it cannot be inherit it can be instantiate
2) Interface contain only declarations no definitions. Abstract contain declarations and definitions.
3) The class which contains only abstract methods is interface class. A class which contains abstract method is called abstract class
4) Public is default access specifier for interface we don’t have a chance to declare other specifiers. In abstract we have chance to declare with any access specifier

Can you Explain Page lifecycle in .net?
Can you Explain .NET architecture in .net?

What is the difference between primary key and unique key with not null?
Ans: There is no difference between primary key and unique key with not null.

What is boxing and unboxing concepts in .net? 
Ans: Boxing is a process of converting value type into reference type
Unboxing is a process of converting reference type to value type.

What are the differences between value type and reference type?
Ans: Value type contain variable and reference type are not containing value directly in its memory.
Memory is allocated in managed heap in reference type and in value type memory allocated in stack. Reference type ex-class value type-struct, enumeration

Is it possible to host the website from desktop?
Ans: Yes 

Why we go for page rendering in Asp.Net Page life cycle?
Ans: Browser understands an only html control that’s why in page rendering we will convert the aspx controls into html controls.

Write a sample query for self join?
Ans: Select e1.ename, e2.empid from emp e1, emp e2 where e1.empid=e2.mgrid;

Can we change the index of primary key on table?
Ans: No

How to change the name of the table or stored procedure in sql?
Ans: sp_rename oldtablename newtablename
For changing the column name
Sp_rename  ‘tablename.[Oldcolumnname]’,’newcolumnname’,’Column’
Ex:sp_rename ‘tblemp.first’,’namechange’,’Column’

How to find out which index is defined on table?
Ans: sp_helpindex tablename

Can you write the program to find the length of string without using library function?
Ans: for (int i=0; str[i]!=”\n”; i++)
{
Count++;
}

What is the difference between scope_identity() and current_identity()?
Ans: Scope_identity and current _identity both are similar and it will return the last identity value generated in the table.
Scope_Identity will return the identity value in table that is currently in scope

What are difference between GET and POST Methods?
Ans:
GET Method (): 

1) Data is appended to the URL.
2) Data is not secret.
3) It is a single call system
4) Maximum data that can be sent is 256.
5) Data transmission is faster
6) this is the default method for many browsers

POST Method (): 


1) Data is not appended to the URL.
2) Data is Secret
3) it is a two call system.
4) There is no Limit on the amount of data. That is characters any amount of data can be sent.
5) Data transmission is comparatively slow.
6) No default and should be explicitly specified.

What are difference between truncate and delete?
Ans: 1) Delete keep the lock over each row where Truncate keeps the lock on table not on all the row.
2) Counter of the Identity column is reset in Truncate where it is not reset in Delete.
3) Trigger is not fired in Truncate where as trigger is fired in Delete.
4) In TRUNCATE we cannot rollback.
5) In DELETE we can rollback

What is the difference Grid View and between Data Grid (Windows)?
Ans:
1) GridView Control Enables you to add sorting, paging and editing capabilities without writing any code.
2)GridView Control Automatically Supports paging by setting the ‘PagerSetting’ Property.The Page Setting Property supports four Modles 

a. Numeric(by default)
b. Next Previous
c. NumericFirstLast
d. Next PreviousLast

3)It is Used in asp.net
4)GridView Supports RowUpdating and RowUpdated Events.
5)GidView is Capable of Pre-Operations and Post-Operations.
6)GridView Has EditTemplates for this control
7)It has AutoFormat

DataGrid(Windows)

1)DataGid Control raises single Event for operations
2)DataGird Supports the SortCommand Events that occur when a column is Soted.
3)DataGrid Supports UpdataCommand Event that occurs when the UpdateButton is clicked for an item in the grid.
4)DataGrid is used in Windows GUI Application.
5)It doesnot have EditTemplates for this control
6)It doesnot have AutoFormat

If I write System.exit (0); at the end of the try block, will the finally block still execute?
Ans: No in this case the finally block will not execute because when you say system.exit(0),the control immediately goes out of the program, and thus finally never executes.

What are the different levels of State management in ASP.NET?
Ans:
State management is the process by which you maintain state and page information over multiple requests for the same or different pages.

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:

a. 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.

b. 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.

c. 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.

d. 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.

e. 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.

2. Server – Side State Management
a. Application State - Application State information is available to all pages, regardless of which user requests a page.

b. 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.

Abstract Class:

Abstract class is a class which can’t be instantiate. Class should have “Abstract” key word with the name.  In any one of the method of class having abstract method with in it, then it should be define as abstract class. The class which derived the abstract class should have definition of the abstract method. These classes which derived the abstract class and implement the abstract methods call concrete class.
Abstract class may have the definition of function or may not.  Below is the simple example of an abstract class
public abstract alass AbstractStudent
    {
        String Roll
        {
            get;
            set;
        }

        String FirstName
        {
            get;
            set;
        }
       
        String LastName
        {
            get;
            set;
        }
       

        Public String GetStudentDetails()
             {

                  // Implementation of Method   
             }

        public String SaveStudentDetails ()
            {
                  // Implementation of Method   
             }

        public abstract String CalculateWage();

    }
So, the class having one abstract method so we need to mention the class as "abstract" .

Difference between Abstract Class and Interface?

Abstract class is a class which can’t be instantiated and which can have methods with definition as well as declaration also. This can be inherited. 

As for Example:

public abstract class AbstractStudent
    {
        String Roll
        {
            get;
            set;
        }

        String FirstName
        {
           get;
           set;
        }
  
        String LastName
        {
           get;
            set;
        }

        Public String GetStudentDetails()
            {
                 // Implementation of Method  
             }

        public String SaveStudentDetails ()
            {
                  // Implementation of Method  
            }

        public abstract String CalculateWage();

    }


Interface can only contain the methods declaration and can be implemented in the class.

As for Example:
Public interface IStudnet
    {
        String Roll
        {
           get;
            set;
        }

        String FirstName
        {
            get;
            set;
        }
   
        String LastName
        {
            get;
            set;
        }
  
        String GetStudentDetails();
        String SaveStudentDetails ();
    }

Below are the few main difference between Abstract Class and Interface

a.    In abstract class method can have definition as well as declaration also. But Interface should have only definition.
b.    All the Methods are Public as default and don’t have any access Modifier Controls in interface, whereas for abstract class we can have access modifier for methods.
c.    Abstract class can have constructor or destructor, whereas interface not.
d.    Abstract class can’t be part of multiple inheritance and we can implement multiple interface.

What do you mean by String objects are immutable?
String objects are immutable as its state cannot be modified once created. Every time when we perform any operation like add, copy, replace, and case conversion or when we pass a string object as a parameter to a method a new object will be created.

Example:
String str = "ABC";

str.Replace("A","X");

Here Replace() method will not change data that "str" contains, instead a new string object is created to hold data "XBC" and the reference to this object is returned by Replace() method.

So in order to point str to this object we need to write below line.
str = str.Replace("A","X");
Now the new object is assigned to the variable str. earlier object that was assigned to str will take care by garbage collector as this one is no longer in used.

What is dll hell problem in .NET and how it will solve?
Ans: Dll hell, is kind of conflict that occurred previously, due to the lack of version supportability of dll for (within) an application
.NET Framework provides operating system with a global assembly cache. This cache is a repository for all the .net components that are shared globally on a particular machine. When a .net component installed onto the machine, the global assembly cache looks at its version, its public key and its language information and creates a strong name for the component. The component is then registered in the repository and indexed by its strong name, so there is no confusion between the different versions of same component, or DLL

What is a Partial class?
Ans: Instead of defining an entire class, you can split the definition into multiple classes by using partial class keyword. When the application compiled, c# compiler will group all the partial classes together and treat them as a single class. There are a couple of good reasons to use partial classes. Programmers can work on different parts of classes without needing to share same physical file
Ex:
Public partial class employee
{
Public void somefunction()
{
}
}
Public partial class employee
{
Public void function ()
{
}
}

What is difference between constants, read-only and, static?

Constants: The value can’t be changed
Read-only: The value will be initialized only once from the constructor of the class.
Static: Value can be initialized once.

What is the cross page post backing?
Asp.Net 2.0 fixed this with built-in features that allowed us to easily send information from one page to another.

Button control has property PostBackUrl that can be set to URL of any page in our ASP.Net WebSite where we want to transfer all form values to.
Along with that Asp.Net 2.0 Page class has a property PreviousPage that allows us to get reference to the Page object that initiated the postback (in other words to get the actual reference to the Page object of the aspx page on which user clicked the Submit button on a HTML form).

So for example lets create two sample pages in our Web Application:  
  • SourcePage.aspx
  • DestinationPage.aspx
In SoucePage in Html form we will put two TextBox controls (one for First Name and one for Last Name) and one Button component  and set its PostBackUrl property to "~/DestinationPage.aspx".

SourcePage.aspx:
    <form id="form1"runat="server">
        <div>
            First Name:&nbsp;<asp:TextBoxID="FirstName"runat="server"></asp:TextBox><br/>
            Last Name:&nbsp;<asp:TextBoxID="LastName"runat="server"></asp:TextBox><br/><br />
            <asp:ButtonID="Button1"runat="server"Text="Submit To Destination Page" PostBackUrl="~/CrossPagePostbacks/DestinationPage.aspx"/>
        </div>
    </form>

When our user clicks the Submit button, all the values from the HTML Form on SourcePage.aspx will be transfered to the DestinationPage.aspx and we will also be able to get reference to the SourcePage.aspx in our DestinationPage with the PreviousPage property like this:

So in our DestinationPage.aspx.cs code-behind we can easily access two TextBox controls on SourcePage.aspx and show them in two label controls like this:
    protected voidPage_Load(object sender, EventArgse)
    {
        // first check if we had a cross page postback
        if ( (PreviousPage != null) && (PreviousPage.IsCrossPagePostBack) )
        {
            PagepreviousPage = PreviousPage;
            TextBoxfirstName = (TextBox)previousPage.FindControl("FirstName");
            TextBoxlastName = (TextBox)previousPage.FindControl("LastName");
            // we can now use the values from TextBoxes and display them in two Label controls..
            labelFirstName.Text = firstName.Text;
            labelLastName.Text = lastName.Text;
         }
    }

You probably noticed that we first checked if PreviousPage property of current page (DestinationPage.aspx) is NOT NULL, this is done to avoid running our code in case that user opens our DestinationPage.aspx directly, without running a cross page postback.

Also here we checked the another PreviousPage property called IsCrossPagePostBackto see if we really had a CrossPagePostback.
(If Server.Transfer is used to redirect to this page, IsCrossPagePostBackproperty will be set to FALSE.

TIP: We can be completely sure that we have a  real CrossPagePostback ONLY IF:
  1. Page.PreviousPage is NOT NULL,
  2. PreviousPage.IsCrossPagePostback is true
This important to check to avoid errors in code.

Now this is very useful and i'm sure you are eager to use this in your next project. But wait, we are not over yet!

Finding the controls on PreviousPage with FindControl method and type-casting them from object to their real type is a little messy.
It feels like there must be a better solution for this!

And here it is: We can use the <%@ PreviousPageType %> directive in the header of our DestinationPage.aspx like this
    <%@ PreviousPageTypeVirtualPath="~/SourcePage.aspx"%>

to declare our previous page type, and then we can access Public properties of the PreviousPage without typecasting.
Now all we need to do is to create some public properties on our SourcePage.aspx.cs to expose data/Controls we want to the destionation page:
    public partialclass SourcePage: System.Web.UI.Page
    {
        public stringFormFirstName
        {
            get { returnFirstName.Text; }
        }

        public stringFormLastName
        {
            get { returnLastName.Text; }
        }
    }

And then we can change the Page_Load code in our DestinationPage.aspx to much cleaner code like this:
    protected voidPage_Load(object sender, EventArgse)
    {
        // first check if we had a cross page postback
        if ( (PreviousPage != null) && (PreviousPage.IsCrossPagePostBack) )
        {
            SourcePageprevPage = PreviousPage;

            // we can now use the values from textboxes and display them in two Label controls..
            labelFirstName.Text = prevPage.FormFirstName;
            labelLastName.Text = prevPage.FormLastName;     
        }
    }

SourcePage type used in the code is offcourse name of the partial class defined is SourcePage.aspx.cs that inherits System.Web.UI.Page that is automatically created for us when we created new WebForm in VisualStudio.

This code is much cleaner and easier to follow, there is no ugly typecasting, just simple property values to use to retrieve the data from previous page.
When should you use Abstract Class vs Interface while programming?

 
Ans: When we want that sub class must implement all the methods of base class. In such a situation we will implement the interface. In the other hand when we want only some method of base class in our sub class then use base class as abstract class.

What is the difference between application exception and system exception?
Ans: The difference between application exception and system exception is that system exceptions are thrown by CLR and application exceptions are thrown by applications.

What is the difference between authorization and authentication?
Ans: Authorization is a process of allowing or denying resources to particular user or record 

Declaration of authorization is
<authorization>
<allow users=”Suresh, Sanjay”/>
<deny users=”Ramana, Rakesh”>
</authorization>
Sometimes authorization allows the unauthorized persons at that time we will use
<deny users=”?”/>

Authentication means
Authentication is a process where we identify the credentials of user i.e. username, password and create an identity to mention user as an authenticated.  

What is the use of n-tier architecture and 3-tier architecture?

Check this article for 3-tier architecture 3 tier architecture example in asp.net

How to get the version of the assembly?
Ans: lbltxt.text=Assembly. GetExecutingAssembly().GetName().Version.ToString();

What is the location of Global Assembly Cache on the system?
Ans: c:\Windows\assembly

 What is the serialization?
Ans: Serialization is a process of converting object into a stream of bites.

What is synchronization?
Ans: The mechanism needed to block one thread access to the data. If the data is being accessed by another thread.
Synchronization can be accessed by using system.monitor class
A monitor class methods are enter, exit, pulse for this lock statement is also used
Suppose if we need to synchronize some data at that time we need to place that data in this block
Lock
{
}
Whatever the data has been placed into the lock block that data has been blocked

What are the thread priority levels?
Ans: Thread priority levels are five types
         0 - Zero level
         1 - Below Normal
         2 - Normal
         3 - Above Normal
         4 - Highest
By Default priority level is 2

What is the difference between .tostring(), Convert.tostring()?
Ans: The basic difference between them is “Convert” function handles NULLS while
“.ToString()” does not it will throw a NULL reference exception error. So as a good coding
practice using “convert” is always safe.

What is Collation?
Ans: Collation refers to a set of rules that determine how the data is sorted and compared.

What is the difference between Primary key and unique key?
Ans: Primary key does not allow the null values but unique key allows one null value.
Primary key will create clustered index on column but unique key will create non-clustered index by default.

How many web.config files are there in 1 project?
Ans: There might be multiple web.config files for a single project depending on the hierarchy of folders inside the root folder of the project, so for each folder we can use one web.config file

What is the difference between throw and throw ex?
What is the difference between view state and hidden field?
Ans: viewstate is secured hidden field is insecure
Viewstate will store large amount of data but hidden filed will store small amount of data. 

What is the difference between binary serialization and xml serialization?
What is the Difference between read only and constant variables?
Ans: Read only can assign the values at runtime only.
Constant will assign the values at compile time only.
We cannot modify the both variable values.

What is static keyword in .Net?
Ans: Static is same as constant variable but we can change the value of static variable and we can access the variables without creating any instances

What is the use of business logic layer in 3-tier architecture in .net?
Ans: Though a web site could talk to the data access layer directly, it usually goes through another layer called the business layer. The business layer is vital in that it validates the input conditions before calling a method from the data layer. This ensures the data input is correct before proceeding, and can often ensure that the outputs are correct as well. This validation of input is called business rules, meaning the rules that the business layer uses to make “judgments” about the data.
However, business rules don’t only apply to data validation; these rules apply to any calculations or any other action that takes place in the business layer. Normally, it’s best to put as much logic as possible in the business layer, which makes this logic reusable across applications.
One of the best reasons for reusing logic is that applications that start off small usually grow in functionality. For instance, a company begins to develop a web site, and as they realize their business needs, they later decide to add a smart client application and windows service to supplement the web site. The business layer helps move logic to a central layer for “maximum reusability.”

Check this post introduction to 3-tier Architecture

What happens when I enter a URL in my browser and click enter?
You type in the URL and hit go. The browser needs to translate that URL www.somesite.com into an IP address so it knows what computer on the internet to connect to (That URL is just there to make it easier for us humans - kinda like speed-dial for phone numbers I guess). So your browser will see if it already has the appropriate IP address cached away from previous visits to the site. If not, it will make a DNS query to your DNS server (might be your router or your ISP's DNS server) - see http://en.wikipedia.org/wiki/Domain_name… for more on DNS. Once your browser knows what IP to use, it will connect to the appropriate webserver and ask for the page. The webserver then returns the requested page and your browser renders it to the screen.

The firewall will control connections to & from your computer. For the most part it will just be controlling who can connect to your computer and on what ports. For web browsing your firewall generally won't be doing a whole lot.

Your router (see http://en.wikipedia.org/wiki/Router ) essentially guides your request through the network, helping the packets get from computer to computer and potentially doing some NAT (see http://en.wikipedia.org/wiki/Network_add… ) to translate IP addresses along the way (so your internat LAN request can be transitioned onto the wider internet and back).

IP Addresses (see http://en.wikipedia.org/wiki/IP_address ) are unique addresses for computers that basically allow computers to find each other. Think of the IP address as a computer's well address or phone number, you've got to know someone's phone number before you can call them and you've got to know a computer's IP address before you can connect to it. Going back to the start - that's what those URLS and DNS make possible, you don't know John Doe's phone number so you look in the phone book; likewise your computer doesn't know yahoo.com's IP address so it looks in DNS.



















C# - Destructor in C# with Example

Suresh Dasari Sep 29, 2013
Introduction:

Here I will explain what is destructor in c# with example, use of destructor in c#.net. Destructor in c# is a special method of a class which will invoke automatically when an instance of the class is destroyed. Destructor is used to write a code that needs to be executed while an instance is destroyed.

Description:

In previous posts I explained constructors in c#, polymorphism in c# with example, private constructor in c#, static constructor in c#, delegates example in c#, sealed class in c#, using statement in c#, OOPS examples in c# and many articles relating to interview questions in c#, asp.net, SQL server, JavaScript, jQuery. Now I will explain destructor in c#.net with example.

To create destructor we need to create method in a class with same name as class preceded with ~ operator.

Syntax of Destructor


class SampleA
{
public SampleA()
{
// Constructor
}
~SampleA()
{
// Destructor
}
}
Example of Destructor

In below example I created a class with one constructor and one destructor. An instance of class is created within a main function. As the instance is created within the function, it will be local to the function and its life time will be expired immediately after execution of the function was completed.


using System;
namespace ConsoleApplication3
{
class SampleA
{
// Constructor
public SampleA()
{
Console.WriteLine("An  Instance  Created");
}
// Destructor
~SampleA()
{
Console.WriteLine("An  Instance  Destroyed");
}
}

class Program
{
public static void Test()
{
SampleA T = new SampleA(); // Created instance of class
}
static void Main(string[] args)
{
Test();
GC.Collect();
Console.ReadLine();
}
}
}
When we run above program it will show output like as shown below

Output


An instance created
An instance destroyed
I hope it helps you to know about destructor concept. If you want to know more about oops concept check this link oops concepts














C# - Private Constructor in C# with Example

Suresh Dasari Sep 27, 2013
Introduction:

Here I will explain what is private constructor in c# with example. Private constructor in c# is used to restrict the class from being instantiated when it contains every member as static.

Description:

In previous posts I explained static constructor in c#, copy constructor in c#, use of virtual, override and new keyword with examples in c# method overloading and overriding, delegates example in c#, OOPS examples in c# and many articles relating to interview questions in oops concepts, c#, asp.net, SQL server, JavaScript, jQuery. Now I will explain private constructor in c#.net with example.

Constructor is a special method of a class which will invoke automatically whenever instance or object of class is created. Constructors are responsible for object initialization and memory allocation of its class. If we create any class without constructor, the compiler will automatically create one default constructor for that class. There is always at least one constructor in every class. If you want to know more about constructors check this article constructors in c#.

Private Constructor

Private constructor is a special instance constructor used in a class that contains static member only. If a class has one or more private constructor and no public constructor then other classes is not allowed to create instance of this class this mean we can neither create the object of the class nor it can be inherit by other class. The main purpose of creating private constructor is used to restrict the class from being instantiated when it contains every member as static.


using System;
namespace ConsoleApplication3
{
public class Sample
{
public string param1, param2;
public Sample(string a,string b)
{
param1 = a;
param2 = b;
}
private Sample()  // Private Constructor Declaration
{
Console.WriteLine("Private Constructor with no prameters");
}
}
class Program
{
static void Main(string[] args)
{
// Here we don't have chance to create instace for private constructor
Sample obj = new Sample("Welcome","to Aspdotnet-Suresh");
Console.WriteLine(obj.param1 +" " + obj.param2);
Console.ReadLine();
}
}
}
 Output


Welcome to Aspdotnet-Suresh
In above method we can create object of class with parameters will work fine. If create object of class without parameters it will not allow us create.


// it will works fine
Sample obj = new Sample("Welcome","to Aspdotnet-Suresh");
// it will not work because of inaccessability
Sample obj=new Sample();
Important points of private constructor

-      One use of private construct is when we have only static member.
-      Once we provide a constructor that is either private or public or any, the compiler will not allow us to add public constructor without parameters to the class.
-      If we want to create object of class even if we have private constructors then we need to have public constructor along with private constructor

I hope it helps to know about private constructor. If you want to know more about constructors check this article constructors in c#.















C# - Static Constructor in C#.NET with Example

Suresh Dasari Sep 27, 2013
Introduction:

Here I will explain what is static constructor in c# with example. Static constructor in c# is used to create static fields of the class and to write the code that needs to be executed only once. 

Description:


Constructor is a special method of a class which will invoke automatically whenever instance or object of class is created. Constructors are responsible for object initialization and memory allocation of its class. If we create any class without constructor, the compiler will automatically create one default constructor for that class. There is always at least one constructor in every class. If you want to know more about constructors check this article constructors in c#.

Static Constructor

When we declared constructor as static it will be invoked only once for any number of instances of the class and it’s during the creation of first instance of the class or the first reference to a static member in the class. Static constructor is used to initialize static fields of the class and to write the code that needs to be executed only once.


using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
static Sample()
{
Console.WriteLine("Static Constructor");
}
public Sample()
{
param1 = "Sample";
param2 = "Instance Constructor";
}
}
class Program
{
static void Main(string[] args)
{
// Here Both Static and instance constructors are invoked for first instance
Sample obj=new Sample();
Console.WriteLine(obj.param1 + " " + obj.param2);
// Here only instance constructor will be invoked
Sample obj1 = new Sample();
Console.WriteLine(obj1.param1 +" " + obj1.param2);
Console.ReadLine();
}
}
}
When we run above program we will get output like as shown below

Output


Static Constructor
Sample Instance Constructor
Sample Instance Constructor
Importance points of static constructor

-      Static constructor will not accept any parameters because it is automatically called by CLR.
-      Static constructor will not have any access modifiers.
-      Static constructor will execute automatically whenever we create first instance of class
-      Only one static constructor will allowed.



















C# - What is Delegates in C# Example | Use of Delegates in C#

Suresh Dasari Sep 20, 2013
Introduction:

Here I will explain what is delegates in c#.net with example. Basically delegates in c# are type safe objects which are used to hold reference of one or more methods in c#.net. Delegates concept will match with pointer concept of c language.  

Description:

In previous posts I explained OOPS examples in c#, polymorphism in c#, Difference b/w datareader, dataset and dataadapter in c#, Difference b/w appsettings and connection strings in asp.net, Difference b/w executereader, executenonquery and executescalar in c# and many articles relating to interview questions in c#, asp.net, sql server, javascript, jquery. Now I will explain delegates in c#.net with example.

Whenever we want to create delegate methods we need to declare with delegatekeyword and delegate methods signature should match exactly with the methods which we are going to hold like same return types and same parameters otherwise delegate functionality won’t work if signature not match with methods.

Syntax of Delegate & Methods Declaration

Check below sample code for delegate declaration and methods declaration


public delegate int Delegatmethod(int a,int b);

public class Sampleclass
{
public int Add(int x, int y)
{
return x + y;
}
public int Sub(int x, int y)
{
return x + y;
}
}
If you observe above code I declared Delegatmethod method with two parameters which matching with methods declared in Sampleclass class.

Complete Example


public delegate int DelegatSample(int a,int b);
public class Sampleclass
{
public int Add(int x, int y)
{
return x + y;
}
public int Sub(int x, int y)
{
return x - y;
}
}
class Program
{
static void Main(string[] args)
{
Sampleclass sc=new Sampleclass();

DelegatSample delgate1 = sc.Add;
int i = delgate1(10, 20);
Console.WriteLine(i);
DelegatSample delgate2 = sc.Sub;
int j = delgate2(20, 10);
Console.WriteLine(j);
}
}
Output

Whenever we run above code we will get output like as shown below


Add Result : 30
Sub Result : 10
What is the use of Delegates?

Suppose if you have multiple methods with same signature (return type & number of parameters) and want to call all the methods with single object then we can go for delegates.

Delegates are two types

      -   Single Cast Delegates
      -  Multi Cast Delegates

Single Cast Delegates

Single cast delegate means which hold address of single method like as explained in above example.

Multicast Delegates

Multi cast delegate is used to hold address of multiple methods in single delegate. To hold multiple addresses with delegate we will use overloaded += operator and if you want remove addresses from delegate we need to use overloaded operator -=

Multicast delegates will work only for the methods which have return type only void. If we want to create a multicast delegate with return type we will get the return type of last method in the invocation list

Check below sample code for delegate declaration and methods declaration


Syntax of Multicast Delegate & Method Declaration

Check below sample code for multicast delegate declaration and methods declaration


public delegate void MultiDelegate(int a,int b);
public class Sampleclass
{
public static void Add(int x, int y)
{
Console.WriteLine("Addition Value: "+(x + y));
}
public static void Sub(int x, int y)
{
Console.WriteLine("Subtraction Value: " + (x - y));
}
public static void Mul(int x, int y)
{
Console.WriteLine("Multiply Value: " + (x * y));
}
}
If you observe above code I declared MultiDelegate method with void return type.

Complete Example


public delegate void MultiDelegate(int a,int b);
public class Sampleclass
{
public static void Add(int x, int y)
{
Console.WriteLine("Addition Value: "+(x + y));
}
public static void Sub(int x, int y)
{
Console.WriteLine("Subtraction Value: " + (x - y));
}
public static void Mul(int x, int y)
{
Console.WriteLine("Multiply Value: " + (x * y));
}
}
class Program
{
static void Main(string[] args)
{
Sampleclass sc=new Sampleclass();
MultiDelegate del = Sampleclass.Add;
del += Sampleclass.Sub;
del += Sampleclass.Mul;
del(10, 5);
Console.ReadLine();
}
}
Output

Whenever we run above code we will get output like as shown below


Addition Value : 15
Subtraction Value : 5
Multiply Value : 50
I hope this post helps you to understand delegates in c#. Happy coding….

























C# - Early Binding and Late Binding with Example & Difference b/w Early & Late Binding

Suresh Dasari Sep 19, 2013
Introduction:

Here I will explain difference between early binding and late binding in c#.net with example or c#.net late binding vs early binding with example. 

Description:

In previous posts I explained OOPS examples in c#, polymorphism in c#, Difference b/w datareader, dataset and dataadapter in c#, Difference b/w appsettings and connection strings in asp.net, Difference b/w executereader, executenonquery and executescalar in c#, difference b/w view and stored procedure in sql and many articles relating to interview questions in c#, asp.net, sql server, javascript, jquery. Now I will explain Difference between early binding and late binding in c#.net with example.

Early Binding and Late Binding concepts occurred in polymorphism. First we will learn about polymorphism

Polymorphism

Polymorphism means many forms (ability to take more than one form). In Polymorphism poly means “multiple” and morph means “forms” so polymorphism means many forms.

In polymorphism we will declare methods with same name and different parameters in same class or methods with same name and same parameters in different classes. Polymorphism has ability to provide different implementation of methods that are implemented with same name.

In Polymorphism we have 2 different types those are

     -      Compile Time Polymorphism (Called as Early Binding or Overloading or static binding)

     -      Run Time Polymorphism (Called as Late Binding or Overriding or dynamic binding)

Compile Time Polymorphism or Early Binding

Compile time polymorphism means we will declare methods with same name but different signatures because of this we will perform different tasks with same method name. This compile time polymorphism also called as early binding or method overloading.

Method Overloading or compile time polymorphism means same method names with different signatures (different parameters)

For more details check this link polymorphism in c#

Run Time Polymorphism or Late Binding

Run time polymorphism also called as late binding or method overridingor dynamic polymorphism. Run time polymorphism or method overriding means same method names with same signatures.

In this run time polymorphism or method overriding we can override a method in base class by creating similar function in derived class this can be achieved by using inheritance principle and using “virtual & override” keywords.

For more details check this link polymorphism in c#
































C# - Difference between Array and Arraylist in C# with Example

Suresh Dasari Sep 17, 2013
Introduction:

Here I will explain difference between array and arraylist in c#.net with example.  

Description:

In previous posts I explained difference between wcf and web application, interview questions in asp.net, sql server, c#, Difference between functions and stored procedures in SQL Server, difference between len and datalength in sql server and many articles relating to interview questions. Now I will explain difference between array and arraylist in c#.net with example.

Arrays

Arrays are strongly typed collection of same datatype and these arrays are fixed length that cannot be changed during runtime. Generally in arrays we will store values with index basis that will start with zero. If we want to access values from arrays we need to pass index values.

Declaration of Arrays

Generally we will declare arrays with fixed length and store values like as shown below


string[] arr=new string[2];
arr[0] = "welcome";
arr[1] = "Aspdotnet-suresh";
In above code I declared array size 2 that means we can store only 2 string values in array.

Arraylists

Array lists are not strongly type collection. It will store values of different datatypes or same datatype. Array list size will increase or decrease dynamically it can take any size of values from any data type. These Array lists will be accessible with “System.Collections” namespace

Declaration of Arraylist

To know how to declare and store values in array lists check below code


ArrayList strarr = new ArrayList();
strarr.Add("welcome"); // Add string values
strarr.Add(10);   // Add integer values
strarr.Add(10.05); // Add float values
If you observe above code I haven’t mentioned any size in array list we can add all the required data there is no size limit and we will use add method to bind values to array list

Difference between Array and ArrayList

Arrays
ArrayLists
These are strong type collection and allow to store fixed length
Array Lists are not strong type collection and size will increase or decrease dynamically

In arrays we can store only one datatype either int, string, char etc…

In arraylist we can store all the datatype values
Arrays belong to System.Array namespace
Arraylist belongs to System.Collection namespaces




























Whether functions will return multiple values or not?

For this question answer will be Yes functions will return either single or multiple values.  

Generally SQL Server functions will return only one parameter value if we want to return multiple values from function then we need to send multiple values in table format by using table valued functions.

Sample function which return table as parameter


CREATE FUNCTION testmultiplevalues
(
@UserId INT
)
returns table as
return
(
Select * from UserInformation WHERE UserId=@userId
)
We can call this function in our query like as shown below


SELECT * FROM dbo.testmultiplevalues(14)
If we run above query we will get output like as shown below

Demo

 














SQL Server- Difference between View and Stored Procedure

Suresh Dasari Aug 30, 2013
Introduction:

Here I will explain difference between SQL SERVER view and stored procedure in SQL Server 2008.  
Description:

In previous posts I explained difference between wcf and web application, interview questions in asp.net, sql server, c#, Difference between functions and stored procedures in SQL Server, difference between len and datalength in sql server and many articles relating to SQL Server. Now I will explain the differences between SQL view and stored procedures.

View in SQL Server

A view represents a virtual table. By using view we can join multiple tables and present the data as coming from a single table.

For example consider we have two tables

      1)    UserInformation table with columns userid, username
      2)    SalaryInformation table with columns salid, userid, salary

Create VIEW by joining above two tables


CREATE VIEW VW_UserInfo
AS
BEGIN
SELECT a.userid,a.username,b.salary from UserInformation a INNER JOIN SalaryInformation b ON a.userid=b.userid
END
By using above view we can get username or salary based on userid for that we need to create procedure like as shown below


CREATE PROCEDURE GetUserInfo
@uid INT
AS
BEGIN
SELECT username from VW_UserInfo WHERE userid=@uid
END
If you observe above procedure it’s like getting username from single table (VW_UserInfo) by passing userid

Stored Procedure

A stored procedure is a group of sql statements that has been created and stored in the database. Stored procedure will accept input parameters so that a single procedure can be used over the network by several clients using different input data. Stored procedure will reduce network traffic and increase the performance. If we modify stored procedure all the clients will get the updated stored procedure

Sample of creating Stored Procedure

USE AdventureWorks2008R2;
GO
CREATE PROCEDURE dbo.sp_who
AS
    SELECT FirstName, LastName FROM Person.Person;
GO
EXEC sp_who;
EXEC dbo.sp_who;
GO
DROP PROCEDURE dbo.sp_who;
GO
For more information check this Stored procedure in SQL Serve




























DIFFRENCE BETWEEN SESSION STATE AND VIEW STATE

      View State

- View state is maintained in page level only.
- View state of one page is not visible in another page.
- View state information stored in client only.
- View state persist the values of particular page in the client (browser) when post back operation done.
- View state used to persist page-instance-specific data. (Read more)

      Session State

- Session state is maintained in session level.
- Session state value is available in all pages within a user session.
- Session state information stored in server.
- Session state persist the data of particular user in the server. This data available till user close the browser or session time completes.
- Session state used to persist the user-specific data on the server side.
 (Read more)   

      Usage

- If you want to access the information on different web pages, you can use SessionState
- If you want to access from the same page, then you can use Viewstate

     Security
     Session state provides more security when compared with view state as the data value is stored in server side






View State

Asp.net ViewState Example in C#, VB.NET

Suresh Dasari Nov 4, 2012
Introduction:

Here I will explain what is viewstate and uses of viewstate with example in asp.net using c# and vb.net.

Description:

In previous posts I explained Create ContactUs Form, Detect Browser type in jQuery, Scroll to particular link when click on link, send mail with images using gmail in asp.net and many relating articles in asp.net, jQuery. Now I will explain what is viewstate and uses of viewstate with example in asp.net using c# and vb.net.

What is ViewState?

ViewState is used to maintain the state of controls during page postback and if we save any control values or anything in viewstate we can access those values throughout the page whenever it required for that check below simple example


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>View State in asp.net Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>ViewState Data:</td><td><b><asp:Label ID="lblString" runat="server"/></b></td>
</tr>
<tr><td></td><td> <asp:Button ID="btnClick" runat="server" Text="Get ViewState Data"
onclick="btnClick_Click"/></td></tr>
</table>
</div>
</form>
</body>
</html>
Now add following namespaces in your codebehind

C# Code


using System;

After that write the following code in button click


protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
string str = "Welcome to Aspdotnet-Suresh Site";
if(ViewState["SampleText"]==null)
{
ViewState["SampleText"] = str;
}
}
}

protected void btnClick_Click(object sender, EventArgs e)
{
lblString.Text = ViewState["SampleText"].ToString();
}
VB.NET Code


Partial Class VBViewStateCode
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
Dim str As String = "Welcome to Aspdotnet-Suresh Site"
If ViewState("SampleText") Is Nothing Then
ViewState("SampleText") = str
End If
End If
End Sub

Protected Sub btnClick_Click(ByVal sender As Object, ByVal e As EventArgs)
lblString.Text = ViewState("SampleText").ToString()
End Sub
End Class









Asp.net Session State Example in C#, VB.NET

Suresh Dasari Nov 5, 2012
Introduction:

Here I will explain SessionState in asp.net with example using c# and vb.net.

Description:

In previous posts I explained ViewState Example in asp.net, Create ContactUs Form, Detect Browser type in jQuery, Scroll to particular link when click on link, send mail with images using gmail in asp.net and many relating articles in asp.net, jQuery. Now I will explain SessionState example in asp.net using c# and vb.net

What is SessionState?

The session state is used to maintain the session of each user throughout the application. Session allows information to be stored in one page and access in another page and support any type of object. In many websites we will see the functionality like once if we login into website they will show username in all the pages for that they will store username in session and they will access that session username in all the pages.

Whenever user enters into website new session id will generate for that user. This session Id will delete when he leave from that application. If he enters again he will get new session Id.

We can check this one with simple example for that create one new website and open Default.aspx page and write the following code

Default.aspx


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Asp.net Session State Example in C#, VB.NET</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h3>SessionStateData.aspx</h3>
<table>
<tr>
<td>FirstName:</td><td><asp:TextBox ID="txtfName" runat="server"/></td>
</tr>
<tr>
<td>LastName:</td><td><asp:TextBox ID="txtlName" runat="server"/></td>
</tr>
<tr><td></td><td> <asp:Button ID="btnSubmit" runat="server" Text="Set SessionState Data" OnClick="btnSubmit_Click" /></td></tr>
</table>
</div>
</form>
</body>
</html>
Now add following namespaces in your codebehind

C# Code


using System;

After that write the following code in button click


protected void Page_Load(object sender, EventArgs e)
{

}
// Set Session values during button click
protected void btnSubmit_Click(object sender, EventArgs e)
{
Session["FirstName"] = txtfName.Text;
Session["LastName"] = txtlName.Text;
Response.Redirect("Default2.aspx");
}
VB.NET Code


Partial Class SessionStateExample
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

End Sub
' Set Session values during button click
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs)
Session("FirstName") = txtfName.Text
Session("LastName") = txtlName.Text
Response.Redirect("Default2.aspx")
End Sub

End Class
Now Right click on your website à select add new item à Select Web Form à Give name as Default2.aspx

Open Default2.aspx page and write the following code

Default2.aspx


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h3>Default2.aspx</h3>
<table>
<tr>
<td colspan="2">Welcome <b><asp:Label ID="lblString" runat="server"/></b></td>
</tr>
<tr>
<td>Your FirstName: </td><td><b><asp:Label ID="lblfName" runat="server"/></b></td>
</tr>
<tr>
<td>Your LastName </td><td><b><asp:Label ID="lbllName" runat="server"/></b></td>
</tr>
<tr><td></td><td> </td></tr>
</table>
</div>
</form>
</body>
</html>
Now add following namespaces in your codebehind

C# Code


using System;

After that write the following code in button click


protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
if (Session["FirstName"] == null && Session["LastName"]==null)
{
Session["FirstName"] = "Aspdotnet";
Session["LastName"] = "  Suresh";
lblString.Text = "Welcome " + Session["FirstName"] + Session["LastName"];
}
else
{
lblString.Text = Session["FirstName"]+" " + Session["LastName"];
lblfName.Text = Session["FirstName"].ToString();
lbllName.Text = Session["LastName"].ToString();
}
}
}
VB.NET Code


Partial Class Default2
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
If Session("FirstName") Is Nothing AndAlso Session("LastName") Is Nothing Then
Session("FirstName") = "Aspdotnet"
Session("LastName") = "  Suresh"
lblString.Text = "Welcome " & Convert.ToString(Session("FirstName")) & Convert.ToString(Session("LastName"))
Else
lblString.Text = Convert.ToString(Session("FirstName")) & " " & Convert.ToString(Session("LastName"))
lblfName.Text = Session("FirstName").ToString()
lbllName.Text = Session("LastName").ToString()
End If
End If
End Sub
End Class
Demo





















Const:

      1.    Const can only be initialized at the time of declaration of the field.
      2.    Const values will evaluate at compile time only.
      3.    Const value can’t be changed these will be same at all the time.
      4.    This type of fields are required when one of the field values remains constant throughout the system like Pi will remain same in your Maths Class.

Read-only:

     1.    The value will be initialized either declaration time or the constructor of the class allowing you to pass the value at run time.
      2.    Read only values will evaluate at runtime only.
        
Example

public class Const_VS_Readonly
{
public const int I_CONST_VALUE = 2;
public readonly int I_RO_VALUE;
public Const_VS_Readonly()
{
I_RO_VALUE = 3;
}
}
Suppose if you want the value of the constant won't change use a const or if you have a constant that may change or when in doubt, use a readonly.  I hope it helps.















C# - Difference between Webservice and WCF in Asp.net

Suresh Dasari Oct 25, 2012
Introduction:

In this article I will explain difference between webservice and wcf in asp.net.

Description:

In previous post I explained Difference between convert.string and .tostring(), difference between web application and website and many articles relating to Interview Questions in asp.net, SQL Server. Now I will explain difference between webservice and wcf in asp.net.

What is Web Service?

Web Service is an application that is designed to interact directly with other applications over the internet. In simple sense, Web Services are means for interacting with objects over the Internet. The Web serivce consumers are able to invoke method calls on remote objects by using SOAP and HTTP over the Web. WebService is language independent and Web Services communicate by using standard web protocols and data formats, such as HTTP, XML and SOAP. (Read More)

What is WCF (windows communication foundation) Service?

Windows Communication Foundation (Code named Indigo) is a programming platform and runtime system for building, configuring and deploying network-distributed services. It is the latest service oriented technology; Interoperability is the fundamental characteristics of WCF. It is unified programming model provided in .Net Framework 3.0. WCF is a combined feature of Web Service, Remoting, MSMQ and COM+. WCF provides a common platform for all .NET communication. (Read More)

Difference between WCF and Web service

Web service is a part of WCF. WCF offers much more flexibility and portability to develop a service when comparing to web service. Still we are having more advantages over Web service; following table provides detailed difference between them.

Features
Web Service
WCF
Hosting
It can be hosted in IIS
It can be hosted in IIS, windows activation service, Self-hosting, Windows service
Programming
[WebService] attribute has to be added to the class
[ServiceContract] attribute has to be added to the class
Model
[WebMethod] attribute represents the method exposed to client
[OperationContract] attribute represents the method exposed to client
Operation
One-way, Request- Response are the different operations supported in web service
One-Way, Request-Response, Duplex are different type of operations supported in WCF
XML
System.Xml.serialization name space is used for serialization
System.Runtime.Serialization namespace is used for serialization
Encoding
XML 1.0, MTOM(Message Transmission Optimization Mechanism), DIME, Custom
XML 1.0, MTOM, Binary, Custom
Transports
Can be accessed through HTTP, TCP, Custom
Can be accessed through HTTP, TCP, Named pipes, MSMQ,P2P, Custom
Protocols
Security
Security, Reliable messaging, Transactions

If you want to know more about WCF check this article Introduction to WCF tutorial

If you want to know more about WebServices check this article Create and Consume WebService tutorial



























Asp.net WebService or Creating and Consuming WebService in asp.net or Create and call webservice in asp.net or how to create webservice and how to use webservice in asp.net

Suresh Dasari May 17, 2011
Introduction:

Here I will explain what webservice is, uses of webservice and how to create webservice and how to consume webservice in asp.net.

Description:
Today I am writing article to explain about webservices. First we will see what is webservice is and uses of webservice and then we will see how to use webservice in our applications.

What is Web Service?

Web Service is an application that is designed to interact directly with other applications over the internet. In simple sense, Web Services are means for interacting with objects over the Internet. The Web serivce consumers are able to invoke method calls on remote objects by using SOAP and HTTP over the Web. WebService is language independent and Web Services communicate by using standard web protocols and data formats, such as
  • HTTP
  • XML
  • SOAP
Advantages of Web Service

Web Service messages are formatted as XML, a standard way for communication between two incompatible system. And this message is sent via HTTP, so that they can reach to any machine on the internet without being blocked by firewall.

Examples for Web Service

Weather Reporting: You can use Weather Reporting web service to display weather information in your personal website.

Stock Quote: You can display latest update of Share market with Stock Quote on your web site.

News Headline: You can display latest news update by using News Headline Web Service in your website.

In summary you can any use any web service which is available to use. You can make your own web service and let others use it. Example you can make Free SMS Sending Service with footer with your advertisement, so whosoever use this service indirectly advertise your company... You can apply your ideas in N no. of ways to take advantage of it.

Frequently used word with web services

What is SOAP?

SOAP (simple object access protocol) is a remote function calls that invokes method and execute them on Remote machine and translate the object communication into XML format. In short, SOAP are way by which method calls are translate into XML format and sent via HTTP.

What is WSDL? 

WSDL stands for Web Service Description Language, a standard by which a web service can tell clients what messages it accepts and which results it will return.
WSDL contains every detail regarding using web service and Method and Properties provided by web service and URLs from which those methods can be accessed and Data Types used.

What is UDDI?

UDDI allows you to find web services by connecting to a directory.

What is Discovery or .Disco Files?

Discovery files are used to group common services together on a web server. Discovery files .Disco and .VsDisco are XML based files that contains link in the form of URLs to resources that provides discovery information for a web service. Disco File contains URL for the WSDL, URL for the documentation and URL to which SOAP messages should be sent.

Before start creating web service first create one table in your database and give name UserInformation in my code I am using same name and enter some dummy data for our testing purpose

Column Name
Data Type
Allow Nulls
UserId
Int(Set Identity=true)
No
UserName
Varchar(50)
Yes
FirstName
Varchar(50)
Yes
LastName
Varchar(50)
Yes
Location
Varchar(50)
Yes

Now we will see how to create new web service application in asp.net

Open visual studio ---> Select File ---> New ---> Web Site---> select ASP.NET Web Service


Now our new web service ready our webservice website like this



Now open your Service.cs file in web service website to write the code to get the user details from database

Before writing the WebMethod in Service.cs first add following namespaces


using System.Xml;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
After adding namespaces write the following method GetUserDetails in Service.cs page

[WebMethod]
public XmlElement GetUserDetails(string userName)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ToString());
con.Open();
SqlCommand cmd = new SqlCommand("select * from UserInformation where UserName like @userName+'%'", con);
cmd.Parameters.AddWithValue("@userName", userName);
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(cmd);
// Create an instance of DataSet.
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
// Return the DataSet as an XmlElement.
XmlDataDocument xmldata = new XmlDataDocument(ds);
XmlElement xmlElement = xmldata.DocumentElement;
return xmlElement;
}

Here we need to remember one point that is adding [WebMethod] before method definition because we need to access web method pulically otherwise it’s not possible to access method publically. If you observe above code I converted dataset to XmlElement t because sometimes we will get error like return type dataset invalid type it must be either an IListSource, IEnumerable, or IDataSource to avoid this error I converted dataset to XmlElement.

Here we need to set the database connection in web.config because here I am getting database connection from web.config


<connectionStrings>
<add name="dbconnection" connectionString="Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"/>
</connectionStrings>
Now run your web service it would be like this


Our web service is working fine now we need to know how we can use webservice in our application? Before to know about using web service in application first Deploy your webservice application in your local system if you want to know how to deploy application in your local system check this link deploy application in local system

How to Use Web service in web application?

By using this webservice we can get the user details based on username. For that first create one new web application

Open visual studio ---> Select File ---> New ---> Web Site---> select ASP.NET Web Site


After creation of new website right click on solution explorer and choose “Add web reference” that would be like this


After select Add Web reference option one window will open like this 



Now enter your locally deployed web service link and click Go button after that your web service will found and window will looks like this




Now click on Add Reference button web service will add successfully. Now open your Default.aspx page and design like this


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Getting Data from WebService</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
<b>Enter UserName:</b>
</td>
<td>
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
</td>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" />
</td>
</tr>
</table>
</div>
<div>
<asp:GridView ID="gvUserDetails" runat="server" EmptyDataText="No Record Found">
<RowStyle BackColor="#EFF3FB" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
</div>
</form>
</body>
</html>
Now in code behind add following namespaces

using System.Data;
using System.Xml;


After adding namespaces write the following code in code behind


protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindUserDetails("");
}
}
protected void BindUserDetails(string userName)
{
localhost.Service objUserDetails = new localhost.Service();
DataSet dsresult = new DataSet();
XmlElement exelement = objUserDetails.GetUserDetails(userName);
if(exelement!=null)
{
XmlNodeReader nodereader = new XmlNodeReader(exelement);
dsresult.ReadXml(nodereader, XmlReadMode.Auto);
gvUserDetails.DataSource = dsresult;
gvUserDetails.DataBind();
}
else
{
gvUserDetails.DataSource = null;
gvUserDetails.DataBind();   
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
BindUserDetails(txtUserName.Text);
}
Now run your application and check output
























Introduction to WCF - WCF tutorial | WCF Tutorial - Windows Communication Foundation | WCF Example | WCF Sample code in asp.net 3.5 | Basic WCF Tutorial for Beginners

Suresh Dasari Jun 26, 2011
Introduction:

Here I will explain what WCF (windows communication foundation) is, uses of windows communication foundation and how to create and use windows communication foundation in c#.

Description:
In previous articles explained clearly what webservice is and how to create and consume webservice using asp.net . In another post I explained clearly what windows service is and how to create windows service and sample of windows service using c#. Now in this article I will explain about windows communication foundation. First we will see what a WCF (window communication foundation) is and uses of WCF (windows communication foundation) after that we will see how to create and use WCF in c#.net.
What is WCF (windows communication foundation) Service?

Windows Communication Foundation (Code named Indigo) is a programming platform and runtime system for building, configuring and deploying network-distributed services. It is the latest service oriented technology; Interoperability is the fundamental characteristics of WCF. It is unified programming model provided in .Net Framework 3.0. WCF is a combined feature of Web Service, Remoting, MSMQ and COM+. WCF provides a common platform for all .NET communication.
Advantages of WCF
     1)    WCF is interoperable with other services when compared to .Net Remoting where the client and service have to be .Net.

     2)    WCF services provide better reliability and security in compared to ASMX web services.

     3)    In WCF, there is no need to make much change in code for implementing the security model and changing the binding. Small changes in the configuration will make your requirements.

     4)    WCF has integrated logging mechanism, changing the configuration file settings will provide this functionality. In other technology developer has to write the code.

Difference between WCF and Web service

Web service is a part of WCF. WCF offers much more flexibility and portability to develop a service when comparing to web service. Still we are having more advantages over Web service; following table provides detailed difference between them.

Features
Web Service
WCF
Hosting
It can be hosted in IIS
It can be hosted in IIS, windows activation service, Self-hosting, Windows service
Programming
[WebService] attribute has to be added to the class
[ServiceContract] attribute has to be added to the class
Model
[WebMethod] attribute represents the method exposed to client
[OperationContract] attribute represents the method exposed to client
Operation
One-way, Request- Response are the different operations supported in web service
One-Way, Request-Response, Duplex are different type of operations supported in WCF
XML
System.Xml.serialization name space is used for serialization
System.Runtime.Serialization namespace is used for serialization
Encoding
XML 1.0, MTOM(Message Transmission Optimization Mechanism), DIME, Custom
XML 1.0, MTOM, Binary, Custom
Transports
Can be accessed through HTTP, TCP, Custom
Can be accessed through HTTP, TCP, Named pipes, MSMQ,P2P, Custom
Protocols
Security
Security, Reliable messaging, Transactions

A WCF Service is composed of three components parts viz,

1) Service Class - A WCF service class implements some service as a set of methods.

2) Host Environment - A Host environment can be a Console application or a Windows Service or a Windows Forms application or IIS as in case of the normal asmx web service in .NET.

3) Endpoints - All communications with the WCF service will happen via the endpoints. The endpoint is composed of 3 parts (collectively called as ABC's of endpoint) as defines below:

Address: The endpoints specify an Address that defines where the endpoint is hosted. It’s basically url.

Ex:http://localhost/WCFServiceSample/Service.svc

Binding: The endpoints also define a binding that specifies how a client will communicate with the service and the address where the endpoint is hosted. Various components of the WCF are depicted in the figure below.
  • "A" stands for Address: Where is the service?
  • "B" stands for Binding: How can we talk to the service?
  • "C" stands for Contract: What can the service do for us?
Different bindings supported by WCF

Binding
Description
BasicHttpBinding
Basic Web service communication. No security by default
WSHttpBinding
Web services with WS-* support. Supports transactions
WSDualHttpBinding
Web services with duplex contract and transaction support
WSFederationHttpBinding
Web services with federated security. Supports transactions
MsmqIntegrationBinding
Communication directly with MSMQ applications. Supports transactions
NetMsmqBinding
Communication between WCF applications by using queuing. Supports transactions
NetNamedPipeBinding
Communication between WCF applications on same computer. Supports duplex contracts and transactions
NetPeerTcpBinding
Communication between computers across peer-to-peer services. Supports duplex contracts
NetTcpBinding
Communication between WCF applications across computers. Supports duplex contracts and transactions
BasicHttpBinding
Basic Web service communication. No security by default
WSHttpBinding
Web services with WS-* support. Supports transactions

Contract: The endpoints specify a Contract that defines which methods of the Service class will be accessible via the endpoint; each endpoint may expose a different set of methods.
Different contracts in WCF

Service Contract

Service contracts describe the operation that service can provide. For Eg, a Service provide to know the temperature of the city based on the zip code, this service is called as Service contract. It will be created using Service and Operational Contract attribute.

Data Contract
Data contract describes the custom data type which is exposed to the client. This defines the data types, which are passed to and from service. Data types like int, string are identified by the client because it is already mention in XML schema definition language document, but custom created class or data types cannot be identified by the client e.g. Employee data type. By using DataContract we can make client to be aware of Employee data type that are returning or passing parameter to the method.

Message Contract

Default SOAP message format is provided by the WCF runtime for communication between Client and service. If it is not meeting your requirements then we can create our own message format. This can be achieved by using Message Contract attribute.

Fault Contract

Suppose the service I consumed is not working in the client application. I want to know the real cause of the problem. How I can know the error? For this we are having Fault Contract. Fault Contract provides documented view for error occurred in the service to client. This helps us to easy identity, what error has occurred.

Overall Endpoints will be mentioned in the web.config file for WCF service like this

<system.serviceModel>
<services>
<service name="Service" behaviorConfiguration="ServiceBehavior">
<!-- Service Endpoints -->
<endpoint address="http://localhost:8090/MyFirstWcfService/SampleService.svc" binding="wsHttpBinding" contract="IService">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>


Creating simple application using WCF

First open Visual Studio and click file --> Select New --> Website Under that select WCF Service and give name for WCF Service and click OK 



Once you created application you will get default class files including Service.csand IService.cs



HereIService.cs is an interface it does contain Service contracts and Data Contracts and Service.cs is a normal class inherited by IServicewhere you can all the methods and other stuff.

Now open IService.cs write the following code

[ServiceContract]
public interface IService
{
[OperationContract]
string SampleMethod(string Name);
}

After that open Service.cs class file and write the following code 

public class Service : IService
{
public string SampleMethod(string Name)
{
return "First WCF Sample Program " + Name;
}
}


Here we are using basicHttpBinding for that our web.config file system.serviceModel code should be like this and I hope no need to write any code because this code already exists in your web.config file in system.serviceModel

<system.serviceModel>
<services>
<service name="Service" behaviorConfiguration="ServiceBehavior">
<!-- Service Endpoints -->
<endpoint address="" binding="wsHttpBinding" contract="IService">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>

Our WCF service ready to use with basicHttpBinding. Now we can call this WCF Service method console applications

After completion of WCF service creation publish or deploy your WCF Service in your system. If you don’t’ have idea on deploy check this post publish or deploy website

After completion of deploy webservice now we can see how to use WCF Service in our console application

Calling WCF Service using Console Application

To call WCF service we have many ways like using console app, windows app and web app but here I am going for console application.

Create new console app from visual studio select project type as console application gives some name as you like.



After Creation Console application now we need to add WCF reference to our console application for that right click on your windows application and select Add Service Reference


Now one wizard will open in that give your WCF service link and click Go after add your service click OK button.



After completion of adding WCF Service write the following code in Program.csclass file Main method

static void Main(string[] args)
{
ServiceReference1.ServiceClient objService = new ServiceClient();
Console.WriteLine("Please Enter your Name");
string Message = objService.SampleMethod(Console.ReadLine());
Console.WriteLine(Message);
Console.ReadLine();
}
After that open your app.config file and check your endpoint connection for WCF Service reference that should be like this

<endpoint address=" http://localhost/WCFServiceSample/Service.svc"
binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IService"
contract="ServiceReference1.IService" name="WSHttpBinding_IService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
Now everything is ready run your application that output should be like this



C# - Difference between Convert.tostring and .tostring() method Example

Suresh Dasari Oct 25, 2012
Introduction:

In this article I will explain differences between .tostring() and Convert.tostring() in asp.net.

Description:

In previous post I explained difference between web application and website, difference between datareader, dataadapter and dataset, difference between tinyint,smallint,int,bigint and many articles relating to asp.net, SQL Server. Now I will explain differences between .tostring() and Convert.tostring() in asp.net.

The basic difference between them is “Convert.ToString(variable)” handles NULL values even if variable value become null but “variable.ToString()” will not handle NULL values it will throw a NULL reference exception error. So as a good coding practice using “convert” is always safe.

Example

//Returns a null reference exception for str.
string str;
object i = null;
str = i.ToString();

//Returns an empty string for str and does not throw an exception. If you dont
string str;
object i = null;
str = Convert.ToString(i);
I hope it helps.




Asp.net Difference between Website and Web Application in C#, VB.NET

Suresh Dasari Oct 13, 2012
Introduction:

Here I will explain the differences between website and web application in asp.net.

Description:

In previous posts I explained Difference between appsettings and connectionstrings, Difference between datareader,dataset and dataadapter and many articles relating Interview Questions in asp.net. Now I will explain the differences between website and web application in asp.net.

Generally whenever we are trying to create new web project in visual studio we will fund two options ASP.NET Web Application and WebSite. What is the difference between these two which one we need to select to create project in asp.net?

It's choice of the people can go for web application or website we cannot say that which one is better because both is having advantages and disadvantages. Check below details for webaplication and website

Web Application

1. If we create any class files / functions those will be placed anywhere in the applications folder structure and it is precomplied into one single DLL.

2. In web application we have chance of select only one programming language during creation of project either C# or VB.NET.

3. Whenever we create Web Application those will automatically create project files (.csproj or .vbproj).

4. We need to pre-compile the site before deployment.

5. If we want to deploy web application project we need to deploy only .aspx pages there is no need to deploy code behind files because the pre-compiled dll will contains these details.

6. If we make small change in one page we need to re-compile the entire sites.

WebSite

1. If we create any class files/functions those will be placed in ASP.NET folder (App_Code folder) and it's compiled into several DLLs (assemblies) at runtime.

2. In website we can create pages in multi programming languages that means we can create one page code in C# and another page code in vb.net.

3. Web Sites won’t create any .csproj/.vbproj files in project

4. No need to recompile the site before deployment.

5. We need to deploy both .aspx file and code behind file.

6. If we make any code changes those files only will upload there is no need to re-compile entire site  




Asp.net Difference between DataReader and DataSet and DataAdapter in C#, VB.NET

Suresh Dasari Oct 12, 2012
Introduction:

In this article I will explain difference between datareader, dataset and dataadapter in asp.net.

Description:

In previous posts I explained Interview Questions in asp.net,C#,SQL, difference between Executereader, ExecuteNonQuery and ExecuteScalar, difference between Len and DataLength functions, difference between int,tinyint and bigint and differences between char, varchar and nvarchar in SQL Server. Now I will explain difference between datareader, dataset and dataadapter in asp.net

DataReader

DataReader is used to read the data from database and it is a read and forward only connection oriented architecture during fetch the data from database. DataReader is used to iterate through resultset that came from server and it will read one record at a time because of that memory consumption will be less and it will fetch the data very fast when compared with dataset. Generally we will use ExecuteReaderobject to bind data to datareader. (Read More)

Sample code of datareader will be like this

C# Code


// This method is used to bind gridview from database
protected void BindGridview()
{
using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select UserName,LastName,Location FROM UserInformation", con);
SqlDataReader dr = cmd.ExecuteReader();
gvUserInfo.DataSource = dr;
gvUserInfo.DataBind();
con.Close();
}
}
VB.NET Code


' This method is used to bind gridview from database
Protected Sub BindGridview()
Using con As New SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")
con.Open()
Dim cmd As New SqlCommand("Select UserName,LastName,Location FROM UserInformation", con)
Dim dr As SqlDataReader = cmd.ExecuteReader()
gvUserInfo.DataSource = dr
gvUserInfo.DataBind()
con.Close()
End Using
End Sub
DataSet

DataSet is a disconnected orient architecture that means there is no need of active connections during work with datasets and it is a collection of DataTables and relations between tables. It is used to hold multiple tables with data. You can select data form tables, create views based on table and ask child rows over relations. Also DataSet provides you with rich features like saving data as XML and loading XML data.

C# Code


// This method is used to bind gridview from database
protected void BindGridview()
{
SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB");
con.Open();
SqlCommand cmd = new SqlCommand("select UserName,LastName,Location from UserInformation", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvUserInfo.DataSource = ds;
gvUserInfo.DataBind();
}
VB.NET Code


' This method is used to bind gridview from database
Protected Sub BindGridview()
Dim con As New SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")
con.Open()
Dim cmd As New SqlCommand("select UserName,LastName,Location from UserInformation", con)
Dim da As New SqlDataAdapter(cmd)
Dim ds As New DataSet()
da.Fill(ds)
gvUserInfo.DataSource = ds
gvUserInfo.DataBind()
End Sub
DataAdapter

DataAdapter will acts as a Bridge between DataSet and database. This dataadapter object is used to read the data from database and bind that data to dataset. Dataadapter is a disconnected oriented architecture. Check below sample code to see how to use DataAdapter in code

C# Code


// This method is used to bind gridview from database
protected void BindGridview()
{
SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB");
con.Open();
SqlCommand cmd = new SqlCommand("select UserName,LastName,Location from UserInformation", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvUserInfo.DataSource = ds;
gvUserInfo.DataBind();
}
VB.NET Code


' This method is used to bind gridview from database
Protected Sub BindGridview()
Dim con As New SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")
con.Open()
Dim cmd As New SqlCommand("select UserName,LastName,Location from UserInformation", con)
Dim da As New SqlDataAdapter(cmd)
Dim ds As New DataSet()
da.Fill(ds)
gvUserInfo.DataSource = ds
gvUserInfo.DataBind()
End Sub




Asp.net Difference between appSettings and Connection Strings in web.config

Suresh Dasari Oct 10, 2012
Introduction:

In this article I will explain the differences between appsettings and connection strings in web.config using asp.net.

Description:

In previous posts I explained Read or Write appsettings from web.config, Read/Write connection strings in web.config. Now I will explain differences between appsettings and connection strings in web.config using asp.net.

In many cases, we need to use some data string throughout the application simple example for this database connection string. Instead of writing the same connection string wherever required, it is easy to maintain if we store it in one place that is web.config file.

In web.config file we can store the connection strings in two ways those are appSettings and connectionStrings

AppSettings in web.config

The AppSettings section in web.config is used to store connection strings, server names, file paths, and other miscellaneous settings needed by an application. (Read More)

Connection String in web.config

The connection string in web.config is a collection of database connection strings only.

Actually in previous versions of ASP.NET all connection string values are storing in appsettings only. In ASP.NET 2.0 + version new features has introduced such as Session, Membership, Personalization, and Role Manager these will depend on connection strings and stored in the connectionStrings element only. (Read More)

Difference

The main difference is in appsettings section we can store any data string values including database connection strings also but in connectionStringssection only database connection strings can store those are our application connection strings and new features (Membership, Personalization and Role Manager) connection strings only.

Instead of this there is no much difference between appsettings and connectionStrings.



















Read or Write connection strings in web.config file using asp.net

Suresh Dasari Nov 27, 2011
Introduction:

In this article I will explain how to read or write connection strings in web.config file using asp.net.

Description:

In Previous article I explained clearly about Encrypt or Decrypt connection strings in web.config file using asp.net. Now I will explain how to write connection strings in web.config file and how to read connection strings from web.config file using asp.net. 

I have one web application that contains many pages and each page contains relationship with database connection to get data from database and display it on page because of that I need to write database connections for each page to interact with database. Now the server name or credentials of database server has changed in that situation it will create problem because we need to modify the database connections of each page using asp.net. 

To avoid this situation it would be better if we place connection string in one place and reuse it in every page wherever we need to connect to SQL Server. Web.config is the best place to store the connection strings in asp.net and it would be safer place to store the connection strings instead of writing connection strings in every web page.

Now we want to add connection string in web.config file for that first create new website using visual studio after that create new website open web.config file and search for “connectionStrings” and add new item in connectionStrings section

After open web.config file in application and add sample db connection in connectionStringssection like this 

<connectionStrings>
<add name="yourconnectinstringName" connectionString="Data Source= DatabaseServerName; Integrated Security=true;Initial Catalog= YourDatabaseName; uid=YourUserName; Password=yourpassword; " providerName="System.Data.SqlClient"/>
</connectionStrings >
Example of declaring connectionStrings in web.config file like this

<connectionStrings>
<add name="dbconnection" connectionString="Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB" providerName="System.Data.SqlClient"/>
</connectionStrings >
Here to access my database server there is no need of username and password for that reason I didn’t enter username and password in connection string.

After add dbconnection in connectionString we need to write the some code in our codebehind file to get connection string from web.config file for that add following namespace in codebehind file and write the following code

using System.Configuration;
 This namespace is used to get configuration section details from web.config file.

After add namespaces write the following code in code behind

C# code

using System;
using System.Data.SqlClient;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{   
//Get connection string from web.config file
string strcon = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
//create new sqlconnection and connection to database by using connection string from web.config file
SqlConnection con = new SqlConnection(strcon);
con.Open();
}
}
VB.NET

Imports System.Data.SqlClient
Imports System.Configuration
Partial Public Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
'Get connection string from web.config file
Dim strcon As String = ConfigurationManager.ConnectionStrings("dbconnection").ConnectionString
'create new sqlconnection and connection to database by using connection string from web.config file
Dim con As New SqlConnection(strcon)
con.Open()
End Sub
End Class
Here we stored our database connection string in web.config file it was not secured if we want to encrypt the connection string in web.config file check this post encrypt or decrypt connection string in web.config file.

Read or Write connection strings in web.config file using asp.net

Suresh Dasari Nov 27, 2011
Introduction:

In this article I will explain how to read or write connection strings in web.config file using asp.net.

Description:

In Previous article I explained clearly about Encrypt or Decrypt connection strings in web.config file using asp.net. Now I will explain how to write connection strings in web.config file and how to read connection strings from web.config file using asp.net. 

I have one web application that contains many pages and each page contains relationship with database connection to get data from database and display it on page because of that I need to write database connections for each page to interact with database. Now the server name or credentials of database server has changed in that situation it will create problem because we need to modify the database connections of each page using asp.net. 

To avoid this situation it would be better if we place connection string in one place and reuse it in every page wherever we need to connect to SQL Server. Web.config is the best place to store the connection strings in asp.net and it would be safer place to store the connection strings instead of writing connection strings in every web page.

Now we want to add connection string in web.config file for that first create new website using visual studio after that create new website open web.config file and search for “connectionStrings” and add new item in connectionStrings section

After open web.config file in application and add sample db connection in connectionStringssection like this 

<connectionStrings>
<add name="yourconnectinstringName" connectionString="Data Source= DatabaseServerName; Integrated Security=true;Initial Catalog= YourDatabaseName; uid=YourUserName; Password=yourpassword; " providerName="System.Data.SqlClient"/>
</connectionStrings >
Example of declaring connectionStrings in web.config file like this

<connectionStrings>
<add name="dbconnection" connectionString="Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB" providerName="System.Data.SqlClient"/>
</connectionStrings >
Here to access my database server there is no need of username and password for that reason I didn’t enter username and password in connection string.

After add dbconnection in connectionString we need to write the some code in our codebehind file to get connection string from web.config file for that add following namespace in codebehind file and write the following code

using System.Configuration;
 This namespace is used to get configuration section details from web.config file.

After add namespaces write the following code in code behind

C# code

using System;
using System.Data.SqlClient;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{   
//Get connection string from web.config file
string strcon = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
//create new sqlconnection and connection to database by using connection string from web.config file
SqlConnection con = new SqlConnection(strcon);
con.Open();
}
}
VB.NET

Imports System.Data.SqlClient
Imports System.Configuration
Partial Public Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
'Get connection string from web.config file
Dim strcon As String = ConfigurationManager.ConnectionStrings("dbconnection").ConnectionString
'create new sqlconnection and connection to database by using connection string from web.config file
Dim con As New SqlConnection(strcon)
con.Open()
End Sub
End Class
Here we stored our database connection string in web.config file it was not secured if we want to encrypt the connection string in web.config file check this post encrypt or decrypt connection string in web.config file.

SQL Server - Differences between Functions and Stored Procedures

Suresh Dasari Oct 7, 2012
Introduction:

Here I will explain the difference between stored procedure and function in SQL Server.

Description:

In previous posts I explained difference between Left Join and Left Outer Join, Difference between Len and DataLength and many articles relating to SQL Server. Now I will explain the difference between stored procedure and function in SQL Server.

Stored Procedre:

Stored Procedure is a group of sql statements that has been created once and stored in server database. It’s pre-compile objects which are compiled for first time and its compiled format is saved which executes (compiled code) whenever it is called. Stored procedures will accept input parameters so that single stored procedure can be used over network by multiple clients using different input data. Stored procedures will reduce network traffic and increase the performance. (Read more Here)

Function:

Function is not pre-compiled object it will execute every time whenever it was called.

Difference between Stored Procedure and Function

1) Procedure can return zero or n values whereas function can return one value which is mandatory (Read more Here).

2) Procedures can have input, output parameters for it whereas functions can have only input parameters.

3) Procedure allows select as well as DML(INSERT/UPDATE/DELETE) statements in it whereas function allows only select statement in it.

4) Functions can be called from procedure whereas procedures cannot be called from function.

5) Exception can be handled by try-catch block in a procedure whereas try-catch block cannot be used in a function.

6) We can go for transaction management in procedure whereas we can't go in function.

7) Procedures cannot be utilized in a select statement whereas function can be embedded in a select statement.

If you want more interview questions check this article Interview Questions Series


what is stored procedure in Sql server | what are the advantages of using stored procedures in sql server

Suresh Dasari Jul 28, 2011
Introduction:

Here I will explain about what is stored procedure is and advantages and disadvantages of stored procedures in sql server

Description:

A stored procedure is a group of sql statements that has been created and stored in the database. Stored procedure will accept input parameters so that a single procedure can be used over the network by several clients using different input data. Stored procedure will reduce network traffic and increase the performance. If we modify stored procedure all the clients will get the updated stored procedure

Sample of creating Stored Procedure

USE AdventureWorks2008R2;
GO
CREATE PROCEDURE dbo.sp_who
AS
    SELECT FirstName, LastName FROM Person.Person;
GO
EXEC sp_who;
EXEC dbo.sp_who;
GO
DROP PROCEDURE dbo.sp_who;
GO

Advantages of using stored procedures

a)    a) Stored procedure allows modular programming. 

You can create the procedure once, store it in the database, and call it any number of times in your program. 

b)    b) Stored Procedure allows faster execution. 

If the operation requires a large amount of SQL code is performed repetitively, stored procedures can be faster. They are parsed and optimized when they are first executed, and a compiled version of the stored procedure remains in memory cache for later use. This means the stored procedure does not need to be reparsed and reoptimized with each use resulting in much faster execution times. 

c)     c) Stored Procedure can reduce network traffic. 

An operation requiring hundreds of lines of Transact-SQL code can be performed through a single statement that executes the code in a procedure, rather than by sending hundreds of lines of code over the network.

d)    d) Stored procedures provide better security to your data

Users can be granted permission to execute a stored procedure even if they do not have permission to execute the procedure's statements directly.

In SQL we are having different types of stored procedures are there

a)    System Stored Procedures
b)    User Defined Stored procedures
c)    Extended Stored Procedures

System Stored Procedures:

System stored procedures are stored in the master database and these are starts with a sp_ prefix. These procedures can be used to perform variety of tasks to support sql server functions for external application calls in the system tables 

Ex: sp_helptext [StoredProcedure_Name]

User Defined Stored Procedures:

User Defined stored procedures are usually stored in a user database and are typically designed to complete the tasks in the user database. While coding these procedures don’t use sp_ prefix because if we use the sp_ prefix first it will check master database then it comes to user defined database

Extended Stored Procedures:

Extended stored procedures are the procedures that call functions from DLL files. Now a day’s extended stored procedures are depreciated for that reason it would be better to avoid using of Extended Stored procedures. 


SQL Server- Difference Between Full Outer Join and Cross Join

Suresh Dasari Sep 22, 2012
Introduction:

Here I will explain what is the difference between cross join and full outer join in SQL Server.

Description:

In previous posts I explained difference between Left Join and Left Outer Join, difference between ExecuteNonQuery, ExecuteReader, ExecuteScalar, Difference between Len and DataLength and many articles relating to SQL Server. Now I will explain the difference between cross join and full outer join in SQL Server.

Cross Join:

A cross join that produces Cartesian product of the tables that involved in the join. The size of a Cartesian product is the number of the rows in first table multiplied by the number of rows in the second table.

Full Outer Join:

Full Outer Join displays all the matching and non matching rows of both the tables.

If you want to know in-depth about Joins in SQL Server please check below link in that post I explained each join clearly with examples

SQL Server- Difference Between Left Outer Join and Right Outer Join

Suresh Dasari Sep 22, 2012
Introduction:

Here I will explain differences between left outer join and right outer join in SQL Server.

Description:

In previous posts I explained difference between ExecuteNonQuery, ExecuteReader, ExecuteScalar, Difference between Len and DataLength and many articles relating to SQL Server. Now I will explain the difference between left outer join and right outer join in SQL Server.

Left Join or Left Outer Join:

The left outer join displays all the rows from the first table and matched rows from the second table. Here one more thing we need to remember that is Left Join is same as Left Outer Join only there is no difference between Left Join and Left Outer Join in SQL Server.

Right Join or Right Outer Join:

The right outer join displays all the rows from the second table and matched rows from the first table. Here one more thing is Right Join is same as Right Outer Join only there is no difference between right Join and right outer Join in SQL Server.

If you want to know in-depth about Joins in SQL Server please check below link in that post I explained each join clearly with examples


Differences between ExecuteReader, ExecuteNonQuery AND ExecuteScalar

Suresh Dasari Sep 19, 2012
Introduction:

In this article I will explain differences between executereader, executenonquery and executescalar in asp.net.

Description:

In previous posts I explained difference between Len and DataLength functions, difference between int,tinyint and bigint and differences between char, varchar and nvarchar in SQL Server. Now I will explain difference between executereader, executenonquery and executescalar in asp.net

ExecuteNonQuery

ExecuteNonQuery method will return number of rows effected with INSERT, DELETE or UPDATE operations. This ExecuteNonQuery method will be used only for insert, update and delete, Create, and SET statements. (Read More)

ExecuteScalar

Execute Scalar will return single row single column value i.e. single value, on execution of SQL Query or Stored procedure using command object. It’s very fast to retrieve single values from database. (Read More)

ExecuteReader

Execute Reader will be used to return the set of rows, on execution of SQL Query or Stored procedure using command object. This one is forward only retrieval of records and it is used to read the table values from first to last. (Read More)

Difference Between LEN and DATALENGTH Functions in SQL Server

Suresh Dasari Sep 19, 2012
Introduction:

In this article I will explain differences between Len() and DataLength() functions in sql server.

Description:

In previous post I explained differences between char, varchar and nvarchar, difference between tinyint,smallint,int,bigint and many articles relating to SQL Server. Now I will explain differences between Len() and DataLength() functions in SQL Server.

Len() function

This Len() function will return number of characters in the string expression excluding the trailing blanks. This mean it will right trim the blank values and give you the count of characters.

DataLength() function

This DataLength() function will return number of bytes to represent any expression. This mean it will give you a storage space required for the characters.

Check below examples for Len() and DataLength() functions

Example1:

In this example I am taking string value without spaces


DECLARE @str VARCHAR(50)
SET @str='Suresh'
SELECT LEN(@str) AS LenCount
SELECT DATALENGTH(@str) AS DataLengthCount
OutPut

Example2:

In this example I am taking string value with spaces


DECLARE @str VARCHAR(50)
SET @str='Suresh   '
SELECT LEN(@str) AS LenCount
SELECT DATALENGTH(@str) AS DataLengthCount
OutPut



ExecuteNonQuery Example in Asp.Net Using C# and VB.NET

Suresh Dasari Sep 20, 2012
Introduction:

In this article I will explain executenonquery example in asp.net using C#.net and VB.NET.

Description:

In previous post I explained differences between ExecuteNonQuery, ExecuteReader and ExecuteScalar in asp.net. Now I will explain ExecuteNonQuery concept with one example in asp.net using C#.net, VB.NET.

ExecuteNonQuery

ExecuteNonQuery method will return number of rows effected with INSERT, DELETE or UPDATE operations. This ExecuteNonQuery method will be used only for insert, update and delete, Create, and SET statements.

Before implement this example first design one table UserInformation in your database as shown below

Column Name
Data Type
Allow Nulls
UserName
varchar(50)
Yes
LastName
varchar(50)
Yes
Location
Varchar(50)
Yes
Once table designed in database write the following code in your aspx page


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Example of ExecuteNonQuery in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" /><br />
<b>Number of Rows Effected: </b><asp:Label ID="lblDetails" runat="server" />
</div>
</form>
</body>
</html>
Now add the following namespaces in code behind

C# Code


using System;
using System.Data.SqlClient;
After add namespaces write the following code in code behind

protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnSubmit_Click(object sender, EventArgs e)
{
using (SqlConnection con=new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"))
{
con.Open();
SqlCommand cmd = new SqlCommand("insert into UserInformation(UserName,FirstName,LastName,Location) values(@Name,@FName,@LName,@Location)", con);
cmd.Parameters.AddWithValue("@Name", "Suresh Dasari");
cmd.Parameters.AddWithValue("@FName", "Suresh");
cmd.Parameters.AddWithValue("@LName", "D");
cmd.Parameters.AddWithValue("@Location","Chennai");
int result= cmd.ExecuteNonQuery();
if(result>=1)
{
lblDetails.Text =  result.ToString();
}
else
{
lblDetails.Text = "0" ;
}
con.Close();
}
}
VB.NET Code


Imports System.Data.SqlClient
Partial Class VBCode
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

End
Sub
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs)
Using con As New SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")
con.Open()
Dim cmd As New SqlCommand("insert into UserInformation(UserName,FirstName,LastName,Location) values(@Name,@FName,@LName,@Location)", con)
cmd.Parameters.AddWithValue("@Name", "Suresh Dasari")
cmd.Parameters.AddWithValue("@FName", "Suresh")
cmd.Parameters.AddWithValue("@LName", "D")
cmd.Parameters.AddWithValue("@Location", "Chennai")
Dim result As Integer = cmd.ExecuteNonQuery()
If result >= 1 Then
lblDetails.Text = result.ToString()
Else
lblDetails.Text = "0"
End If
con.Close()
End Using
End Sub
End Class
Demo

If you observe above output whenever we click on button one new record inserting into table UserInformation and returning number records inserted.




ExecuteScalar Example in Asp.Net Using C# and VB.NET

Suresh Dasari Sep 20, 2012
Introduction:

In this article I will explain executescalar example in asp.net using C#.net and VB.NET.

Description:

In previous post I explained ExecuteNonQuery Example and differences between ExecuteNonQuery, ExecuteReader and ExecuteScalar in asp.net. Now I will explain ExecuteScalar concept with one example in asp.net using C#.net, VB.NET.

ExecuteScalar

Execute Scalar will return first row first column value i.e. it will return single value and ignore other values on execution of SQL Query or Stored procedure using command object. It’s very fast to retrieve single values from database.

Before implement this example first design one table UserInformation in your database as shown below

Column Name
Data Type
Allow Nulls
UserName
varchar(50)
Yes
LastName
varchar(50)
Yes
Location
Varchar(50)
Yes
Once table designed in database enter some dummy data to test after that write the following code in your aspx page


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Example of ExecuteNonQuery in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" /><br />
<b>First Row First Column Value: </b><asp:Label ID="lblDetails" runat="server" />
</div>
</form>
</body>
</html>
Now add the following namespaces in code behind

C# Code


using System;
using System.Data.SqlClient;
After add namespaces write the following code in code behind

protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnSubmit_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select UserName,LastName,Location FROM UserInformation", con);
string result = (string)cmd.ExecuteScalar();
if (!string.IsNullOrEmpty(result))
{
lblDetails.Text = result;
}
else
{
lblDetails.Text =  "No value Selected" ;
}
con.Close();
}
}
VB.NET Code


Imports System.Data.SqlClient
Partial Class ExecuteScalar
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

End Sub
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs)
Using con As New SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")
con.Open()
Dim cmd As New SqlCommand("Select UserName,LastName,Location FROM UserInformation", con)
Dim result As String = DirectCast(cmd.ExecuteScalar(), String)
If Not String.IsNullOrEmpty(result) Then
lblDetails.Text = result
Else
lblDetails.Text =  "No value Selected"
End If
con.Close()
End Using
End Sub
End Class
Demo

If you observe above code I written select query like getting all the data from UserInfromationtable but whenever we click on button we are getting only one value (First Row First Column value) and ignoring other row and column values.


ExecuteReader Example in Asp.Net using C#,VB.NET

Suresh Dasari Sep 21, 2012
Introduction:
 
In this article I will explain ExecuteReader example in asp.net using C#.net and VB.NET. 

Description:

In previous post I explained ExecuteScalar Example, ExecuteNonQuery Example and differences between ExecuteNonQuery, ExecuteReader and ExecuteScalar in asp.net. Now I will explain ExecuteReader concept with one example in asp.net using C#.net, VB.NET. 

ExecuteReader

Execute Reader will be used to return the set of rows, on execution of SQL Query or Stored procedure using command object. This one is forward only retrieval of records and it is used to read the table values from first to last.

Before implement this example first design one table UserInformation in your database as shown below

Column Name
Data Type
Allow Nulls
UserName
varchar(50)
Yes
LastName
varchar(50)
Yes
Location
Varchar(50)
Yes
Once table designed in database enter some dummy data to test after that write the following code in your aspx page 


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Example of ExecuteReader in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<b>Bind Gridview with ExecuteReader command object Data</b><br /><br />
<asp:GridView ID="gvUserInfo" runat="server">
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White"/>
</asp:GridView>
</div>
</form>
</body>
</html>
Now add the following namespaces in code behind

C# Code


using System;
using System.Data.SqlClient;
using System.Data;
After add namespaces write the following code in code behind

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridview();
}
}

// This method is used to bind gridview from database
protected void BindGridview()
{
using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select UserName,LastName,Location FROM UserInformation", con);
SqlDataReader dr = cmd.ExecuteReader();
gvUserInfo.DataSource = dr;
gvUserInfo.DataBind();
con.Close();
}
}
VB.NET Code

Imports System.Data.SqlClient
Imports System.Data

Partial Class VBCode
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindGridview()
End If
End Sub

' This method is used to bind gridview from database
Protected Sub BindGridview()
Using con As New SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")
con.Open()
Dim cmd As New SqlCommand("Select UserName,LastName,Location FROM UserInformation", con)
Dim dr As SqlDataReader = cmd.ExecuteReader()
gvUserInfo.DataSource = dr
gvUserInfo.DataBind()
con.Close()
End Using
End Sub
End Class
Demo

If you observe above code I written select query like getting all the data from UserInfromation table but whenever we click on button we are getting only one value (First Row First Column value) and ignoring other row and column values.



Bit DataType

This datatype represents a single bit that can be 0 or 1.

tinyint DataType

This datatype represents a single byte which is used to store values from 0 to 255 (MinVal: 0, MaxVal: 255). Its storage size is 1 byte.

smallint DataType

This datatype represents a signed 16-bit integer which is used to store values from -2^15 (-32,768) through 2^15 - 1 (32,767) and its storage size is 2 bytes.

int DataType

This datatype represents a signed 32-bit integer which is used to store values from -2^31(-2,147,483,648) to 2 ^31-1(2,147,483,647). Its storage size is 4 bytes.

Bigint DataType

This datatype represents a signed 64-bit integer which is used to store values from -2^63 (-9223372036854775808) through 2^63-1 (9223372036854775807). Its storage size is 8 bytes.














Difference between char varchar and nvarchar in sql server

Suresh Dasari Jul 22, 2012
Introduction:

In this article I will explain what is the difference between char, varchar and nvarchar in SQL Server.

Description:

In previous post I explained many articles relating to SQL Server. Now I will explain the differences between char, varchar and nvarchar in SQL Server. Actually one of blog reader has asked me question regarding differences between varchar and nvarchar at that time I decided it’s better to write article on this topic.

Char DataType

Char datatype which is used to store fixed length of characters. Suppose if we declared char(50) it will allocates memory for 50 characters. Once we declare char(50) and insert only 10 characters of word then only 10 characters of memory will be used and other 40 characters of memory will be wasted.

varchar DataType

Varchar means variable characters and it is used to store non-unicode characters. It will allocate the memory based on number characters inserted. Suppose if we declared varchar(50) it will allocates memory of 0 characters at the time of declaration. Once we declare varchar(50) and insert only 10 characters of word it will allocate memory for only 10 characters.

nvarchar DataType

nvarchar datatype same as varchar datatype but only difference nvarchar is used to store Unicode characters and it allows you to store multiple languages in database. nvarchar datatype will take twice as much space to store extended set of characters as required by other languages.

So if we are not using other languages then it’s better to use varchardatatype instead of nvarchar








what are the sealed classes in c# | uses of sealed keyword in c# |Sealed classes example in c# | Object-Oriented Programming: Sealed Classes

Suresh Dasari Nov 6, 2011
Introduction

Here I will explain what are the sealed classes in c# and uses of sealed classes in c#.

Description:

In previous article I explained clearly about OOPS concepts now I will explain what is the use of sealed classes in c#. Generally if we create classes we can inherit the properties of that created class in any class without having any restrictions. In some situation we will get requirement like we don’t want to give permission for the users to derive the classes from it or don’t allow users to inherit the properties from particular class in that situations what we can do? 
For that purpose we have keyword called “Sealed” in OOPS. When we defined class with keyword “Sealed” then we don’t have a chance to derive that particular class and we don’t have permission to inherit the properties from that particular class.

Example to declare class as sealed 

sealed class Test
{
public int Number;
public string Name;
}
If the class declared with an access modifier, the Sealed keyword can appear after or before the public keyword. 

Example

Public sealed class Test
{
public int Number;
public string Name;
}

Here we can declare a class that is derived from another class can also be sealed. Check below example

Public sealed class Test
{
public int Number;
public string Name;
}

Public sealed class child1:Test
{
public string Name;
}









Example to use Sealed Keyword First create console application in C# and write the following code in Program.cs file and test it once.
  
using System;

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Irregular tri = new Irregular(42.73, 35.05);
tri.Describe("Irregular");
}
}
public abstract class Triangle
{
private double bs;
private double hgt;

public Triangle(double length , double height)

{
bs = length;
hgt = height;
}

public virtual double Area()
{
return bs * hgt / 2;
}

public void Describe(string type)
{
Console.WriteLine("Triangle - {0}", type);
Console.WriteLine("Base:   {0}", bs);
Console.WriteLine("Height: {0}", hgt);
Console.WriteLine("Area:   {0}", Area());
}
}

sealed public class Irregular : Triangle
{
public Irregular(double Base, double Height): base(Base, Height)
{
}
}
}








































Output of above sample will be like this














From above example we can easily say that sealed classes can’t inherit or acquire properties from parent class. 

Another Important information is if we create a staticclass, it becomes automatically sealed. This means that you cannot derive a class from a static class. So, the sealed and the static class have in common that both are sealed. The difference is that you can declared a variable of a sealed class to access its members but you use the name of a static class to access its members.


No comments: