Dot.Net


1) Page Life Cycle:
Page_Init -- Page Initialization
LoadViewState -- View State Loading
LoadPostData -- Postback data processing
Page_Load -- Page Loading
RaisePostDataChangedEvent -- PostBack Change Notification
RaisePostBackEvent -- PostBack Event Handling
Page_PreRender -- the brief movement Before the page is displayed to the user as HTML
SaveViewState -- View State Saving
Page_Render -- Page Rendering
Page_UnLoad -- when page finishes loading.

The new events added to the page class are:

1. InitComplete is called when the page is initialized and the process is complete.

2. LoadComplete as the name suggests is called at the end of the load stage of the page’s life cycle.

3. PreInit is called before the page is initialized

4. PreLoad is called before the loading of the page is complete.

5. PreRenderComplete is called when the prerendering phase is complete and all the child controls have been created. After the event, the personalization data and the view state are saved and the page is rendered to HTML.

2) What happens during the Page_Init event?
The server controls are loaded and initialized from the Web form’s view state. This is the first step in a Web form’s life cycle.
3) What are the major differences between asp.net1.1 and asp.net 2.0?
 
Asp.net 2.0 enhanced with many new features.
 
* Partial Classes * Master pages * Skins and Themes * Roles and MemberProfiles
* Generics * Added many new server contols like GridView, DetilsView, FileUpload 
* Web Personalization - Web Parts * New Folders like App_Browsers, App_Code
 
You can improve your ASP.NET application performance using:
·         Use Page.IsPostBack
·         Use SQL Server Stored Procedures for Data Access
·         the HttpServerUtility.Transfer method
·         Save View State Only When Necessary.
·         Don’t Rely on Exceptions.
·         Restrict Use of Session State.
·         Limit ASP.NET Server Controls
·         Precompiled Your Apps
·         Use ASP.NET Caching3

ASP
ASP.NET
It is a COM Based Technology
It is dot net framework built in technology
Asp is bounded with the scripting language
Asp.net is language independent technology
Asp depends on html controls
Asp.net provides its own server side controls
Asp uses web services like IIS ,buster web services,peer web server for its program execution
Uses only IIS for it’s program executions.
It is a interpreted technology
It is a compiled technology
It is object based technology(it supports only few oops concept)
It is object oriented technology
Files should save with .asp extension
Should save with .aspx extension
Asp work with VB as the language
Work with vb & c# as the languages.

 
4) State Management is 2 types
 
Client-side state management                 
         This maintains information on the client's machine using Cookies, View State, and Query Strings.
Cookies.
A cookie is a small text file on the client machine either in the client's file system or memory of client browser session. Cookies are not good for sensitive data. Moreover, Cookies can be disabled on the browser. Thus, you can't rely on cookies for state management.
View State 
Each page and each control on the page has View State property. Viewstate are nothing but hidden fields generated by asp.net at runtime to maintain the state of the (Controls) object. We can maintain viewstate in three levels. Application level, Page Level, Control level. For this EnableViewState property should be true. These viewstate will be available only in the page. If the page will get expire this also will be expire in runtime. We can maintain viewstate with in the page only. You can't transmit data to other page using view state. 
Querystring
Query string can maintain limited state information. Data can be passed from one page to another with the URL but you can send limited size of data with the URL. Most browsers allow a limit of 255 characters on URL length.
Server-side state management
       This kind of mechanism retains state in the server.
Application State
The data stored in an application object can be shared by all the sessions of the application. The application object stores data in the key value pair. 
Session State
Session state stores session-specific information and the information is visible within the session only. ASP.NET creates unique sessionId for each session of the application. SessionIDs are maintained either by an HTTP cookie or a modified URL, as set in the application's configuration settings. By default, SessionID values are Stored in a cookie.

How do you create a permanent cookie?
 
You can set the permanent cookied by setting the expiry date to the MaxDate
<%
Response.Cookies("username") = "you"
Response.Cookies("username").Expires = Date.MaxValue 
%>
How do you turn off cookies for one page in your site? Answer

Use the Cookie.Discard Property which Gets or sets the discard flag set by the server. When true, this property instructs the client application not to save the Cookie on the user’s hard disk when a session ends.

Explain the functionality of "EnableViewState" ? What happens if you want it on or off?
 
If we Enable Enableviewstate property then the state of that particular control will remains even after postback.If we disable Enableviewstate property then after postback that control will lose the previous state.
What is the difference between a session object and cache object

Caching :- used to minimize the DB/Server hit and improves Performance. Data is available to all users.Can expire automatically once duration is specified and until memory is available or expires as application restarts.
Session: - used to store data specific to user and remains until user logs off or session expires. Usually session lasts for 20 minutes (configurable)

What are the different types of Session state management options available with ASP.NET?
1)In process (InProc)LDefault) Session state exists within the process the web is using
2)state server (OutProc)Session data is sent to the configured state server service
3)sql server (OutProc)Session data is store in the configured sql server database
InProc
Adv.: 1) Faster as session resides in the same process as the application
         2) No need to serialize the data
DisAdv.: 1) Will degrade the performance of the application if large chunk of data is stored
             2) On restart of IIS all the Session info will be lost
State Server
Adv.: 1) Faster then SQL Server session management
         2) Safer then InProc. As IIS restart won't effect the session data
DisAdv.:1) Data need to be serialized
            2) On restart of ASP.NET State Service session info will be lost
            3)Slower as compared to InProc
SQL Server
Adv.:1) Reliable and Durable
        2) IIS and ASP.NET State Service restart won't effect the session data
        3) Good place for storing large chunk of data
DisAdv.:1) Data need to be serialized
            2) Slower as compare to InProc and State Server
            3)Need to purchase Licensed version of SQL Server

What are the benefits and limitations of using hidden fields?
Advantages:
a. Easy to implement
b. Hidden fields are supported by all browsers
c. Enables faster access of information because data is stored on client side
Disadvantages:
a. Not secure because the data is stored on Client side.
b. Decreases page performance if too many hidden fields
c. Only support single value.

What are benefits and limitations of using Cookies?
Advantages:
a. They are simple to use.
b. Light in size, thus occupy less memory.
c. Stores server information on client side
d. Data need not to be sent back to server.
e. Cookies persist for much longer period of time than a session.
Disadvantages :
a. Since they are stored on the client side in plain text, they are not secure.
b. Number of cookies that can be stored and their size is limited.
c. They don't work if security level is set too high in browser.
d. Some people might just disable cookies on their browsers.

What is QueryString? Benefits and limitations of using querystring.
Querystring is way to transfer information from one page to another through the URL. QueryString is attached to the URL with "?".
Advantages:
a. Supported by all the browsers
b. No extra effort is needed to code.
c. Easy to use.
Disadvantages:
a.  All the attributes and values are visible to the end user. Therefore, they are not secure.
b. There is a limit to URL length of 255 characters.

Explain the types of Caching using Cache object of ASP.NET.
Caching is a concept of storing frequently used data into temporary memory. Actually caching is improves the performance of the page.
Page output: Is used to fetch information or data at page level. It is best used when the site is mainly static. Used by declaring the output page directive
Page fragment: Is used to cache the structure level information. It is used when parts of pages change. For example: user control
Programmatic or data: Is used to fetch the information of an application quickly based on the requirements

What r the Templeats in ASP.net?

ASP.NET WEBSITE TEMPLATE, ASP.NET WEB SERVICE,AJAX,PERSONAL WEB STARTER,ETC
The Repeater ,DataList, ASP.NET server controls and ASP.NET mobile controls are templated controls.
In repeater control there have a 7 Templates
1.header temp
2.item temp
3.alternative temp
4.seperater temp
5.footer temp
6.Selected item Template
7.Edit item Template

Types of object in asp.net..?
 
    Request object, Response object, session object, application object ,server . 
    here are five types of built in objects
1) Request Object (It is used to access the information sent in a request from a                                    browser to the server).
2) Response Object (It is used to send information to the browser).
3) Session Object (It is used to store & retrieve information about particular user sessions).
4) Application object (It is used to store & retrieve information that can be shared among   all the users of an             application).
5) Server Object (It is used to access various utility functions on the server).

What are differences between html controls and server controls.

HTML controls do process on client side whereas Server controls run on server side.

Asp.net - How to find last error which occurred?
 
Exception LastError;
String ErrMessage;
LastError = Server.GetLastError();
if (LastError != null)
ErrMessage = LastError.Message;
else
ErrMessage = "No Errors";
Response.Write("Last Error = " + ErrMessage);
 
What is the Pre-Compilation feature of ASP.NET 2.0?
                        Previously, in ASP.NET, the pages and the code used to be compiled dynamically and then cached so as to make the requests to access the page extremely efficient. In ASP.NET 2.0, the pre-compilation feature is used with which an entire site is precompiled before it is made available to users. There is a pre-defined folder structure for enabling the pre-compilation feature:
  • App_Code: stores classes
  • App_Themes: stores CSS files, Images, etc.
  • App_Data: stores XML files, Text Files, etc.
  • App_GlobalResources: stores all the resources at global level E.g. resx files, etc
  • App_LocalResources: stores all the resources at local/Page level
App_code in as.net..?

     App_Code directory contains reusable classes while compiling the project all the classes create one dll at runtime that is accessed by websites if necessary. If we are not putting the class files in to App_Code directory compiler does not create a dll file also websites cant able to access program logics files from the dll.

Can any one explain about 3-tier architecture and how to deploy 3 layers of 3-tier architecture in 3 different  servers.
3 tier architecture is sliced into three layers.
1) Presentation / application layer : that consists of all the UI part which is shown to the screen.
2) Business logic layer : which contains all the business logic for manipulation and ways to handle data.
3) Data access layer : which comunicate to database and pull all the data from data server and provide data to business layer.
  Each layer communicated to its nearest layer only ie. Presentation layer can communicate to Business layer and vice versa.
  In 3 tier architecture there are basically two are the assemblies for BLL and DAL. if we have to deploy these on three different server than we need to do something like:
Server 1 : Database server : (SQL Server / Oracle)
Server 2 : Business Server : Contain Assemblies and communicate to Presentation layer using web service or WCF.
Server 3 : Presentation Server : Contain the UI part to display data fetched from Business layer consuming the Webservice or WCF.
Tell About Global.asax
      Global.asax file is resides in the root directory of the application. it is also known an asp.net application file.
it is handle for the application and session levels events raised by Asp.net. At run time. it is compiled dynamically.
         This is the single file in all over the application. i.e. you can't add the file with the same name in another location
2. it is used to set the variable or other global settings..
3. it has events for
                            a) application start
                            b) application end
                            c) session start
                            d) session end
                            e) application error
                            f) application Authenticate Request
we can use appropriate event for appropriate work

What is application variable and when it is initialized

 Application variable is generally Stored in Application State in Application_start event in Global.asax file which is fired when the first Instance of Application is created or when first user open the Website. Item added to the Application variable in function like global variable in ASP.NET Page



What is Difference between Callbacks and Postback in ASP.NET?

Callback is also the form of Postback, but the difference is in postback execute a complete page life cycle and whole page redraw, in callback only specific portion (Contorl) is executed/redraw using client side scriptiong.PostBack: Postback is the event which sends the form data to the server. The server processes the data & sends it back to the browser. The page goes through its full life cycle.

What is the difference between application object and session object?

Application object: can store the value through out the application.It using Application.lock(),Application.unlock () for store the values.
Session Object:- Using the session object u can store data for some specific user.data not store permanently in the session.
The Application object stores data that is shared accross the application and not for a specific user. Internally the values of both the Session and Application objects are stored in a key/value pair (HashTable).

 
why we should use more than one web.config files in our application? I have two web.config files in my application. One in the root directory and another one inside a sub folder. When the application runs which web.config file will run? why?
 
   we can use more than one web.config file to meet the different security and other configuration requirements of different directories, and in any case web.config file of 
subdirectory will take the precedence over file of root directory.
 
What is difference b/w Data Grid in ASP.Net 1.1 and Gridview in 2.0
Data Grid
Gridview
Code requires handling the Sort Command event and
rebinding grid required.

No code required.

Code requires handling the Page Index Changed

No code required for Page Index Changed.

Need extensive code for update operation on data.

Needs little code for update operation.

When compared to grid view fewer events supported.

Grid View supports events fired before and after database updates

In data grid no image templete column
dataview have image templete column.



How to edit gridview control in asp.net 2.0?

   Add Edit button into gridview item template.
   Gridview1_rowedit event we can write the code.

How many web.config files add in each solutions.

    By default there is only one web.config file in asp.net application. but if we want to create more than one web.config we can create, but they should not be in same directory.
 
What is response.flush method..?
    
     It send all buffered data to the browser immediately. when u use response.flush() before that checks wheather u have write response.buffer=true.
How .Net has implemented security for web applications?

1) Authentication/Authorization
2) Encryption/Decryption
3) Maintaining web servers outside the corporate firewall. etc.,
 
 Types of configuration files and their differences?
1) app.config-> contains application specific settings

2)web.config :Web.config is a security in ASP.Net application and how to secure applications. Web.config does most of the work for the application the who, what, where, when and how to be authenticated.
1.This is automatically created when you create an ASP.Net web application project.
2.This is also called application level configuration file.
3.This file inherits setting from the machine.config

3) Machine.config contains settings that apply to an entire computer. This file is located in the %runtime install path% \Config directory. Machine.config contains configuration settings for machine-wide assembly binding, built-in remoting channels.
1.This is automatically installed when you install Visual Studio. Net.
2.This is also called machine level configuration file.
3.Only one machine.config file exists on a server.
4.This file is at the highest level in the configuration hierarchy.
 
Where does Web.Config Info stored? Will this be stored in the registry?

Web Config is a file which contains settings for your application. You can check Web.config file in your application main folder. This information is not stored in registry

What was the difference between machine.config and web.config files

1)Machine.config is used to store machine level settings Web.config is used to store per application based settings
2)We can have more than one web.config files but only one machine.config
3)Web.config overrides the machine.config file. If we store different values on both for a single key, the application will get the value from the web.config file.

How to authenticate users using Web.Config ?

in web.config file we can specify the authentication mode
<authentication mode="windows/forms">
for form autentication we can wirte like this
<authentication mode="forms">
<form name="a.aspx" loginurl="login.aspx"  time out="30" protection ="all">

What are the types of authentications in ASP.NET?

Both Authentication and Authorization are concepts of providing permission to users to maintain different levels of security, as per the application requirement.
Authentication: is the mechanism whereby systems may securely identify their users. Authentication systems depend on some unique bit of information known only to the individual being authenticated and the authentication system.
Authorization : is the mechanism by which a system determines what level of access a particular authenticated user should have to secured resources controlled by the system.
When a user logs on to an application/system, the user is first Authenticated, and then Authorized.
ASP.NET has 3 ways to Authenticate a user:
1) Forms Authentication
2) Windows Authentication
3) Passport Authentication (This is obsolete in .NET 2.0)

What are Authentication mechanisms in .Net?

authentication is to verify that indentity has right to access or not mechanisms are
1.windows :  for windows authentication we need iis because iis provid windows authentication.
2.passport  :in that authentication check using microsoft passport  service.
3.form : in that authentication is based on session cokkies.if that is not available then page is redirected.

How To Deploy The Asp.Net Project..?
                                                                                  
   the other way of deploying the asp.net project is, we can go IIS (Internet Information Service ). create a new virtual directory in the IIS-->Default Website-->UR project name -->and browse the path of your project.after completion of this processec.go to browser ant type. http://localhost/UR project name/login.aspx

What is meant by role based security? when we use this one

We can use role based security while we use forms authentication to authenticte users and roles are used to
authorize i.e grant or deny access to particular pages in ur application depending upon the user role assigned to
them.



Explain the access specifiers Public, Private, Protected, Friend, Internal, Default
The main purpose of using access specifiers is to provide security to the applications. The
availability (scope) of the member objects of a class may be controlled using access specifiers.
1. PUBLIC :As the name specifies, it can be accessed from anywhere. If a member of a class is defined as public then it can be accessed anywhere in the class as well as outside the class. This means that objects can access and modify public fields, properties, methods.
2. PRIVATE : As the name suggests, it can't be accessed outside the class. It’s the private property of the class and can be accessed only by the members of the class.
3. FRIEND/INTERNAL : Friend & Internal mean the same. Friend is used in VB.NET. Internal is used in C#. Friends can be accessed by all classes within an assembly but not from outside the assembly.
4. PROTECTED : Protected variables can be used within the class as well as the classes that inherites this class.
5. PROTECTED FRIEND/PROTECTED INTERNAL : The Protected Friend can be accessed by Members of the Assembly or the inheriting class, and of course, within the class itself.
6. DEFAULT: A Default property is a single property of a class that can be set as the default. This
allows developers that use your class to work more easily with your default property
because they do not need to make a direct reference to the property. Default properties
cannot be initialized as Shared/Static or Private and all must be accepted at least on
argument or parameter. Default properties do not promote good code readability, so use
this option sparingly.
Object
Instance of Class is called object. An object is created in memory using keyword “new”.
Properties
Attribute of object is called properties. Eg1:- A car has color as property.
Eg2:
private string m_Color;;
public string Color
{
get
{
return m_Color;
}
set
{
m_Color = value;
}
}
Car Maruti = new Car();
Maruti.Color= “White”;
Console.Write(Maruti.Color);
Value Type and Reference Type Concept in .Net
A variable is value type or reference type is solely determined by its data type.
Eg: int, float, char, decimal, bool, decimal, struct, etc are value types, while object type such as class, String, Array, etc are reference type.
Value Type1) As name suggest Value Type stores “value” directly.
2) For eg:
//I and J are both of type int
I = 20;
J = I;
int is a value type, which means that the above statements will results in two locations in memory.
3) For each instance of value type separate memory is allocated.
4) Stored in a Stack.
5) It Provides Quick Access, because of value located on stack.
Reference Type1) As name suggest Reference Type stores “reference” to the value.
2) For eg:
Vector X, Y; //Object is defined. (No memory is allocated.)
X = new Vector(); //Memory is allocated to Object. //(new is responsible for allocating memory.)
X.value = 30; //Initialising value field in a vector class.
Y = X; //Both X and Y points to same memory location. //No memory is created for Y.
Console.writeline(Y.value); //displays 30, as both points to same memory
Y.value = 50;
Console.writeline(X.value); //displays 50.
Note: If a variable is reference it is possible to indicate that it does not refer to any object by setting its value to null;
3) Reference type are stored on Heap.
4) It provides comparatively slower access, as value located on heap.
“out Keyword” in C#.
out keyword is used for passing a variable for output purpose. It has same concept as ref keyword, but passing a ref parameter needs variable to be initialized while out parameter is passed without initialized. 
It is useful when we want to return more than one value from the method.
Point to be kept in mind while using out keyword.
You must assigned value to out parameter in method body, otherwise the method won’t compiled.
Example of “out keyword”:
class Test
{
public static void Main()
{
int a; // may be left un-initialized
DoWork(out a); // note out
Console.WriteLine("The value of a is " + a); 
}
public static void DoWork(out int i) // note out
{
i=4; //must assigned value.
}
}

The program will result : The value of a is 4
this Keyword
Each object has a reference “this” which points to itself.
Two uses of this keyword.
o Can be used to refer to the current object.
o It can also be used by one constructor to explicitly invoke another constructor of the same class.
Eg1:
class Student
{
private string name;
private int age;
Student(string name, int age)
{
this.name = name;
this.age = age;
}
}
Eg2:
class Circle
{
double x,y,radius;
Circle(double x){
this(x,0,1);
}
Circle(double x, double y){
this(x,y,1);
}
Circle(double x, double y, double radius){
this.x = x;
this.y = y;
this.radius = radius;
}
}
what is difference between const, static and readonly?

const variable : const can never be modified and must be initialized to a compile time constant.
Static variable : you received last updated value, when u getting value for static variable.
Readonly variable : The readonly variable can be changed inside the constructor.

Garbage Collection Concept

1) Garbage collection is the mechanism that reclaims the memory resources of an object when it is no longer referenced by a variable.
2) .Net Runtime performs automatically performs garbage collection, however you can force the garbage collection to run at a certain point in your code by calling System.GC.Collect().
3) Advantage of Garbage collection : It prevents programming error that could otherwise occur by incorrectly deleting or failing to delete objects.
What is “out” keyword in C#.
Casting 
Converting between data types can be done explicitly using a cast, but in some cases, implicit conversions are allowed. For example:
static void TestCasting()
{
    int i = 10;
    float f = 0;
    f = i;  // An implicit conversion, no data will be lost.
    f = 0.5F;
    i = (int)f;  // An explicit conversion. Information will be lost.
}
The following program casts a double to an int. The program will not compile without the cast.
class Test
{
    static void Main()
    {
        double x = 1234.7;
        int a;
        a = (int)x;  // cast double to int
        System.Console.WriteLine(a);
    }
}

enum

The enum keyword is used to declare an enumeration, a distinct type that consists of a set of named constants called the enumerator list.
Usually it is best to define an enum directly within a namespace so that all classes in the namespace can access it with equal convenience. However, an enum can also be nested within a class or struct.
By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1. For example: enum Days {Sat, Sun, Mon, Tue, Wed, Thu, Fri};
In this enumeration, Sat is 0, Sun is 1, Mon is 2, and so forth. Enumerators can have initializers to override the default values. For example: enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};
Every enumeration type has an underlying type, which can be any integral type except char. The default underlying type of the enumeration elements is int. To declare an enum of another integral type, such as byte, use a colon after the identifier followed by the type: enum Days : byte {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};
The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong.
public class EnumTest
{
    enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
 
    static void Main()
    {
        int x = (int)Days.Sun;
        int y = (int)Days.Fri;
        Console.WriteLine("Sun = {0}", x);
        Console.WriteLine("Fri = {0}", y);
    }
}
/* Output:
   Sun = 0
   Fri = 5
*/
public class EnumTest2
{
    enum Range : long { Max = 2147483648L, Min = 255L };
    static void Main()
    {
        long x = (long)Range.Max;
        long y = (long)Range.Min;
        Console.WriteLine("Max = {0}", x);
        Console.WriteLine("Min = {0}", y);
    }
}
/* Output:
   Max = 2147483648
   Min = 255
*/
The following code example illustrates the use and effect of the System.FlagsAttribute attribute on an enum declaration.          
[Flags]
public enum CarOptions
{
    SunRoof = 0x01,
    Spoiler = 0x02,
    FogLights = 0x04,
    TintedWindows = 0x08,
}
 
class FlagTest
{
    static void Main()
    {
        CarOptions options = CarOptions.SunRoof | CarOptions.FogLights;
        Console.WriteLine(options);
        Console.WriteLine((int)options);
    }
}
/* Output:
   SunRoof, FogLights
   5
*/

Constants

Constants are immutable values which are known at compile time and do not change for the life of the program. Constants are declared with the const modifier. 
C# does not support const methods, properties, or events.
(video)

Casting and Type Conversions 

(video)
Implicit conversions: No special syntax is required because the conversion is type safe and no data will be lost. Examples include conversions from smaller to larger integral types, and conversions from derived classes to base classes.
// Implicit conversion. num long can
// hold any value an int can hold, and more!
int num = 2147483647;
long bigNum = num;
Derived d = new Derived();
Base b = d; // Always OK.
Explicit conversions (casts): Explicit conversions require a cast operator. Casting is required when information might be lost in the conversion, or when the conversion might not succeed for other reasons.  Typical examples include numeric conversion to a type that has less precision or a smaller range, and conversion of a base-class instance to a derived class.
class Test
{
    static void Main()
    {
        double x = 1234.7;
        int a;
        // Cast double to int.
        a = (int)x;
        System.Console.WriteLine(a);
    }
}
// Output: 1234
// Create a new derived type.
        Giraffe g = new Giraffe();
 
        // Implicit conversion to base type is safe.
        Animal a = g;
 
        // Explicit conversion is required to cast
        // back to derived type. Note: This will compile but
        // throw an exception at run time if the right-side
        // object is not in fact a Giraffe.
        Giraffe g2 = (Giraffe) a;

User-defined conversions: User-defined conversions are performed by special methods that you can define to enable explicit and implicit conversions between custom types that do not have a base class–derived class relationship.

Strings

A C# string is an array of characters declared using the string keyword. A string literal is declared using quotation marks,
String objects are immutable, meaning that they cannot be changed once they have been created. Methods that act on strings actually return new string objects.
string s = "Hello, World!";
string s1 = "orange";
string s2 = "red";
 
s1 += s2;
System.Console.WriteLine(s1);  // outputs "orangered"
 
s1 = s1.Substring(2, 5);
System.Console.WriteLine(s1);  // outputs "anger"
ToString()--Like all objects derived from Object, strings provide the ToString method, which converts a value to a string. This method can be used to convert numeric values into strings, like this:
string s3 = "Visual C# Express";
 
System.Console.WriteLine(s3.Substring(7, 2));         // outputs "C#"
System.Console.WriteLine(s3.Replace("C#", "Basic"));  // outputs "Visual Basic Express"
string s4 = "Hello, World";
char[] arr = s4.ToCharArray(0, s4.Length);
 
foreach (char c in arr)
{
    System.Console.Write(c);  // outputs "Hello, World"
}
 
string s5 = "Printing backwards";
 
for (int i = 0; i < s5.Length; i++)
{
    System.Console.Write(s5[s5.Length - i - 1]);  // outputs "sdrawkcab gnitnirP"
}
string s6 = "Battle of Hastings, 1066";
 
System.Console.WriteLine(s6.ToUpper());  // outputs "BATTLE OF HASTINGS 1066"
System.Console.WriteLine(s6.ToLower());  // outputs "battle of hastings 1066"
string color1 = "red";
string color2 = "green";
string color3 = "red";
 
if (color1 == color3)
{
    System.Console.WriteLine("Equal");
}
if (color1 != color2)
{
    System.Console.WriteLine("Not equal");
}
string s7 = "ABC";
string s8 = "abc";
 
if (s7.CompareTo(s8) > 0)
{
    System.Console.WriteLine("Greater-than");
}
else
{
    System.Console.WriteLine("Less-than");
}
string s9 = "Battle of Hastings, 1066";
 
System.Console.WriteLine(s9.IndexOf("Hastings"));  // outputs 10
System.Console.WriteLine(s9.IndexOf("1967"));      // outputs -1
char[] delimit = new char[] { ' ' };
string s10 = "The cat sat on the mat.";
foreach (string substr in s10.Split(delimit))
{
    System.Console.WriteLine(substr);
}
string str = "hello";
string nullStr = null;
string emptyStr = "";
 
string tempStr  = str + nullStr; // tempStr = "hello"
bool b = (emptyStr == nullStr);// b = false;
emptyStr + nullStr = ""; // creates a new empty string
int I  = nullStr.Length; // throws NullReferenceException
 
 

Using StringBuilder

The StringBuilder class creates a string buffer that offers better performance if your program performs a lot of string manipulation. The StringBuilder string also allows you to reassign individual characters, something the built-in string data type does not support. This code, for example, changes the content of a string without creating a new string:

System.Text.StringBuilder sb = new System.Text.StringBuilder("Rat: the ideal pet");
sb[0] = 'C';
System.Console.WriteLine(sb.ToString());
System.Console.ReadLine();

In this example, a StringBuilder object is used to create a string from a set of numeric types:

class TestStringBuilder
{
    static void Main()
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
 
        // Create a string composed of numbers 0 - 9
        for (int i = 0; i < 10; i++)
        {
            sb.Append(i.ToString());
        }
        System.Console.WriteLine(sb);  // displays 0123456789
 
        // Copy one character of the string (not possible with a System.String)
        sb[0] = sb[9];
 
        System.Console.WriteLine(sb);  // displays 9123456789
    }
}
 

        Both String and StringBuilder are classes used to handle strings. The most common operation with a string is concatenation. This activity has to be performed very efficiently. When we use the "String" object to concatenate two strings, the first string is combined to the other string by creating a new copy in the memory as a string object, and then the old string is deleted. This process is a little long. Hence we say "Strings are immutable".
When we make use of the "StringBuilder" object, the Append method is used. This means, an insertion is done on the existing string. Operation on StringBuilder object is faster than String operations, as the copy is done to the same location. Usage of StringBuilder is more efficient in case large amounts of string manipulations have to be
performed.

String Class
StringBuilder
Once the string object is created, its length and content cannot be modified. so strings r immutable.
Even after object is created, it can be able to modify length and content.
Slower
Faster

What r collections c sharp?

collection classes in c#.net is data structors this data structors are hold the data in diffrent way for flexible operations this collection classes are derived from i collection and I list ,ienumerable,idictionary interfaces..
in .net version 1.0 having different type of collection classes this are all defined with in system.collection namespaces main imp classes array list,hash table,stack,queue in the above collection classes support diff way to data storing and retrieving
in .net 2.0 having different type of collection classes this classes are define under system.collection.generic  namespce imp classes
list --this is corresponding to array list
dictionay--this is corresponding to hashtable
stack and heap --this are corresponding to same stack and heap collection classes in the system.collection namespace

 

Arrays

An array is a data structure that contains several variables of the same type. Arrays are declared with a type:
type[] arrayName;
class TestArraysClass
{
    static void Main()
    {
        // Declare a single-dimensional array 
        int[] array1 = new int[5];
 
        // Declare and set array element values
        int[] array2 = new int[] { 1, 3, 5, 7, 9 };
 
        // Alternative syntax
        int[] array3 = { 1, 2, 3, 4, 5, 6 };
 
        // Declare a two dimensional array
        int[,] multiDimensionalArray1 = new int[2, 3];
 
        // Declare and set array element values
        int[,] multiDimensionalArray2 = { { 1, 2, 3 }, { 4, 5, 6 } };
 
        // Declare a jagged array
        int[][] jaggedArray = new int[6][];
 
        // Set the values of the first array in the jagged array structure
        jaggedArray[0] = new int[4] { 1, 2, 3, 4 };
    }
}
(video)
ArrayList:
 ArrayList is a dynamical array; it will increase the size of the storage location as required. It stores the value as object. The allocation of the ArrayList can be achieved through the TrimToSize property.
1
Add
It will add the element as object in the ArrayList
2
AddRange
It will add the collections of elements in the object as individual objects in the ArrayList
3
Clear
It will clear the all objects in the ArrayList
4
BinarySearch
It will return the position of the search object as integer value.
5
Insert
It will insert the element in the specified location of the index in the ArrayList.
6
InsertRange
It will insert the elements in the object as individual objects in the specified location.
7
Remove
It will remove the given object in the first occurrence in the ArrayList.
8
RemoveAt
It will remove the object as specified in the argument.
9
RemoveRange
It will remove the set of objects in the ArrayList from the range specified.
10
Sort
It will do the sorting of the elements in the ascending order.
11
Reverse
It will arrange the elements in the reverse order in the ArrayList.
12
GetEnumerator
It will return the collection of objects in the ArrayList as enumerator.
13
Contains
It checks whether the objects exists or not.
ArrayList oArrayList = new ArrayList();
oArrayList.Add("senthil");

Stack oStack = new Stack();
oStack.Push(1);
oStack.Push(2);
oStack.Push(3);
oStack.Push(4);

ArrayList oArrayList = new ArrayList();
oArrayList.Add("Senthil");
oArrayList.Add("Kumar");
oArrayList.AddRange(oStack);
ArrayListObject.Clear();

 Advantages:
  • The ArrayList is not a specific data type storage location, it stores everything as object.
  • No need to do allocation and deallocation explicitly to store the data.
  • It has the explicit sorting methods.
  • It can insert and delete the elements in between positions in the ArrayList.
  • It can store the object as elements.
Disadvantages:
  • ArrayList is not a strongly typed one. It has to do the type casting when you retrieve the content. When we do the type casting every time, it hits the performance.
  • It uses the LinkedList storage approach, because if you insert or delete the specific position it has to forward/backward in the storage address.
  • Sometimes it leads to the runtime error. Consider an example, we store the ids of the employee in the arraylist and then we want to retrieve the element for some other operations. Obviously we need to do the type casting, that time if there is any string element then what will happen? It will throw the error.
Difference between Array and ArrayList:
Array
ArrayList
Array uses the Vector array to store the   elements
ArrayList uses the LinkedList to store the   elements.
Size of the Array must be defined until redim used( vb)
No need to specify the storage size.
Array is a specific data type storage
ArrayList can be stored everything as object.
No need to do the type casting
Every time type casting has to do.
It will not lead to Runtime exception
It leads to the Run time error exception.
Element cannot be inserted or deleted in   between.
Elements can be inserted and deleted.
There is no built in members to do ascending or descending.
ArrayList has many methods to do operation like Sort, Insert, Remove, BinarySeacrh,etc..,

Explain constructor and destructor with an example using C#.NET.
A constructor is a member function that performs the task of initializing the objects with the default values to be assigned after creation.
A destructor is a function that is run to release the resources held by an object when it is no longer needed by the application.
In C#.NET we can create constructor and destructor in the following manner:
-----------------CONSTRUCTOR---------
class C
{
       private int x; 
       public C (int i, int j)
       {
                 x = i;
                 y = j;
       }
       public void display ()  
       {
               Console.WriteLine(x + "i+" + y);
       }
}
----------------DESTRUCTOR---------
class D
{
        public D()
        {
            // constructor
        }      
        ~D()
        {
           // Destructor
        }
}

 

Static Constructors

(video)
A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.
class SimpleClass
{
    // Static constructor
    static SimpleClass()
    {
        //...
    }
}
Static constructors have the following properties:
·         A static constructor does not take access modifiers or have parameters.
·         A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
·         A static constructor cannot be called directly.
·         The user has no control on when the static constructor is executed in the program.
·         A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
·         Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.
In this example, the class Bus has a static constructor and one static member, Drive(). When Drive() is called, the static constructor is invoked to initialize the class.
public class Bus
{
    // Static constructor:
    static Bus()
    {
        System.Console.WriteLine("The static constructor invoked.");
    }
 
    public static void Drive()
    {
        System.Console.WriteLine("The Drive method invoked.");
    }
}
 
class TestBus
{
    static void Main()
    {
        Bus.Drive();
    }
}
O/P::::::
The static constructor invoked.
The Drive method invoked.

Boxing and Unboxing

Boxing is used to store value types in the garbage-collected heap. Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by this value type. Boxing a value type allocates an object instance on the heap and copies the value into the new object.
Boxing Conversion

BoxingConversion graphic
It also possible to perform the boxing expli
class TestBoxing
{
    static void Main()
    {
        int i = 123;
        object o = i;  // Implicit boxing
 
        i = 456;  // Change the contents of i
 
        System.Console.WriteLine("The value-type value = {0}", i);
        System.Console.WriteLine("The object-type value = {0}", o);
    }
}
/* Output:
    The value-type value = 456
    The object-type value = 123
*/
Unboxing
Unboxing is an explicit conversion from the type object to a value type or from an interface type to a value type that implements the interface. An unboxing operation consists of:
·         Checking the object instance to make sure that it is a boxed value of the given value type.
·         Copying the value from the instance into the value-type variable.
int i = 123;      // a value type
object o = i;     // boxing
int j = (int)o;  // unboxing
UnBoxing Conversion graphic
Constructor and Destructors
(video)
 (Video)
 What is early binding and late binding. Difference which is better?

Early binding: Properties and method can be identified by compile time.
Example:  dim rs as recordset
Late binding: Properties and method can be identified by Run time.
Example:  dim  obj as classname
                 set obj=new  classname

Difference b/w casting and boxing?

Boxing is converting a value type to a reference type (Object Type).Casting is converting a reference type to a  reference type or a value type as another value type.
int i = 0;
object o = (object)i; //this is boxing
int i2 = (int)o; //this is unboxing.
long l = (long)i; //this is casting.
 
Does C# support multiple inheritance ?

.NET not supports multiple inheritance. It only supports muli- level inheritance.
ie : Only one class can inherit at a time. If u need more, u have to inherit that classes
one after one in Different clasees
eg: A inplements B
B implements C
then u can implement B,C to A


Difference between strong type and weak type

Strong types are type checked which is done at the time of compiling and on the other hand Weak types are done at run time. If we have big programs then we will use strong type. And at the time of we are doing Scripting we uses the weak type.

What do you mean by Hash Mapping

Hash map is same as hash table but it will allows null values as keys and objects. One more feature is Hash map is not synchronized one but hash table is synchronized. We can use hash map when data is in form of key pair values.

What is an Event?

When an action is performed, this action is noticed by the computer application based on which the output is displayed. These actions are called events. Examples of events are pressing of the keys on the keyboard, clicking of the mouse. Likewise, there are a number of events which capture your actions. 

Define Delegate. ?    

Delegates are kind of similar to the function pointers. But they are secure and type-safe.
A delegate instance encapsulates a static or an instance method.
Declaring a delegate defines a reference type which can be used to encapsulate a method having a specific signature. 
An event is a message sent by a control to notify the occurrence of an action. However it is not known which object receives the event. For this reason, .NET provides a special type called Delegate which acts as an intermediary between the sender object and receiver object.
Explain Generics?
i)Generics does not require boxing and unboxing while inserting and retrieving elements.
ii)By Performane wise Generics were fast
iii)Generics are type safety.

 

How does the ASP.NET Cache work?                  

 

=======================================================

how to insert images into database and how to retrieve and bind images to gridview using asp.net (or) save and retrieve images from database using asp.net

Introduction
Here I will explain how insert and retrieve images from database and how to bind images to gridview using asp.net.
Description:
I have worked on one social networking site at that time we save all the images in to directory folder and we save image path into database at that time I got idea to implement concept like inserting images into database and retrieving the images from database and binding images to gridview using asp.net for that we need follow below steps

First Design table like this in your SQL Server database and give name as Image
Column Name
Data Type
Allow Nulls
ImageId
Int(set identity property=true)
No
ImageName
Varchar(50)
Yes
Image
image
Yes
After that Design your aspx page like this 
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Inserting images into databse and displaying images with gridview</title>
<style type="text/css">
.Gridview
{
font-family:Verdana;
font-size:10pt;
font-weight:normal;
color:black;
width:500px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
Image Name:
</td>
<td>
<asp:TextBox ID="txtImageName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Upload Image:
</td>
<td>
<asp:FileUpload ID="fileuploadImage" runat="server" />
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnUpload" runat="server" Text="Upload" onclick="btnUpload_Click" />
</td>
</tr>
</table>
</div>
<div>
<asp:GridView ID="gvImages" CssClass="Gridview" runat="server" AutoGenerateColumns="False"
HeaderStyle-BackColor="#7779AF" HeaderStyle-ForeColor="white">
<Columns>
<asp:BoundField HeaderText = "Image Name" DataField="imagename" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "ImageHandler.ashx?ImID="+ Eval("ImageID") %>' Height="150px" Width="150px"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
After that add using System.IOusing System.Data.SqlClient; and using System.Configuration; namespaces and write the following code in code behind

string strcon = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridData();
}
}
/// <summary>
/// btnUpload_Click event is used to upload images into database
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnUpload_Click(object sender, EventArgs e)
{
//Condition to check if the file uploaded or not
if (fileuploadImage.HasFile)
{
//getting length of uploaded file
int length = fileuploadImage.PostedFile.ContentLength;
//create a byte array to store the binary image data
byte[] imgbyte = new byte[length];
//store the currently selected file in memeory
HttpPostedFile img = fileuploadImage.PostedFile;
//set the binary data
img.InputStream.Read(imgbyte, 0, length);
string imagename = txtImageName.Text;
//use the web.config to store the connection string
SqlConnection connection = new SqlConnection(strcon);
connection.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Image (ImageName,Image) VALUES (@imagename,@imagedata)", connection);
cmd.Parameters.Add("@imagename"SqlDbType.VarChar, 50).Value = imagename;
cmd.Parameters.Add("@imagedata"SqlDbType.Image).Value = imgbyte;
int count = cmd.ExecuteNonQuery();
connection.Close();
if (count == 1)
{
BindGridData();
txtImageName.Text = string.Empty;
ScriptManager.RegisterStartupScript(thisthis.GetType(), "alertmessage""javascript:alert('" + imagename + " image inserted successfully')"true);
}
}
}
/// <summary>
/// function is used to bind gridview
/// </summary>
private void BindGridData()
{
SqlConnection connection = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("SELECT imagename,ImageID from [Image]", connection);
SqlDataAdapter daimages = new SqlDataAdapter(command);
DataTable dt = new DataTable();
daimages.Fill(dt);
gvImages.DataSource = dt;
gvImages.DataBind();
gvImages.Attributes.Add("bordercolor""black");
}
Here we need to restrict user to upload only image formats in file upload control for that validaiton check this post how to validate file type in file upload control using javascript

After Completion of above code we need to add HTTPHandler file to our project to retrieve images from database because we save our images in binary format getting the binary format of data from database it’s easy but displaying is very difficult that’s why we will use HTTPHandler to solve this problem.
Here HTTPHandler is a simple class that allows you to process a request and return a response to the browser. Simply we can say that a Handler is responsible for fulfilling requests from the browser. It can handle only one request at a time, which in turn gives high performance.
Right Click on your project add new HTTPHandler.ashx file and give name as ImageHandler.ashx and write the following code in pagerequest method like this 
string strcon = ConfigurationManager.AppSettings["ConnectionString"].ToString();
public void ProcessRequest(HttpContext context)
{
string imageid = context.Request.QueryString["ImID"];
SqlConnection connection = new SqlConnection(strcon);
connection.Open();
SqlCommand command = new SqlCommand("select Image from Image where ImageID=" + imageid, connection);
SqlDataReader dr = command.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((Byte[])dr[0]);
connection.Close();
context.Response.End();
}

Here don’t forgot to set the connection string in web.config file here I am getting database connection from web.config file for that reason you need to set the connectionstring in web.config file like this
<connectionStrings>
<add name="dbconnection" connectionString="Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"/>
</connectionStrings>
Demo















1 comment:

hi Happy Reading.......................