Visual Studio 2008 Visual Studio 2005: Web Parts Control Description
Visual Studio 2008 Visual Studio 2005: Web Parts Control Description
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.
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 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.
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,
Response.Write("Name is "+Name+"<br>");
To call the above method using delegate we should declare a delegate with similar signature,
Before calling we should initialize or register the delegate with the method like,
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,
The below code will explain how to call PrintName and PrintAddress methods using a delegate,
del(“Chidambaram”);
Name 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,
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.
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
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
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.
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.
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.
T head;
8
T next;
Here, T is the type parameter. We can pass any data type as parameter.
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
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;
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:
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>
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.
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
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
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
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){
});
});
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.
<style type="text/css">
</style>
$("a").click(function(event){ // if you click any link, it should make itself slowly disappear.
event.preventDefault();
$(this).hide("slow");
});
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.
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".
$.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({
url : 'post.php',
data : { id : 123 },
method : 'GET',
dataType : 'json',
success : function(json) {
$('<h1/>').text(json.title).appendTo('body');
$('<div class="content"/>')
.html(json.html).appendTo('body');
},
14
// the raw request and status codes are
},
});
An ordered list of values. In most languages, this is realized as an array, vector, list, or
sequence.
• 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
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.
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
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)
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.
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.
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
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.
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.
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.
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
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.
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.
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
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.
Even though AJAX is a client side technology that uses JavaScript, the client-server
interaction is very important.
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
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
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
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
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.
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.
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" %>
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.
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" %>
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.
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;
}
}
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
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 makes implementation inaccessible to other parts of the program and protect
from whatever actions might be taken outside the function or class.
• 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.
Benefits of Encapsulation
• In Encapsulation fields of a class can be read-only or can be write-only
• 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.
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
declare @a nvarchar(512)
set @a = (select [dbo].[create_SQL_string](N'SRV', @query))
exec sp_executesql @a
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;
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;
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:
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.
42
http://www.dotnetfunda.com/articles/article771-aspnet-page-life-cycle-.aspx
Virtual Abstract
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'
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.
http://www.dotnetspider.com/forum/181568-what-diff-between-virtual-class-abstract-class.aspx
45