Nothing Special   »   [go: up one dir, main page]

Visual Studio 2008 Visual Studio 2005: Web Parts Control Description

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 45

ASP.

NET Web Parts Overview

• Visual Studio 2008


• .NET Framework 3.0
• Visual Studio 2005

ASP.NET Web Parts is an integrated set of controls for creating Web sites that enable end users to
modify the content, appearance, and behavior of Web pages directly from a browser. The
modifications can be applied to all users on the site or to individual users. When users modify
pages and controls, the settings can be saved to retain a user's personal preferences across
future browser sessions, a feature called personalization. These Web Parts capabilities mean that
developers can empower end users to personalize a Web application dynamically, without
developer or administrator intervention.
Using the Web Parts control set, you as a developer can enable end users to:
• Personalize page content. Users can add new Web Parts controls to a page, remove them,
hide them, or minimize them like ordinary windows.
• Personalize page layout. Users can drag a Web Parts control to a different zone on a page,
or change its appearance, properties, and behavior.
• Export and import controls. Users can import or export Web Parts control settings for use in
other pages or sites, retaining the properties, appearance, and even the data in the
controls. This reduces data entry and configuration demands on end users.
• Create connections. Users can establish connections between controls so that, for
example, a chart control could display a graph for the data in a stock ticker control. Users
could personalize not only the connection itself, but the appearance and details of how the
chart control displays the data.

Web Parts Essentials


The Web Parts control set consists of three main building blocks: personalization, user interface
(UI) structural components, and actual Web Parts UI controls. For more details, see Web Parts
Control Set Overview. Much of your development effort will focus on Web Parts controls, which are
simply ASP.NET controls that can use the features of the Web Parts control set.

Essential Personalization Components

Web Parts control Description

WebPartManager Manages all Web Parts on a page, enables or disables personalization,


and manages the life cycle of personalization data. One (and only one)
WebPartManager control is required for every Web Parts page.

WebPartPersonaliza Implements the logic necessary to carry out personalization actions.


tion

Requirements for Using Web Parts Personalization

• Visual Studio 2008


• .NET Framework 3.0
• Visual Studio 2005

1
Personalization is a fundamental capability of the ASP.NET Web Parts control set, and is required
when you want to create pages with Web Parts controls that allow users to modify or personalize
Web pages. This topic discusses the basic requirements for working with Web Parts
personalization. For additional material on personalization and what it does within the Web Parts
control set

.NET Framework Conceptual Overview

• .NET Framework 4
• Visual Studio 2008
• Visual Studio 2005
• .NET Framework 1.1

The .NET Framework is an integral Windows component that supports building and running the
next generation of applications and XML Web services. The .NET Framework is designed to fulfill
the following objectives:
• To provide a consistent object-oriented programming environment whether object code is
stored and executed locally, executed locally but Internet-distributed, or executed
remotely.
• To provide a code-execution environment that minimizes software deployment and
versioning conflicts.
• To provide a code-execution environment that promotes safe execution of code, including
code created by an unknown or semi-trusted third party.
• To provide a code-execution environment that eliminates the performance problems of
scripted or interpreted environments.
• To make the developer experience consistent across widely varying types of applications,
such as Windows-based applications and Web-based applications.
• To build all communication on industry standards to ensure that code based on the .NET
Framework can integrate with any other code.
The .NET Framework has two main components: the common language runtime and the .NET
Framework class library. The common language runtime is the foundation of the .NET Framework.
You can think of the runtime as an agent that manages code at execution time, providing core
services such as memory management, thread management, and remoting, while also enforcing
strict type safety and other forms of code accuracy that promote security and robustness. In fact,
the concept of code management is a fundamental principle of the runtime. Code that targets the
runtime is known as managed code, while code that does not target the runtime is known as
unmanaged code. The class library, the other main component of the .NET Framework, is a
comprehensive, object-oriented collection of reusable types that you can use to develop
applications ranging from traditional command-line or graphical user interface (GUI) applications
to applications based on the latest innovations provided by ASP.NET, such as Web Forms and
XML Web services.
The .NET Framework can be hosted by unmanaged components that load the common language
runtime into their processes and initiate the execution of managed code, thereby creating a
software environment that can exploit both managed and unmanaged features. The .NET
Framework not only provides several runtime hosts, but also supports the development of third-
party runtime hosts.
For example, ASP.NET hosts the runtime to provide a scalable, server-side environment for
managed code. ASP.NET works directly with the runtime to enable ASP.NET applications and XML
Web services, both of which are discussed later in this topic.

2
Internet Explorer is an example of an unmanaged application that hosts the runtime (in the form
of a MIME type extension). Using Internet Explorer to host the runtime enables you to embed
managed components or Windows Forms controls in HTML documents. Hosting the runtime in
this way makes managed mobile code (similar to Microsoft® ActiveX® controls) possible, but
with significant improvements that only managed code can offer, such as semi-trusted execution
and isolated file storage.
The following illustration shows the relationship of the common language runtime and the class
library to your applications and to the overall system. The illustration also shows how managed
code operates within a larger architecture.

.NET Framework in context

Delegates:
Delegate is similar to function pointer in C and C++. A function pointer in C is a variable that
points to function. Similarly, a delegate is a reference type in .net that is used to call the methods
of similar signature as of the delegate. For example, consider a C# method,

void PrintName(string Name)

Response.Write("Name is "+Name+"<br>");

To call the above method using delegate we should declare a delegate with similar signature,

delegate void DelegateTest(string n);

Before calling we should initialize or register the delegate with the method like,

DelegateTest del = new DelegateTest(this.PrintName);

Finally we can call the function by,

Del(“Satheesh Babu”);

3
So what makes the real difference between C language function pointer and a delegate is, at a
given time a function pointer can point to a single function only i.e. it can be used to call a single
function only. But delegate are by default they are multicast delegate, means they can be used
to call multiple functions at a time. Consider a function,

void PrintAddress(string Address)

Response.Write("City he lives is "+Address);

The below code will explain how to call PrintName and PrintAddress methods using a delegate,

DelegateTest del = new DelegateTest(this.PrintName);

del += new DelegateTest(this.PrintAddress);

del(“Chidambaram”);

So the output will be,

Name is Chidambaram

City he lives is Chidambaram

The other difference between a delegate and a function pointer is, a delegate is type safe, means
it will throw a compilation error if a method with different signature is assigned to the delegate.

Other than the above examples the delegates are used in event handling, for callbacks etc. For
example, if you see the Web form designer code in Visual studio 2003 there will be,

btnCheck.Click += new EventHandler(this.btnCheck_Click);

Here EventHandler is a delegate that is registered with btnCheck_Click event.

Lambda Expressions
C# 3.0 has added the lambda expression. Lambda expressions are an even more compact syntax
for defining anonymous functions (anonymous methods and lambda expressions are collectively
referred to as anonymous functions). The following section of code filters a list of cities as we did
before, but this time using a lambda expression.

string[] cities = { "Boston", "Los Angeles", "Seattle", "London", "Hyderabad" };

IEnumerable<string> filteredList = cities.Where(s => s.StartsWith("L"));

The distinguishing feature in this code is the "goes to" operator (=>). The left hand side of the
=> operator defines the function signature, while the right hand side of the => operator defines
the function body.

You'll notice that the lambda expression doesn't require a delegate keyword.

You'll also notice the function signature doesn't include any type information for the parameter
named

4
Examples

Where : List<Product> products = GetProductList();


int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, var expensiveInStockProducts =
0 };
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, from p in products
0 }; where p.UnitsInStock > 0 && p.UnitPrice
var lowNums = > 3.00M
from n in numbers select p;
where n < 5
select n;

DataTable contacts = Select


ds.Tables["Contact"];
IEnumerable<DataRow> query = var productNames =
from contact in from p in products
contacts.AsEnumerable() select p.ProductName;
orderby
contact.Field<string>("LastName")
select contact;

string[] words = { "aPPLE", "BlUe", DataTable products = ds.Tables["Product"];


"cHeRry" }; IEnumerable<DataRow> query =
var upperLowerWords = from product in products.AsEnumerable()
from w in words select product;
select new { Upper = w.ToUpper(),
Lower = w.ToLower() };

DataTable contacts = Group By


ds.Tables["Contact"];
DataTable orders = List<Product> products = GetProductList();
ds.Tables["SalesOrderHeader"]; var orderGroups =
var query = from p in products
from contact in group p by p.Category into g
contacts.AsEnumerable() select new { Category = g.Key,
from order in orders.AsEnumerable() Products = g };
where contact.Field<int>("ContactID")
==
order.Field<int>("ContactID")
&& order.Field<decimal>("TotalDue")

5
< 500.00M Distinct
select new
{ List<Product> products = GetProductList();
ContactID = var categoryNames = (
contact.Field<int>("ContactID"), from p in products
LastName = select p.Category)
contact.Field<string>("LastName"), .Distinct();
FirstName
=contact.Field<string>("FirstName"),
OrderID =
order.Field<int>("SalesOrderID"),
Total =
order.Field<decimal>("TotalDue")
};

Average Join

var products = var orders =


ds.Tables["Product"].AsEnumerable(); ds.Tables["SalesOrderHeader"].AsEnumerab
var query = from product in products le();
group product by var details =
product.Field<string>("Styl ds.Tables["SalesOrderDetail"].AsEnumerabl
e") into g e();
select new var query =
{ from order in orders
Style = g.Key, join detail in details
AverageListPrice = on order.Field<int>("SalesOrderID")
g.Average(product => equals detail.Field<int>("SalesOrderID")
product.Field<Decimal>("ListPr into ords
ice")) select new
}; {
CustomerID =
order.Field<int>("SalesOrderID"),
ords = ords.Count()
};

Design Pattern
Design patterns can help solve complex design problems if they are properly used. The main
advantage of using the Model-View-Control (MVC) pattern is decoupling the business and the
presentation layers.
Figure 1: The MVC Architectural Components

6
MVC Architectural Components
The MVC design pattern is comprised of three major components.
1. The Model (The Data Layer):
The model object knows about all the data that need to be displayed. It is model who is
aware about all the operations that can be applied to transform that object. It only
represents the data of an application. The model represents enterprise data and the
business rules that govern access to and updates of this data. Model is not aware about
the presentation data and how that data will be displayed to the browser.
2. The View (The User Interface Layer)
The view represents the presentation of the application. The view object refers to the
model. It uses the query methods of the model to obtain the contents and renders it. The
view is not dependent on the application logic. It remains same if there is any
modification in the business logic. In other words, we can say that it is the responsibility
of the of the view's to maintain the consistency in its presentation when the model
changes.
3. The Controller (The Business Logic Layer)
Whenever the user sends a request for something then it always go through the
controller. The controller is responsible for intercepting the requests from view and
passes it to the model for the appropriate action. After the action has been taken on the
data, the controller is responsible for directing the appropriate view to the user. In GUIs,
the views and the controllers often work very closely together.

Advantages of MVC Pattern


The main objective of the MVC design pattern is separation of concerns. It provides an
isolation of the application’s presentation layer that displays the data in the user interface,
from the way the data is actually processed. In other words, it isolates the application's data

7
from how the data is actually processed by the application’s business logic layer. The biggest
advantage of the MVC design pattern is that you have a nice isolation of these
components/layers and you can change any one of them without the rest being affected.
Here is the list of the major advantages of this pattern.
· It provides a clean separation of concerns. · It is easier to test code that implements this
pattern. · It promotes better code organization, extensibility, scalability and code re-use. · It
facilitates de-coupling the application's layers.

Disadvantages of MVC Pattern


Even if this pattern comes with a lot of advantages, there are distinct disadvantages too.
Firstly, it is too complex to implement and is not suitable for smaller application; rather,
implementing this pattern in such applications will have adverse effects in the application's
performance and design. In this regard, the MSDN states, "You are building a Web
application in Microsoft ASP.NET, and, based on the complexity of your application, you need
to separate different aspects of the program to reduce code duplication and to limit the
propagation of change." This is where this design pattern fits in.
Site: http://www.dotnetjohn.com/articles.aspx?articleid=287
Generics
Generic helps us to maximize the reuse of code, Type safety and better performance

Why Generics Term Came?

Generics provide the solution to a limitation in earlier versions of the common language runtime
and the C# language in which generalization is accomplished by casting types to and from the
universal base type Object.

Benefits Of Generics

By creating a generic class, you can create a collection that is type-safe at compile-time.

By allowing you to specify the specific types acted on by a generic class or method, the generics
feature shifts the burden of type safety from developer to the compiler. There is no need to write
code to test for the correct data type, because it is enforced at compile time. The need for type
casting and the possibility of run-time errors are reduced

They are cheaper in performance because they run much faster than ArrayLists. They are
cheaper in development time because there's no more boxing and unboxing. They are cheaper
stress wise because I no longer have to go through the nightmare of resizing an array in C#
because it grew dynamically.

Generic Classes

Generic classes encapsulate operations that are not specific to any particular data type. The
most common use for generic classes is with the collections like linked lists, hash tables, stacks,
queues, trees and so on where operations such as adding and removing items from the collection
are performed in more or less the same way regardless of the type of the data being stored.

public class Node <T>

T head;

8
T next;

Here, T is the type parameter. We can pass any data type as parameter.

This class can be instantiated like this:

Node<string> node = new Node<string>();This will tell the compiler that the properties, head
and next are of type string. Instead of string, you can substitute this with any data type.

Generic Methods

A generic method is a method that is declared with a type parameter.

void Swap<T>( ref T left, ref T right)

T temp;

temp = left;

left = right;

right = temp;

The following code example shows how to call the above method:

int a = 1;

int b = 2;

Swap <int> (a, b);

You can also omit the type parameter because the compiler will automatically identify it for you.
The following is also a valid call to the same method:

Swap (a, b);

Generic Constraints

In working with Generic classes, particularly collections, you will soon encounter situations where
you will want to restrict the possible types that the generic class will accept. You may need to
ensure that your collection only accepts reference types, not value types. Or, you may need to
make sure that the object derives from another class or implements a particular interface such as
IComparable<T>. To do this, you would use what is called a Constraint.

The example presented here makes use of a CustomUserList Collection class that will only accept
types that are reference types (a class, not a struct), and that implement IComparable<T> and
IEnumerable<T>. I will present both the collection class, the object type that it can hold, and
provide a Windows Forms test harness that will allow you to add test items and will show you the
list.

9
Here is the signature of the class:
public class CustomUserList<T> where T: class, IComparable<T>, IEnumerable<T>

Association, Aggregation, Composition


Association is a relationship where all object have their own lifecycle and there is no owner.
Let’s take an example of Teacher and Student. Multiple students can associate with single
teacher and single student can associate with multiple teachers but there is no ownership
between the objects and both have their own lifecycle. Both can create and delete
independently.

Aggregation is a specialize form of Association where all object have their own lifecycle but
there is ownership and child object cannot belongs to another parent object. Let’s take an
example of Department and teacher. A single teacher cannot belongs to multiple departments,
but if we delete the department teacher object will not destroy. We can think about “has-a”
relationship.
Composition is again specialize form of Aggregation and we can call this as a “death”
relationship. It is a strong type of Aggregation. Child object dose not have their lifecycle and if
parent object deletes all child object will also be deleted. Let’s take again an example of
relationship between House and rooms. House can contain multiple rooms there is no
independent life of room and any room can not belongs to two different house if we delete the
house room will automatically delete. Let’s take another example relationship between Questions
and options. Single questions can have multiple options and option can not belong to multiple
questions. If we delete questions options will automatically delete.

/w EWCALM26ykD

Serialization in .NET

Introduction
Serialization is a process of taking an object and converting into a form so that it can be
transported across the network or can be persisted in the storage location. This storage location
can be physical file, database or ASP.NET Cache. The form contains the state of the object so
that by this format, we can construct the same object a later point in time, which is called
Deserialization.

There are three formats of serialization

Binary Serialization : Light andcompact used in Remoting

SOAP Serialization :interoperableuse SOAP and used in web Services

XML Serialization :Custom Serialization

XMLSerialization

For XML serialization, you need touse the attributes and specifythem for each and every public
member that youneed. But since it is limited that it can serialize only public members,Serization
done by it is called custom serialization. It is also known as Shallow Serialization

SOAP and Binary Serialization

10
XML serializes only public members of the class. You use SOAP or Binary serialization when you
need to transport data across the network. SOAP sends it using HTTP Protocol which makes it
mostinter operable while Binary serialization is known for its light and compact nature.Web
Services uses the SOAP Serialization and Remoting uses the Binary Serialization. Infact
Serialization is always neccessary when you need the object to transfer across a network.
Advantage of using the SOAP or Binary serialization is that you can serialize the entire object and
all those object that are being refrenced by it. This is why it is also called Deep Serialization. If
you want any class to serialize through any ofthese methods then you should use [Serializable]
attribute on that class and then you can use the Soap Formater class or Binary Formatter class
to do the serialization. These classes have Serialize and DeSerialize method. If you will not use
Serializable Attribute for the class, then it will raise the exception.

Though this is the easiest way but at time you need the way so that you can decide what
fields to serialize and howthe serialization actually occurs. You can implement the
ISerializable interfacein the class. You need two things for that

1. Constructorthat is overridden and can handle the Deserialization process


2. GetObjectmethod that tracks about which data is serialized.
A small example below illustrate this all.

publicclass Employee :ISerializable

privateint emp_no;

privatestring name;

protectedTestData(SerializationInfo info,StreamingContextcontext)
{
this.emp_no =info.GetInt32("emp_no");
this.name =info.GetString("name");
}

voidISerializable.GetObjectData(SerializationInfoinfo,

StreamingContextcontext)
{
info.AddValue("emp_no",this.emp_no);
info.AddValue("name",this.name);
}

11
New features of .net 4.0

• Adding MetaKeyword and MetaDescription Using Page object


• More Control on Controls ViewState

This property can take 3 values,


1. Enabled
This value will enable the view state. This is the default value for the Page object.
2. Disabled
This value will disable the viewstate
3. Inherit

• ClientID Generation for ASP.Net Controls


This property will take the following 4 values,
1. Static
Setting this value will make the ClientID same as the ID. It will not concatenate ID
of the parent naming containers.
2. Predictable
This will be useful to predict the ClientID of child controls in data controls. Setting
this property will prevent the “ctlxxx” prefix in the ClientID. We will see more
about this value later in this section.
3. Legacy
This value will make the ClientID generation same as earlier versions of ASP.Net
4. Inherit
This value will make the control to inherit the parent control’s setting. This is
the default value for this property.

• Improvements in Code Expressions


<%: HTMLOutput %> is equivalent to <%= HttpUtility.HtmlEncode(HTMLOutput) %>
• Simplified Web.Config File
One of the most striking features in ASP.NET 4.0 is web.config minification – a feature that
allows you to have a web.config file that is much smaller in size with fewer configuration
elements compared to what we used to have in the earlier versions of ASP.NET. Most of
the configuration elements now have been moved to the machine.config file resulting in a
minified web.config file for your applications. Your applications can easily inherit the
settings specified in the machine.config file. So, you can have a web.config file that is
either empty or, much smaller in size. Here is how you can specify the target framework
for your application’s web.config file in ASP.NET 4.0:–
<?xml version="1.0"?><configuration><system.web><compilation
targetFramework="4.0" /></system.web></configuration>
• Session State Improvements
In ASP.NET 4.0 you can use compression for out of process session state providers. Here
is what you need to use this feature:<sessionState mode=”SqlServer”
sqlConnectionString=”data source=joydip; Initial Catalog=aspnetstate”
allowCustomSqlDatabase=”true” compressionEnabled=”true”/>
JQuery

jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event
handling, animating, and Ajax interactions for rapid web development. jQuery is designed to
change the way that you write JavaScript.

12
$("p.neat").addClass("ohmy").show("slow");

$(document).ready(function(){

$("a").click(function(event){

alert("Thanks for visiting!");

});

});

Let's have a look at what we are doing: $("a") is a jQuery selector, in this case, it selects all a
elements. $ itself is an alias for the jQuery "class", therefore $() constructs a new jQuery object.
The click() function we call next is a method of the jQuery object. It binds a click event to all
selected elements (in this case, a single anchor element) and executes the provided function
when the event occurs.

add the addClass call to your script:

<style type="text/css">

a.test { font-weight: bold; }

</style>

$("a").addClass("test"); //All your a elements will now be bold.

$("a").click(function(event){ // if you click any link, it should make itself slowly disappear.

event.preventDefault();

$(this).hide("slow");

});

$.get('myhtmlpage.html', myCallBack); // Callback without arguments

Note that the second parameter here is simply the function name (but not as a string and
without parentheses). Functions in Javascript are 'First class citizens' and so can be
passed around like variable references and executed at a later time.

$.get('myhtmlpage.html', function(){// Callback with arguments

myCallBack(param1, param2);

});

jQuery provides two approaches to select elements. The first uses a combination of CSS and
XPath selectors passed as a string to the jQuery constructor (eg. $("div > ul a")). The second
uses several methods of the jQuery object. Both approaches can be combined.

13
Few examples

$("#orderedlist").addClass("red"); //document.getElementById("orderedlist").

$("#orderedlist > li").addClass("blue"); //This selects all child lis of the element with the id
orderedlist and adds the class "blue".

$('#myId'); // note IDs must be unique per page

$('div.myClass'); // Selecting elements by class name , performance improves if you


specify element type

$('input[name=first_name]'); // Selecting elements by attribute, beware, this can be very


slow

$.ajax

$.ajax method is a powerful and straightforward way of creating Ajax requests. It takes a
configuration object that contains all the instructions jQuery requires to complete the
request

$.ajax({

// the URL for the request

url : 'post.php',

// the data to send

// (will be converted to a query string)

data : { id : 123 },

// whether this is a POST or GET request

method : 'GET',

// the type of data we expect back

dataType : 'json',

// code to run if the request succeeds;

// the response is passed to the function

success : function(json) {

$('<h1/>').text(json.title).appendTo('body');

$('<div class="content"/>')

.html(json.html).appendTo('body');

},

// code to run if the request fails;

14
// the raw request and status codes are

// passed to the function

error : function(xhr, status) {

alert('Sorry, there was a problem!');

},

// code to run regardless of success or failure

complete : function(xhr, status) {

alert('The request is complete!');

});

JSON (JavaScript Object Notation) is a lightweight data-interchange format

JSON is built on two structures:

A collection of name/value pairs. In various languages, this is realized as an object,


record, struct, dictionary, hash table, keyed list, or associative array.

An ordered list of values. In most languages, this is realized as an array, vector, list, or
sequence.

JSON, they take on these forms:

• An object is an unordered set of name/value pairs. An object begins with { (left brace)
and ends with } (right brace). Each name is followed by : (colon) and the name/value
pairs are separated by , (comma).
• An array is an ordered collection of values. An array begins with [ (left bracket) and ends
with ] (right bracket). Values are separated by , (comma).
• A value can be a string in double quotes, or a number, or true or false or null, or an object
or an array. These structures can be nested
• A string is a collection of zero or more Unicode characters, wrapped in double quotes,
using backslash escapes. A character is represented as a single character string. A string
is very much like a C or Java string
• A number is very much like a C or Java number, except that the octal and hexadecimal
formats are not used.
To convert a JSON text into an object, you can use the eval() function. eval() invokes the
JavaScript compiler. Since JSON is a proper subset of JavaScript, the compiler will correctly
parse the text and produce an object structure
What is JSON?
• Lightweight data-interchange format
> Compared to XML
• Simple format
> Easy for humans to read and write
> Easy for machines to parse and generate
• JSON is a text format

15
> Programming language independent
> Uses conventions that are familiar to programmers of the Cfamily of
languages, including C, C++, C#, Java, JavaScript,Perl, Python6
Why Use JSON over XML
• Lighter and faster than XML as on-the-wire data format
• JSON objects are typed while XML data is typeless
> JSON types: string, number, array, boolean,
> XML data are all string
• Native data form for JavaScript code
> Data is readily accessible as JSON objects in your JavaScript code vs. XML data
needed to be
parsed and assigned to variables through tedious DOM APIs
> Retrieving values is as easy as reading from an object property in your
JavaScript code

C# boxing and unboxing


C# Type System contains three Types , they are Value Types , Reference Types and Pointer
Types. C# allows us to convert a Value Type to a Reference Type, and back again to Value
Types . The operation of Converting a Value Type to a Reference Type is called Boxing and the
reverse operation is called Unboxing.
Boxing
1: int Val = 1;
2: Object Obj = Val; //Boxing
The first line we created a Value Type Val and assigned a value to Val. The second line , we
created an instance of Object Obj and assign the value of Val to Obj. From the above operation
(Object Obj = i ) we saw converting a value of a Value Type into a value of a corresponding
Reference Type . These types of operation is called Boxing.
UnBoxing
1: int Val = 1;
2: Object Obj = Val; //Boxing
3: int i = (int)Val; //Unboxing
The first two line shows how to Box a Value Type . The next line (int i = (int) Obj) shows extracts
the Value Type from the Object . That is converting a value of a Reference Type into a value of a
Value Type. This operation is called UnBoxing.
Boxing and UnBoxing are computationally expensive processes. When a value type is boxed, an
entirely new object must be allocated and constructed , also the cast required for UnBoxing is
also expensive computationally.

Web services
describes a standardized way of integrating Web-based applications using the XML, SOAP, WSDL and UDDI open
standards over an Internet protocol backbone. XML is used to tag the data, SOAP is used to transfer the data, WSDL
is used for describing the services available and UDDI is used for listing what services are available. Used primarily
as a means for businesses to communicate with each other and with clients, Web services allow organizations to
communicate data without intimate knowledge of each other's IT systems behind the firewall
Unlike traditional client/server models, such as a Web server/Web page system, Web services do not provide the
user with a GUI. Web services instead share business logic, data and processes through a programmatic interface
across a network. The applications interface, not the users. Developers can then add the Web service to a GUI (such
as a Web page or an executable program) to offer specific functionality to users.
Web services allow different applications from different sources to communicate with each other without time-
consuming custom coding, and because all communication is in XML, Web services are not tied to any one operating

16
system or programming language. For example, Java can talk with Perl, Windows applications can talk with UNIX
applications.Web services do not require the use of browsers or HTML.Web services are sometimes called
application services.

Windows Communication Foundation (WCF)


Windows Communication Foundation (WCF) is a dedicated communication framework provided by Microsoft.
WCF is a part of .NET 3.0. The runtime environment provided by the WCF enables us to expose our CLR types as
services and to consume other existing services as CLR types.

Background:
In the world there are a lot of distributed communication technologies that exist. Some of them are:
• ASP.NET Web Services (ASMX)
• Web Services Enhancements (WSE)
• Messaging (MSMQ)
• .NET Enterprise Services (ES)
• .NET Remoting

Creating and Consuming a Sample WCF Service:

Three major steps are involved in the creation and consumtion of the WCF services. Those
are:
1. Create the Service.(Creating)
2. Binding an address to the service and host the Service. (Hosting)
3. Consuming the Service.(Consuming)

Step 1: Creating the Service

In WCF, all services are exposed as contracts. A contract is a neutral way of describing what
the service does. Mainly we have four types of contracts:
1. Service Contract

This contract describes all the available operations that a client can perform on the
service.

.Net uses "System.ServiceModel" Name space to work with WCF services.

17
ServiceContract attribute is used to define the service contract. We can apply this
attribute on class or interface. ServiceContract attribute exposes a CLR interface (or
a class) as a WCF contract.

OperationContract attribute, is used to indicate explicitly which method is used to


expose as part of WCF contract. We can apply OperationContract attribute only on
methods, not on properties or indexers.

[ServiceContract] applies at the class or interface level.


[OperatiContract] applies at the method level.

2. Data Contract

This contract defines the data types that are passed into and out of the service.

[DataContract] attribute is used at the custom data type definition level, i.e. at class
or structure level.
[DataMember] attribute is used for fields, properties, and events.

3. Fault Contract

This contract describes about the error raised by the services.

[FaultContract(<<type of Exception/Fault>>)] attribute is used for defining the fault


contracts.

4. Message Contracts

This contract provides the direct control over the SOAP message structure. This is
useful in inter-operability cases and when there is an existing message format you
have to comply with.

[MessageContract] attribute is used to define a type as a Message type.


[MessageHeader] attribute is used for those members of the type we want to make
into SOAP headers
[MessageBodyMember] attribute is used for those members we want to make into
parts of the SOAP body of the message.
STEP 2: Binding and Hosting

Each service has an end point. Clients communicates with this end points only. End point
describes 3 things :
1. Address
2. Binding type
3. Contract Name (which was defined in STEP 1)

18
Address

Every service must be associated with a unique address. Address mainly contains the
following two key factors :
1. Transport protocal used to communicate between the client proxy and service.

WCF supports the following transport machinisams:

○ HTTP (ex : http:// or https:// )


○ TCP (ex : net.tcp :// )
○ Peer network (ex: net.p2p://)
○ IPC (Inter-Process Communication over named pipes) (ex: net.pipe://)
○ MSMQ (ex: net.msmq://)

2. Location of the service.

Location of the service describes the targeted machine (where service is hosted)
complete name (or) path and optionally port / pipe /queue name.
Example : localhost:8081
Here local host is the target machine name.
8081 is the optional port number.
Example 2: localhost
This is with out optional parameter.
Here are a few sample addresses:
http://localhost:8001
http://localhost:8001/MyFirstService
net.tcp://localhost:8002/MyFirstService
net.pipe://localhost/MyFirstPipe
net.msmq://localhost/MyFirstService

Binding is nothing but a set of choices regarding the transport protocol (which transport
protocal we have to use : http /tcp /pipe etc.) ,message encoding (tells about the message
encdong / decoidng technique) ,communication pattern (whether communication is
asynchronous, synchronous, message queued etc.) , reliability, security, transaction
propagation, and interoperability.

WCF defines the nine basic bindings

19
Binding .Net Class Transport Encoding Inter Comments
Type implements this operable
binding
Basic BasicHttpBinding Http / Text / Yes Used to expose a WCF
Binding Https MTOM service as a legacy
ASMX web service.
TCP NetTcpBinding TCP Binary NO TCP is used for cross-
binding machine communication
on the intranet.
Peer NetPeerTcpBinding P2P Binary NO In this peer network
network transport schema is
binding used to communicate.
IPC NetNamedPipeBinding IPC Binary NO This uses named pipes
binding as a transport for
same-machine
communication. It is
the most secure binding
since it cannot accept
calls from outside the
machine.
WSbinding WSHttpBinding Http / Text / Yes This uses Http / Https
Https MTOM as a communication
schema.
Federated WSFederationHttpBindin Http / Text / Yes This is a specialization
WS g Https MTOM of the WS binding. This
binding offers the support for
federated security
Duplex WS WSDualHttpBinding Http Text / Yes This is a WS binding
binding MTOM with bidirectional
communication support
from the service to the
client.
MSMQ NetMsmqBinding MSMQ Binary NO This supports for
binding disconnected queued
calls
MSMQ MsmqIntegrationBinding MSMQ Binary Yes This is designed to
integration interoperate with legacy
binding MSMQ clients.

Hosting:
Every service must be hosted in a host process. Hosting can be done by using the
• IIS
• Windows Activation Service (WAS)
• Self hosting

Hostin Advantages Limitations


g Type
IIS IIS manages the life cycle of host Only HTTP transport schemas WCF

20
Hosting process. ( like application pooling, service are hosted in IIS.
recycling, idle time management, identity
management, and isolation)
WAS • WAS supports for all available Some adv of self hosted processing is
Hosting missing.
WCF transports, ports, and
queues.
• WAS manages the life cycle of
host process.
Self • Missing the host process life cycle
Developer can have explicit
Hosting management.
control over opening and closing
the host.
• In-Proc hosting can be done.

IIS Hosting

IIS hosting is the same as hosting the traditional web service hosting. Create a virtual
directory and supply a .svc file.

In the solution explorer, under the App_code folder you can find the two files: "IService.cs"
and "Service.cs".
"IService.cs" class file defines the contracts. "Service.cs" implements the contracts defined
in the "IService.cs". Contracts defined in the "IService.cs" are exposed in the service.

Check in the Web.Config file, under <system.serviceModel> section:

Consuming WCF Service Hosted by IIS/WAS

Consuming WCF service is a very similar way of consuming a web service by using the
proxy. To consume the service, in the solution explorer click on "Add service Reference" and
add the service created in the STEP1.

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

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

Windows Communication Foundation (WCF) ASP.NET Web Service


WCF supports multiple bindings HTTP, WSHTTP, TCP, MSMQ. ASP.NET Web Services
supports only HTTP
binding.
WCF supports Atomic Transactions*. ASP.NET Web Services
does not support
Atomic Transactions*.
By default WCF uses SOAP for sending and receiving the messages. ASP.NET Web Services
But WCF can support any kind of message format not only SOAP. can send and receive
messages via the SOAP
only.
The System.Runtime.Serialization.DataContract and ASP.NET Web Services
System.Runtime.Serialization.DataMember attributes of the WCF's uses XmlSerializer to
System.Runtime.Serialization assembly can be added for .NET translate the XML data
types to indicate that instances of the type are to be serialized into (Message Send or
XML, and which particular fields or properties of the type are to be received) into .NET
serialized. objects.

What is AJAX?

AJAX, or Asynchronous JavaScript and XML, is a fancy way to use JavaScript and XML to
communicate with a web server without refreshing the web page. You can visit this web
page for more information about AJAX; it has a good list of links.
Why use AJAX?

There are a couple of reasons to use AJAX in lieu of the traditional form submission. The
first is that it is very light weight: instead of sending all of the form information to the
server and getting all of the rendered HTML back, simply send the data the server needs to
process and get back only what the client needs to process. Light weight means fast. The

22
second reason to use AJAX is because (as the logo in the link above makes clear) AJAX is
cool.

Using AJAX with ASP.NET

Even though AJAX is a client side technology that uses JavaScript, the client-server
interaction is very important.

Difference between structures and classes


1. The structures are value types and the classes are reference types. Before stepping
to the next point let explain the difference between the two types. Imagine this is
the memory within the machine

Figure 1

The value types are stocked in the stack but the reference type no. In fact, what
could be really stocked in the stack for the reference types is a pointer that targets
an address at the heap level.

Then type of structure objects are stocked in the stack exactly like any value type
say an Integer, a double or a float. Meanwhile, memory emplacements could be
reserved for the reference types in the heap. Defining heap and stack and the
difference between them is beyond the scope of this article but nevertheless I
propose this excellent Matthew article to understand the memory mechanism.

2. Classes are usually used for large amounts of data, whereas structs are usually used
for smaller amount of data
3. Classes could be inherited whereas structures no
4. A structure couldn't be Null like a class
5. A structure couldn't have a destructor such as class
6. A structure can't be abstract, a class can
7. You cannot override any methods within a structure except those belong to type of
object

○ Equals()
○ GetHashCode()
○ GetType()

23
○ ToString()
And the other polymorphism technique used for structures is implementing interfaces
8. Declared events within a class are automatically locked and then they are Thread
safe, at the contrast of the structure type where event couldn't be locked.
9. A structure must have always the default parameter less constructor be defined as
public but a class might have one, so you can't define a private parameter less
constructor

struct Me class Me
{ {
private Me() // compile-time error private Me() // runs Ok{
{ }
}
}

10. A static constructor is trigged in case of class but not in case of structure

struct myStructure class Program


{ {
static myStructure() static void Main(string[] args)
{ {
Console.WriteLine("This is me a myStructure s = new
structure"); myStructure();//Nothing happen
} myClass c = new myClass();//Will
}
out put This is me a class
class myClass
Console.Read();
{ }
static myClass() }
{
Console.WriteLine("This is
me a class");
}
}

11. The strucutre can't conatain a volatile field wheatheas the class does
12. You can't use sizeof with classes but you can with structures
13. Fields are automatically initialized with classes to 0/false/null wheatheras in
strucutres no
14. Fields couldn't directley instanciated within structures but classes allow such
operations

struct myStructure class myClass


{ {

24
public string x = 2;//Not allowed public string x = 2; //Allowed
} }

15. Structure and class don't adopt the same aproach taward the
System.Object.Equals() method

Suppose those Strucutre and class

struct StructurePerson
{
public string FirstName;
public string LastName;
}
class ClassPerson
{
public string FirstName;
public string LastName;
}
Now, try this code

class Program
{
static void Main(string[] args)
{
StructurePerson strX = new StructurePerson();
strX.LastName = "Bejaoui";
strX.FirstName = "Bechir";
StructurePerson strY = new StructurePerson();
strY.LastName = "Bejaoui";
strY.FirstName = "Bechir";
if (strX.Equals(strY))
{
Console.WriteLine("strX = strY");
}
else
{
Console.WriteLine("strX != strY");
}//This code displays strX = strY

ClassPerson clsX = new ClassPerson();


clsX.LastName = "Bejaoui";
clsX.FirstName = "Bechir";
ClassPerson clsY = new ClassPerson();
clsY.LastName = "Bejaoui";
clsY.FirstName = "Bechir";

if (clsX.Equals(clsY))
{

25
Console.WriteLine("clsX = clsY");
}
else
{
Console.WriteLine("clsX != clsY");
}//This code displays clsX != clsY
Console.Read();
}
}

In the first strucutre case the two objects are value types, they are compared
according to their values like int I = 5 and int J = 5 so I=J because they have
the same value. At the contrast, in the class case two different and distinct
reference are created so to make clsX = clsY you should use this code.

ClassPerson clsX = new ClassPerson();


clsX.LastName = "Bejaoui";
clsX.FirstName = "Bechir";
ClassPerson clsY = clsX;
if (clsX.Equals(clsY))
{
Console.WriteLine("clsX = clsY");
}
else
{
Console.WriteLine("clsX != clsY");

}//This code displays clsX = clsY

Abstraction Vs Encapsulation
Abstraction means hiding the internal details and just exposing the functionality.
For Example:-When you change the gear of your car, you know the gears will be
changed without knowing how they are functioning internally.Abstraction focuses on
the outside view of an object (i.e. the interface)

Encapsulation means put the data and the function that operate on that data in a
single unit(information hiding) .Encapsulation prevents clients from seeing its inside
view, where the behavior of the abstraction is implemented.

Difference between the store procedure and function

26
1. the store procedure can not be execute with the select command while function execute
with the select command you can execute the store procedure with the execute
statement
2. you can not apply the crud operation on the function while this my be apply on sql
3. there are two type in function deterministic and undeterministic you can not return the
value with the deterministic function

Windows Services
As a matter of fact Microsoft windows services, formerly known as NT services enable you to
create long-running executable applications that run in its own windows session, which then has
the ability to start automatically when the computer boots and also can be manually paused,
stopped or even restarted.
This makes services ideal for use on a server or whenever you need long-running functionality
that does not interfere with other users who are working on the same computer. You can also run
services in the security context of a specific user account that is different from the logged-on user
or the default computer account.
windows services dont have any interface to the user, so it can not be debugged like any regular
application, but its debugged as a process. .Net has a very nice tool that enables processes
debugging while its in the run status, by easily pressing Ctrl + Alt + P shortcut.
Caching
ASP.NET 2.0 caching in one of the best way to improve the performance of a Web application.
By taking advantage of caching we can dramatically improve the performance of web
applications.

Opening a database connection and retrieving the data from the database may be a time and
resource consuming operation. However, for every page refresh or data view, we do not have to
open and close the database connection if we can store data in memory and not hit the database
until the data update operation.

By taking the advantage of caching, we can retrieve and cache our data in memory and
everytime our application needs data, we get from the cache, not go to the database. By applying
this theory in practice, we can singnificantly improve the performance of our data access and
hence the application.
Why caching?
Retrieving data from a database is one of the slowest Web site operations.

Every time the page requests for data, it has to go through "client->server->database->server-
>client" cycle, which is very time consuming. Time taken might increase as per the data density
and in turn affect the performance.
It will be more pathetic when multiple users access a Web site simultaneously. Now this is where
"caching" comes into picture.
So if the database data is cached in memory and database-access with every page request is
avoided, the performance of your application increases.
Different types of caching:

27
ASP.Net provides three basic types of caching:
• Page level output caching
• Fragment caching
• Data Caching
Page level output caching:
Page caching is mainly used for static pages, where the contents does not change. Output caching
has the advantage of being incredibly simple to implement, and are sufficient in many cases.
This technique caches the output of a page so that content of pages are not generated every time
it is loaded. Output caching simply keeps a copy of the HTML that was sent in response to a
request in memory. In this case the subsequent requests are severed with the cached out until
cache expires. This gives a great performance increase of web application.
Just add the OutputCache directive to the page you wish to cache.
for eg. <%@ OutputCache Duration="30" VaryByParam="none" %>
Code snippet:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Sample.aspx.cs"
Inherits="Sample" %>

<%@ OutputCache Duration="10" VaryByParam="none"%>


Date time:
<% DateTime t = DateTime.Now;
Response.Write(t.ToString()); %>

This page is cached for 10 seconds. When this page was last cached the date/time was 1/1/2009
11:27:27 AM. When you refresh repeatedly this time remains constant until the cache is expired,
then it is updated to the current time. So after 10 seconds, you can get the current time. This is
because, ASP.Net caches the HTML using Output Caching.

Page Fragment Caching:

This type of technique is used when we need to cache only a part(or rather Fragment) of page
instead of the whole page. Suppose, if we need to cache only header of a page, then instead of
caching the whole page, its better to cache only header.

When you login to a website, you might find your name on the header. This happens with all the
users. So header has to be stored in cache till he logs out. So the header has to be an user control.
Fragment caching is applied to this user control.

Just add the OutputCache directive to the user control page you wish to cache.
for eg. <%@ OutputCache Duration="30" VaryByControl="Header1" %>

This will cache Header1 for 30 seconds


Data Caching:
Data caching is also called Application caching. It is much more powerful than the other two
caching options. It caches data as objects and its scope is as that of the application. Here, an item

28
is cached under a name , then extract it with the same name when required. Data caching is done
using "cache" class.
Data caching is done in this way:
Cache["ID"] = EmployeeID;
Here EmployeeID is cached under "ID" key.
Now while extracting,
EmployeeID = Cache["ID"];
Where does cached data gets stored?
The location for cached data can be specified in OutputCache directive.
• Any - This stores the output cache in the client's browser, on the proxy server (or any
other server) that participates in the request, or on the server where the request is
processed. By default, Any is selected.
• Client Caching - This stores output cache in the client's browser.
• Downstream - This stores the output cache in any cache-capable devices that participate
in the request. To store the output cache on any HTTP 1.1 cache-capable devices
including the proxy servers and the client that made request.
• Web Server Caching - This stores the output cache on the Web server.
• None - Output caching is deactivated.
Partial Class
Partial class is a new feature added to C# 2.0 and Visual Studio 2005. It is supported in .NET
Framework 2.0. If you are working with .NET 1.0 or 1.1, partial classes may not work.

It is possible to split the definition of a class or a struct, or an interface over two or more source
files. Each source file contains a section of the class definition, and all parts are combined when
the application is compiled.

When working on large projects, spreading a class over separate files allows multiple
programmers to work on it simultaneously.

When working with automatically generated source, code can be added to the class without
having to recreate the source file. Visual Studio uses this approach when creating Windows
Forms, Web Service wrapper code, and so on. You can create code that uses these classes
without having to edit the file created by Visual Studio.

Benefit of partial classes:

1) More than one developer can simultaneously write the code for the class.

2) You can easily write your code (for extended functionality) for a VS.NET generated class.
This will allow you to write the code of your own need without messing with the system
generated code.

29
There are a few things that you should be careful about when writing code for partial classes:
• All the partial definitions must proceeded with the key word "Partial".
• All the partial types meant to be the part of same type must be defined within a same
assembly and module.
• Method signatures (return type, name of the method, and parameters) must be unique for
the aggregated typed (which was defined partially).
• The partial types must have the same accessibility.
• If any part is sealed, the entire class is sealed.
• If any part is abstract, the entire class is abstract.
• Inheritance at any partial type applies to the entire class.
Abstract class
Abstract class is an incomplete class or special class we can't instantiated. We can us this
Abstract class as a Base Class. Abstract method must implement on the non-Abstract class by
using override keyword. After override abstract method in the non-Abstract class. We can
derived this class into antoher class and again we can override same abstract method with it.

Features:
1. An abstract calss can inherit from a class and one or more interfaces.
2. An abstract class can implement code with non-Abstract methods.
3. Abstract class can have modifiers for methods,properties etc.,
4. Abstract class can have constant and fields.
5. An abstract class can implement a property.
6. An abstract class can have constructors or destructors.
7. An abstract class cannot be inherited from by structures.
8. An abstract class cannot support multiple inheritance.
An Abstract class without any implementation just looks like an Interface; however there are lot
of differences than similarities between an Abstract class and an Interface. Let's explain both
concepts and compare their similarities and differences.
What is an Abstract Class?
An abstract class is a special kind of class that cannot be instantiated. So the question is why we
need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited
from). In other words, it only allows other classes to inherit from it but cannot be instantiated.
The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a
kind of contract that forces all the subclasses to carry on the same hierarchies or standards.
http://www.codeproject.com/KB/cs/jmabstractclasses.aspx
using System;

namespace abstractSample
{

30
//Creating an Abstract Class
abstract class absClass
{
//A Non abstract method
public int AddTwoNumbers(int Num1, int Num2)
{
return Num1 + Num2;
}

//An abstract method, to be


//overridden in derived class
public abstract int MultiplyTwoNumbers(int Num1, int Num2);
}

//A Child Class of absClass


class absDerived:absClass
{
[STAThread]
static void Main(string[] args)
{
//You can create an
//instance of the derived class

absDerived calculate = new absDerived();


int added = calculate.AddTwoNumbers(10,20);
int multiplied = calculate.MultiplyTwoNumbers(10,20);
Console.WriteLine("Added : {0},
Multiplied : {1}", added, multiplied);
}

//using override keyword,


//implementing the abstract method
//MultiplyTwoNumbers
public override int MultiplyTwoNumbers(int Num1, int Num2)
{
return Num1 * Num2;
}
}

}
What is an Interface?
An interface is not a class. It is an entity that is defined by the word Interface. An interface has
no implementation; it only has the signature or in other words, just the definition of the methods
without the body. As one of the similarities to Abstract class, it is a contract that is used to define

31
hierarchies for all subclasses or it defines specific set of methods and their arguments. The main
difference between them is that a class can implement more than one interface but can only
inherit from one abstract class. Since C# doesnt support multiple inheritance, interfaces are used
to implement multiple inheritance.
Both Together
When we create an interface, we are basically creating a set of methods without any
implementation that must be overridden by the implemented classes. The advantage is that it
provides a way for a class to be a part of two classes: one from inheritance hierarchy and one
from the interface.
When we create an abstract class, we are creating a base class that might have one or more
completed methods but at least one or more methods are left uncompleted and declared abstract.
If all the methods of an abstract class are uncompleted then it is same as an interface. The
purpose of an abstract class is to provide a base class definition for how a set of derived classes
will work and then allow the programmers to fill the implementation in the derived classes.
There are some similarities and differences between an interface and an abstract class that I have
arranged in a table for easier comparison:
Feature Interface Abstract class

Multiple inheritance A class may inherit several A class may inherit only one
interfaces. abstract class.
Default implementation An interface cannot provide An abstract class can provide
any code, just the signature. complete, default code and/or
just the details that have to be
overridden.
Access Modfiers An interface cannot have An abstract class can
access modifiers for the contain access modifiers
subs, functions, for the subs, functions,
properties etc everything properties
is assumed as public

Core VS Peripheral Interfaces are used to define An abstract class defines the
the peripheral abilities of a core identity of a class and
class. In other words both there it is used for objects of
Human and Vehicle can the same type.
inherit from a IMovable
interface.
Homogeneity If various implementations If various implementations
only share method signatures are of the same kind and use
then it is better to use common behaviour or status
Interfaces. then abstract class is better to
use.
Speed Requires more time to find Fast
the actual method in the

32
corresponding classes.
Adding functionality If we add a new method to an If we add a new method to an
(Versioning) Interface then we have to abstract class then we have
track down all the the option of providing
implementations of the default implementation and
interface and define therefore all the existing code
implementation for the new might work properly.
method.
Fields and Constants No fields can be defined An abstract class can
in interfaces have fields and
constrants defined

Difference between SQL SERVER 2000 and2005


1. The most significant change is the .NET integration with SQL SERVER 2005. Stored
procedures, User-defined functions, triggers, aggregates, and user-defined types can now
be written using your own favorite .NET language(VB.NET, C#, J# etc .). This support
was not there in SQL SERVER2000 where the only language was T-SQL. In SQL 2005
you have support for two languages T-SQL and .NET.
2. SQL SERVER 2005 has reporting services for reports which is a newly added feature and
does not exist for SQL SERVER 2000.It was a separate installation for SQL Server 2000
3. SQL SERVER 2005 has introduced two new data types varbinary (max) and XML. If you
remember in SQL SERVER 2000 we had image and text data types. Problem with image
and text data types is that they assign same amount of storage irrespective of what the
actual data size is. This problem is solved using varbinary (max) which acts depending on
amount of data. One more new data type is included "XML" which enables you to store
XML documents and also does schema verification. In SQL SERVER 2000 developers
used varchar or text data type and all validation had to be done programmatically
4. Other than Serializable, Repeatable Read, Read Committed and Read Uncommitted
isolation level there is one more new isolation level “Snapshot Isolation level”.
5. SQL SERVER 2005 can now process direct incoming HTTP request with out IIS web
server. Also stored procedure invocation is enabled using the SOAP protocol
6. In SQL SERVER 2000 if you rebuilt clustered indexes even the non-clustered indexes
where rebuilt. But in SQL SERVER 2005 building the clustered indexes does not built the
non-clustered indexes
7. Bulk data uploading in SQL SERVER 2000 was done using BCP (Bulk copy program’s)
format files. But now in SQL SERVER 2005 bulk data uploading uses XML file format.
8. In SQL SERVER 2000 there where maximum 16 instances, but in 2005 you can have up
to 50 instances.

What is Encapsulation ?
• Encapsulation is one of the fundamental principles of object-oriented programming.

• Encapsulation is a process of hiding all the internal details of an object from the outside world

33
• Encapsulation is the ability to hide its data and methods from outside the world and only
expose data and methods that are required

• Encapsulation is a protective barrier that prevents the code and data being randomly accessed
by other code or by outside the class

• Encapsulation gives us maintainability, flexibility and extensibility to our code.

• Encapsulation makes implementation inaccessible to other parts of the program and protect
from whatever actions might be taken outside the function or class.

• Encapsulation provides a way to protect data from accidental corruption

• Encapsulation hides information within an object

• Encapsulation is the technique or process of making the fields in a class private and providing
access to the fields using public methods

• Encapsulation gives you the ability to validate the values before the object user change or
obtain the value

• Encapsulation allows us to create a "black box" and protects an objects internal state from
corruption by its clients.

• There are two ways to create a validation process.

1. Using Accessors and Mutators


2. Using properties

Benefits of Encapsulation
• In Encapsulation fields of a class can be read-only or can be write-only

• A class can have control over in its fields

• A class can change data type of its fields anytime but users of this class do not
need to change any code

34
In this example _employeeid and _salary is private fields and providing access to the fields using
public methods (SetEmployeeID,GetEmployeeID,SetSalary,GetSalary)

In this example _employeeid and _salary is private fields and providing access to the fields using
public methods (EmployeeID,Salary).
Last time in an interview i was asked what is Enacaplation and Abstraction with an example?I
explained to them with an example like this.Suppose you have a button on the Form.The
customer has to know only his job is just click the button which is showing the essential feature
known as Abstraction, but he dosn't need to know how the button is worked,it is hiding the non-
essential features known as Encapsulation.Then they asked me this is example where you are
right. But how do you implement these two concepts by coding in your application for which you
can tell this code is for abstraction and this code is for encpsulation ?

35
User Contol vs Custom Control
Both User Control and Custom Control can be created to avoid the work repeatation. Both can be
used in multiple applications. Still it is a confusion for many programmers where to use which
control .This article explains the difference between both and give a solution to use it as best
choice in various applicaitons.

Difference in some factors :

Factors User Control Custom Control


Creation Creation is similar to the way Web Writing involves lots of code because
Forms pages are created; well-suited there is no designer support
for rapid application development
(RAD)
Content A much better choice when you need More suited for when an application
static content within a fixed layout, for requires dynamic content to be
example, when you make headers and displayed; can be reused across an
footers application, for example, for a data
bound table control with dynamic rows
Design Writing doesn't require much Writing from scratch requires a good
application designing because they are understanding of the control's life
authored at design time and mostly cycle and the order in which events
contain static data execute, which is normally taken care
of in user controls.
Deploymen 1. Designed for single-application 1. Designed so that it can be used by
t scenarios more than one application
2. Deployed in the source form (.ascx) 2. Deployed either in the application's
along with the source code of the Bin directory or in the global assembly
application cache
3. If the same control needs to be used 3. Distributed
in more than one application, it
introduces redundancy and
maintenance problems

Executing Store Procedure inside a Function


1. either convert both the function and procedure to procedures or convert them to
functions
2. you can actually call a sp from an udf by using the openquery(). the trick is that you can
use openquery within a udf and sql do not parse the character string that you give as

36
parameter to the openquery and the best thing is that you can refer to your own server
when using openquery. to be able to do so you have to execute the following script:
• EXEC sp_serveroption [server_name], 'Data Access', true
• and here is an example how to call sp with openquery:
• select * from openquery(MyServer, 'exec sp_who')go

eg CREATE function [dbo].[create_SQL_string](@driver nvarchar(32), @sql


nvarchar(max))
returns nvarchar(max)
with execute as caller
as begin
declare @out_sql nvarchar(max)
return 'select * from openquery('+@driver+',
'''+REPLACE(@sql,'''','''''')+''')'
end

declare @a nvarchar(512)
set @a = (select [dbo].[create_SQL_string](N'SRV', @query))
exec sp_executesql @a

State Management Techniques in ASP.NET


http://www.codeproject.com/KB/aspnet/state_management_intro.aspx
web applications are based on stateless HTTP protocol which does not retain any information about user
requests. In typical client and server communication using HTTP protocol, page is created each time the
page is requested.

Developer is forced to implement various state management techniques when developing applications
which provide customized content and which "remembers" the user.
Client side State management Options:

ASP.NET provides various client side state management options like Cookies, QueryStrings (URL),
Hidden fields, View State and Control state (ASP.NET 2.0). Let's discuss each of client side state
management options.
Bandwidth should be considered while implementing client side state management options because they
involve in each roundtrip to server. Example: Cookies are exchanged between client and server for each
page request.
Cookie:

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

Let's see an example which makes use of cookies to customize web page.

if (Request.Cookies["UserId"] != null)
lbMessage.text = "Dear" + Request.Cookies["UserId"].Value + ", Welcome to our website!";
else
lbMessage.text = "Guest,welcome to our website!";
If you want to store client's information use the below code

37
Response.Cookies["UserId"].Value=username;
Advantages:
• Simplicity
Disadvantages:
• Cookies can be disabled on user browsers
• Cookies are transmitted for each HTTP request/response causing overhead on bandwidth
• Inappropriate for sensitive data
Hidden fields:

Hidden fields are used to store data at the page level. As its name says, these fields are not rendered by
the browser. It's just like a standard control for which you can set its properties. Whenever a page is
submitted to server, hidden fields values are also posted to server along with other controls on the page.
Now that all the asp.net web controls have built in state management in the form of view state and new
feature in asp.net 2.0 control state, hidden fields functionality seems to be redundant. We can still use it to
store insignificant data. We can use hidden fields in ASP.NET pages using following syntax
protected System.Web.UI.HtmlControls.HtmlInputHidden Hidden1;

//to assign a value to Hidden field


Hidden1.Value="Create hidden fields";
//to retrieve a value
string str=Hidden1.Value;
Advantages:
• Simple to implement for a page specific data
• Can store small amount of data so they take less size.
Disadvantages:
• Inappropriate for sensitive data
• Hidden field values can be intercepted(clearly visible) when passed over a network
View State:

View State can be used to store state information for a single user. View State is a built in feature in web
controls to persist data between page post backs. You can set View State on/off for each control using
EnableViewState property. By default, EnableViewState property will be set to true. View state
mechanism poses performance overhead. View state information of all the controls on the page will be
submitted to server on each post back. To reduce performance penalty, disable View State for all the
controls for which you don't need state. (Data grid usually doesn't need to maintain state). You can also
disable View State for the entire page by adding EnableViewState=false to @page directive. View state
data is encoded as binary Base64 - encoded which add approximately 30% overhead. Care must be taken
to ensure view state for a page is smaller in size. View State can be used using following syntax in an
ASP.NET web page.
// Add item to ViewState
ViewState["myviewstate"] = myValue;

//Reading items from ViewState


Response.Write(ViewState["myviewstate"]);

Advantages:

38
• Simple for page level data
• Encrypted
• Can be set at the control level
Disadvantages:
• Overhead in encoding View State values
• Makes a page heavy
Query strings:
Query strings are usually used to send information from one page to another page. They are passed along
with URL in clear text. Now that cross page posting feature is back in asp.net 2.0, Query strings seem to
be redundant. Most browsers impose a limit of 255 characters on URL length. We can only pass smaller
amounts of data using query strings. Since Query strings are sent in clear text, we can also encrypt query
values. Also, keep in mind that characters that are not valid in a URL must be encoded using
Server.UrlEncode.
Let's assume that we have a Data Grid with a list of products, and a hyperlink in the grid that goes to a
product detail page, it would be an ideal use of the Query String to include the product ID in the Query
String of the link to the product details page (for example, productdetails.aspx?productid=4).
When product details page is being requested, the product information can be obtained by using the
following codes:
string productid;
productid=Request.Params["productid"];
Advantages:
• Simple to Implement
Disadvantages:
• Human Readable
• Client browser limit on URL length
• Cross paging functionality makes it redundant
• Easily modified by end user
Control State:
Control State is new mechanism in ASP.NET 2.0 which addresses some of the shortcomings of View
State. Control state can be used to store critical, private information across post backs. Control state is
another type of state container reserved for controls to maintain their core behavioral functionality
whereas View State only contains state to maintain control's contents (UI). Control State shares same
memory data structures with View State. Control State can be propagated even though the View State for
the control is disabled. For example, new control Grid View in ASP.NET 2.0 makes effective use of
control state to maintain the state needed for its core behavior across post backs. Grid View is in no way
affected when we disable View State for the Grid View or entire page
Server Side State management:
As name implies, state information will be maintained on the server. Application, Session, Cache and
Database are different mechanisms for storing state on the server.
Care must be taken to conserve server resources. For a high traffic web site with large number of
concurrent users, usage
of sessions object for state management can create load on server causing performance degradation
Application object:

39
Application object is used to store data which is visible across entire application and shared across
multiple user sessions. Data which needs to be persisted for entire life of application should be stored in
application object.
In classic ASP, application object is used to store connection strings. It's a great place to store data which
changes infrequently. We should write to application variable only in application_Onstart event
(global.asax) or application.lock event to avoid data conflicts. Below code sample gives idea
Application.Lock();
Application["mydata"]="mydata";
Application.UnLock();
Session object:
Session object is used to store state specific information per client basis. It is specific to particular user.
Session data persists for the duration of user session you can store session's data on web server in
different ways. Session state can be configured using the <session State> section in the application's
web.config file.
Configuration information:

<sessionState mode = <"inproc" | "sqlserver" | "stateserver">


cookieless = <"true" | "false">
timeout = <positive integer indicating the session timeout in minutes>
sqlconnectionstring = <SQL connection string that is only used in the SQLServer mode>
server = <The server name that is only required when the mode is State Server>
port = <The port number that is only required when the mode is State Server>
Mode:

This setting supports three options. They are InProc, SQLServer, and State Server

Cookie less:
This setting takes a Boolean value of either true or false to indicate whether the Session is a cookie less
one.
Timeout:
This indicates the Session timeout vale in minutes. This is the duration for which a user's session is
active. Note that the session timeout is a sliding value; Default session timeout value is 20 minutes

SqlConnectionString:
This identifies the database connection string that names the database used for mode SQLServer.

Server:
In the out-of-process mode State Server, it names the server that is running the required Windows NT
service: aspnet_state.

Port:

This identifies the port number that corresponds to the server setting for mode State Server. Note that a
port is an unsigned integer that uniquely identifies a process running over a network.
You can disable session for a page using EnableSessionState attribute. You can set off session for entire
application by setting mode=off in web.config file to reduce overhead for the entire application.

40
Session state in ASP.NET can be configured in different ways based on various parameters including
scalability, maintainability and availability
• In process mode (in-memory)- State information is stored in memory of web server
• Out-of-process mode- session state is held in a process called aspnet_state.exe that runs as a
windows service.
• Database mode – session state is maintained on a SQL Server database.
In process mode:

This mode is useful for small applications which can be hosted on a single server. This model is most
common and default method to store session specific information. Session data is stored in memory of
local web server
Configuration information:
<sessionState mode="Inproc"
sqlConnectionString="data source=server;user id=freelance;password=freelance"
cookieless="false" timeout="20" />
Advantages:
• Fastest mode
• Simple configuration
Disadvantages:
• Session data will be lost if the worker process or application domain recycles
• Not ideal for web gardens and web farms
Out-of-process Session mode (state server mode):

This mode is ideal for scalable and highly available applications. Session state is held in a process called
aspnet_state.exe that runs as a windows service which listens on TCP port 42424 by default. You can
invoke state service using services MMC snap-in or by running following net command from command
line.
Net start aspnet_state
Configuration information:

<sessionState mode="StateServer"
StateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;user id=freelance; password=freelance"
cookieless="false" timeout="20"/>
Advantages:
• Supports web farm and web garden configuration
• Session data is persisted across application domain recycles. This is achieved by using separate
worker process for maintaining state
Disadvantages:
• Out-of-process mode provides slower access compared to In process
• Requires serializing data
SQL-Backed Session state:

41
ASP.NET sessions can also be stored in a SQL Server database. Storing sessions in SQL Server offers
resilience that can serve sessions to a large web farm that persists across IIS restarts.

SQL based Session state is configured with aspnet_regsql.exe. This utility is located in .NET
Framework's installed directory
C:\<windows>\microsoft.net\framework\<version>. Running this utility will create a database which will
manage the session state.
Configuration Information:
<sessionState mode="SQLServer"
sqlConnectionString="data source=server;user id=freelance;password=freelance"
cookieless="false" timeout="20" />
Advantages:
• Supports web farm and web garden configuration
• Session state is persisted across application domain recycles and even IIS restarts when session
is maintained on different server.
Disadvantages:
• Requires serialization of objects
Choosing between client side and Server side management techniques is driven by various factors
including available server resources, scalability and performance. We have to leverage both client side
and server side state management options to build scalable applications.
When leveraging client side state options, ensure that little amount of insignificant information is
exchanged between page requests.
Various parameters should be evaluated when leveraging server side state options including size of
application, reliability and robustness. Smaller the application, In process is the better choice. We should
account in the overheads involved in serializing and deserializing objects when using State Server and
Database based session state. Application state should be used religiously.

ASP.NET Page Life Cycle


Stage Events/Method

Initialization of the page Page_Init

Loading of the View State LoadViewState

processing of the Post back data LoadPostData

Loading of Page Page_Load

Notification of PostBack RaisePostDataChangedEvent

Handling of PostBack Event RaisePostBackEvent

Pre Rendering of Page Page_PreRender

Saving of view state SaveViewState

Rendering of Page Page_Render

Unloading of the Page Page_UnLoad

42
http://www.dotnetfunda.com/articles/article771-aspnet-page-life-cycle-.aspx
Virtual Abstract

If you feel that the derived class may


or may not override the base class
method, then you will define the base
class method as virtual. Consider the
But if you want to enforce that derived class must
following example:
override the base class method then you will
namespace Application1 {
define the base class method as abstract.
public class virtualClass {
namespace Application1 {
public virtual void virtualMethod(){
public abstract class abstractClass {
Console.WriteLine("Virtual Method..");
public abstract void abstractMethod();
}
}
}
public class derivedClass:abstractClass{
public class derivedClass:virtualClass{
public override void abstractMethod(){
public override void virtualMethod(){
Console.WriteLine("Overridden..");
Console.WriteLine("Overridden..");
}
}
}
}
public class testClass {
public class testClass {
public static void Main() {
public static void Main() {
derivedClass obj = new
virtualClass obj = new virtualClass();
derivedClass();
obj.virtualMethod();
obj.abstractMethod();
derivedClass dObj = new
}
derivedClass();
}
dObj.virtualMethod();
}
}
Output of this code will be:
}
Overridden..
}
Output of this code will be:
Virtual Method..
Overridden..

Abstract methods should compulsorily be


overridden by the derived class. In the above
Virtual methods need not be
example, if the derivedClass does not override
compulsorily overridden. In the above
abstractMethod, then during compilation you will
example if the derived class does not
get the following error:
override the method virtualMethod,
'Application1.derivedClass' does not implement
then again the code will work.
inherited abstract member
'Application1.abstractClass.abstractMethod()'

To define a base class method to be If you want to define a method as abstract in the
virtual, you need not include any new base class then the base class should also be
definition for the base class. In the marked as abstract. Consider the following
earlier example, you can see that the example:
class virtualClass just includes an namespace Application1 {
access modifier followed by the class public class abstractClass {
name. No other additional modifiers public abstract void abstractMethod();

43
}
}
In this example, abstractClass has an abstract
method. Hence the class in itself has to be marked
abstract. But it is not done in the above example.
are required.
Therefore during compilation, you will end up in
the following error:
'Application1.abstractClass.abstractMethod()' is
abstract but it is contained in nonabstract class
'Application1.abstractClass'

Abstract methods have only the signature. It


cannot have method body. However the abstract
class can include non-abstract methods and these
methods can have method body defined. Consider
the following example:
namespace Application1 {
public abstract class abstractClass {
Virtual method can have a method public abstract void abstractMethod(){
body. In the earlier example, Console.WriteLine("Abstract
virtualMethod of virtualClass has method..");
method definition like any of the other }
methods that you define and it is }
perfectly legal. }
Here you are trying to include method body for an
abstract method. This is not permissible. Hence
during compilation you will end up in the following
error:
"'Application1.abstractClass.abstractMethod()'
cannot declare a body because it is marked
abstract"

Class containing virtual method can be


Class containing abstract method cannot be
instantiated. Here is an example:
instantiated. It can only be inherited. Consider the
namespace Application1 {
following example:
public class virtualClass {
namespace Application1 {
public virtual void virtualMethod(){
public abstract class abstractClass {
Console.WriteLine("Virtual Method..");
public abstract void abstractMethod();
}
}
}
public class testClass {
Public class testClass {
public static void Main() {
public static void Main() {
abstractClass obj = new abstractClass();
virtualClass obj = new virtualClass();
}
obj.virtualMethod();
}
}
}
}
Here you are trying to create an instance of
}
abstract class. This is not possible. Hence during
Output of this code will be:
compilation you will end up in the following error:
Virtual Method…
"cannot create an instance of the abstract class or
interface Application1.abstractClass"

Not just methods, virtual modifier can Apart from class and method, the modifer abstract

44
can be associated with properties, events and
also be used with properties.
indexers.

There is a restriction when using


Abstract modifiers also have a restriction. They
virtual modifer. You cannot use this
cannot be used along with static or virtual or
modifer along with static or abstract
override modifiers.
or override modifiers.

http://www.dotnetspider.com/forum/181568-what-diff-between-virtual-class-abstract-class.aspx

45

You might also like