Sunday, July 25, 2010

WCF 5

Problem of Fault on channel:
Once the fault occurs on proxy object, It becomes useless. You can't even call proxy.close() on it, Because of object got faulted. The reason is because of implementation of ICommunicationObject interface. This interface is contract for basic state machine for all communication oriented objects in system. And once the channel is faulted, it goes into fault state. So In order to overcome such problem we need to test state  of proxy object and accordingly apply method on it.
If(serviceClient.State == CommunicationState.faulted)
{
..
}
Or we can subscribe to fault event of communication object.
Once the object is faulted we must create a new instance of it.

Auto-Open Vs Open:
WCF support ICommunicationObject which has different states:
Created -> Opening -> Opened -> Closing -> Closed
WCF supports auto-open. This feature allows you to call an I/O method while the object is in the Created (or Opening) state. And objects I/O method ensures that the object transitions to the opened state before calling the inner channel. If you are using a session and you need to send multiple messages concurrently and you care that the first couple messages are actually sent concurrently, you should not use auto-open.
Whenever some method is invoked there is serviceChannel class which does some work and call this
channel.send(message)
Concurrent messages with auto open creates problem,Because it works like this:
If(this.State == created)
{
Open channel
}
So every call has to wait for first call to get finish.Then also there will be race condition for messages to be sent. If the order of message is important then it will create problem. Point to note here is that if we are using multithreading then also the order is not defined.I agree with the same but what if we are using some async calls which must be deterministic.
So in order to avoid it we must open the channel manually by using .open method.

Session limit on server side:
There is always MaxConcurrentSessions on server side. Default value for this is 10. If we are opening channels and crossing the limit of MaxConcurrentSessions, then we can get some timeout errors.
Ex:
for (int i = 0; i < 100; i++)
{
    proxy = create channel Using factory
    proxy.Mymethod();
    ((IChannel)proxy).Close();
}
Here if we don't use .close() method and haven't set anything on MaxConcurrentSessions. Then at i=10 it will say time out. and the loop will only be able to create 10 channels.
In order to solve this problem add these statements inside system.servicemodel block inside behaviours tag
behavior name="myBehavior">
serviceThrottling maxConcurrentCalls="Integer" maxConcurrentInstances="Integer" maxConcurrentSessions="Integer"  />
/behavior>
And in service tag write this:
service name="mySvc" behaviorConfiguration="myBehavior">

.Close Vs .Abort:
.Close will close the connection gracefully. If there is any call left it will wait for its response and then only it will close the connection.But Abort() is a forced close.
We can understand the difference between these 2 by following code:
try
{
    myeClient.CallSomething();
    myClient.Close();
}
catch(FaultException)
{
    myClient.Abort();
}


Generics class mapping in proxy: 
Generics is very common in today world of coding. But WCF does not support use of generics methods for service operation. So open generics type cannot  be used for in it. People may think that it is limitation of WCF, But it is not so, Actually it is limitation of WSDL(Used to expose service metadata to consumers).
Then is there no way that we can expose generic object client side?
The answer is Yes!!!!
Service side Code: Service:
[DataContract]
public class MyObj
{
   ..
}

[ServiceContract]
Public interface IBoundedGenerics
{
    [OperationContract]
    MyObj GetObj(int id);
}


On client side the proxy get created like this:
[DataContract]
public class MyObjOfint
{
   ...
}
Resulting Name = Generic Class Name + “of” + Type Parameter + Hash
Hash is there to reduce name collision risk. But causes ugly name. So in order to avoid it we can use
[DataContract(Name = "MyObjOf{0}"]
It will create name of our choice.

WCF 4 (Service Behavior:InstanceContextMode)

Instance management is set of techniques used by WCF to bind a set of messages to a service instance.Instance management is necessary because applications differ in their needs for scalability, performance, throughput, transactions. InstanceContextMode is a property which is available in the System.ServiceModel. InstanceContextMode property is mainly used in the ServiceBehaviour attribute in order to mention what kind of state maintenance your WCF application should provide. There is an enumerator available in the Sytem.ServiceModel library named as InstanceContextMode and it can be used in order to set the property InstanceContextMode.

Per-Call:
Per-call services are the WCF default instantiation mode. When the service type is configured for per-call activation, a service instance, a CLR object, exists only while a client call is in progress. Every client request gets a new dedicated service instance. The benefit with this approach is that the service instance will be caught by client only upto it is being used. So it is possible to dispose service object and expensive resources long before client disposes of the proxy. In order to support per call mode we need to design the service and its contract to support it. Maintaining a state is always a problem with per call mode, because every call creates a new instance of service. So if we want to maintain the session in per call mode also, then on each call we need to fetch the values from som storage( file system, Database) and at end of the call save the values back. But still all the states are not possible to save, For example state containing database connection. Object must reaquire the connection. Per-call activation mode works best when the amount of work to be done in each method call is small and there are no more activities to complete in the background once a method returns. For this reason, you should not spin off background threads or dispatch asynchronous calls back into the instance because the object will be discarded once the method returns. Per-call services clearly offer a trade-off in performance (the overhead of reconstructing the instance state on each method call) with scalability (holding onto the state and the resources it ties in). To use this mode we can explicit add this attribute on service definition.In pre call mode this attribute is optional.
[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall)]
We can use basicHTTPBinding with it. 

Per-Session:
Windows Communication Foundation can maintain a private session between a client and a particular service instance. When the client creates a new proxy to a service configured as session-aware, the client gets a new dedicated service instance that is independent of all other instances of the same service. That instance will remain in service usually until the client no longer needs it. Each private session uniquely binds a proxy to a particular service instance. Note that the client session has one service instance per proxy. If the client creates another proxy to the same or a different endpoint, that second proxy will be associated with a new instance and session. Because the service instance remains in memory throughout the session, it can maintain state in memory. A service configured for private sessions cannot support large number of clients due to the cost associated with each such dedicated service instance.To support sessions, you need to set Session to true at the contract level:
[ServiceContract(Session = true)]
interface IMyContract {...}
Set the InstanceContextMode property of the ServiceBehavior attribute to InstanceContextMode.PerSession to make teh service to be in per session mode.
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
class MyService : IMyContract {...}
The session will end once the client closes the proxy or the client is idle for some time(timeout( default is 10 mins)).
Any binding but basichttpbinding will work for it.

Single instance:
When a service is configured as a singleton, all clients get connected to the same single instance independently of each other, regardless of which endpoint of the service they connect to. The singleton service lives forever, and is only disposed of once the host shuts down. The singleton is created exactly once when the host is created. If we are using default constructor, first client will always face time delay in initialization, So to avoid it WCF allows you to create the singleton instance directly using normal CLR instantiation beforehand, initialize the instance, and then open the host with that instance in mind as the singleton service. In singleton as lot many clients are using same service instance so synchronization of methods is always a critical step. We can specify singleton mode by this attribute on service class:
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
Any binding but basichttpbinding will work for it.

Saturday, July 3, 2010

.NET fundamentals 8(Assembly concept)

What is an assembly?
* An Assembly is a  logical unit of code
* Assembly physically exist as DLLs or EXEs
* One assembly can contain one or more files
* The constituent files can include any file types like image files, text files etc. along with DLLs or EXEs
* When you compile your source code by default the exe/dll generated is actually an assembly
* Unless your code is bundled as assembly it can not be used in any other application
* When you talk about version of a component you are actually talking about version of the assembly to which the component belongs.
* Every assembly file contains information about itself. This information is called as Assembly Manifest.

What is assembly manifest?
* Assembly manifest is a data structure which stores information about an assembly
* This information is stored within the assembly file(DLL/EXE) itself
* The information includes version information, list of constituent files etc.

What is private and shared assembly?
The assembly which is used only by a single application is called as private assembly. Suppose you created a DLL which encapsulates your business logic. This DLL will be used by your client application only and not by any other application. In order to run the application properly your DLL must reside in the same folder in which the client application is installed. Thus the assembly is private to your application.
Suppose that you are creating a general purpose DLL which provides functionality which will be used by variety of applications. Now, instead of each client application having its own copy of DLL you can place the DLL in 'global assembly cache'. Such assemblies are called as shared assemblies.

What is Global Assembly Cache?
Global assembly cache is nothing but a special disk folder where all the shared assemblies will be kept. It is located under :\WinNT\Assembly folder.

How assemblies avoid DLL Hell?
As stated earlier most of the assemblies are private. Hence each client application refers assemblies from its own installation folder. So, even though there are multiple versions of same assembly they will not conflict with each other. Consider following example :
* You created assembly Assembly1
* You also created a client application which uses Assembly1 say Client1
* You installed the client in C:\MyApp1 and also placed Assembly1 in this folder
* After some days you changed Assembly1
* You now created another application Client2 which uses this changed Assembly1
* You installed Client2 in C:\MyApp2 and also placed changed Assembly1 in this folder
* Since both the clients are referring to their own versions of Assembly1 everything goes on smoothly
Now consider the case when you develop assembly that is shared one. In this case it is important to know how assemblies are versioned. All assemblies has a version number in the form:
major.minor.build.revision
If you change the original assembly the changed version will be considered compatible with existing one if the major and minor versions of both the assemblies match.
When the client application requests assembly the requested version number is matched against available versions and the version matching major and minor version numbers and having most latest build and revision number are supplied.

How do I create shared assemblies?
Following steps are involved in creating shared assemblies :
* Create your DLL/EXE source code
* Generate unique assembly name using SN utility
* Sign your DLL/EXE with the private key by modifying AssemblyInfo file
* Compile your DLL/EXE
* Place the resultant DLL/EXE in global assembly cache using AL utility

How do I create unique assembly name?
Microsoft now uses a public-private key pair to uniquely identify an assembly. These keys are generated using a utility called SN.exe (SN stands for shared name). The most common syntax of is :
sn -k mykeyfile.key
Where k represents that we want to generate a key and the file name followed is the file in which the keys will be stored.

How do I sign my DLL/EXE?
Before placing the assembly into shared cache you need to sign it using the keys we just generated. You mention the signing information in a special file called AssemblyInfo. Open the file from VS.NET solution explorer and change it to include following lines :
[assembly:AssemblyKeyFile("file_path")]
Now recompile the project and the assembly will be signed for you.
Note : You can also supply the key file information during command line compilation via /a.keyfile switch.

What makes an assembly unique?
filename + assembly version + culture + public key token

Why publicKeytoken is hash code instead of unique identifier as like GUID, URL?
conserve storage

Is it possible to have reference of unsigned assembly in strongly signed assembly?
No, It will give you compile time error.

How signing make an assembly secure?
Signing has followign steps:
1) When we compile the code compiler will create hash code of IL and every other resource in assembly.
2) Then we sign the assembly. In this this step private Key will encode the has code with some algorithm and will create some kind of identifier and place it in assembly itself.
3) During 2nd step public key corresponding to private key is also placed in assembly.
4) Now when CLR tries to load this assembly, it will again create hash code of assembly and will decode the identifier(placed in 2nd step) with public Key, and will see if both hash codes are same.
If hash codes are different then it means assembly is been tempered and CLR won't load it else it will load it.


What is Satellite assembly?
Satellite assembly is region/location specific resource file. When we want to have our code location specific we can have our data in some resource file. This resource file can be deployed in form of assembly which is nothing but satellite assembly.

Is it possible to have satellite assembly in form of exe not dll?
No, Satellite assembly doesn't contain any code in it, it only contains resources. Thus we can't have Satellite EXE.

What is delay signing?
Delay signing is feature provided by .NET. It is used when we don't want to provide private/public key pair to developer. We want to get it signed in the end i.e. after every kind of testing is done.
There are attributes available which you will need to add in your class:
AssemblyKeyFileAttribute - passes the name of the file containing public key info.
AssemblyDelaySignAttribute - indicates delay sign is used in this assembly.

There are few steps by which we give strong name to assembly so that it can be GACed, and skip validation of our assembly. In this step, assembly only have information about public key.It has strong name but it not validated, thus can be GACed and used.

What is difference between signing an assembly and giving it a strong name?
After signing we get assembly which is completely secure i.e. while loading these assembly CLR will check if it is original one or tempered. But signing is only required to GAC the dll. It is possible to have assembly which has strong name but not signed(delay sign).

.NET fundamentals 7

->What are the types of assemblies?
(A)  With Respect to  Program Access.
     i) Private Assembly- It can be used only in one application.
     ii) Public/Shared Assembly- It can be used by all applications in the server.
(B)  With Respect to Number of Resources.
     i) Static Assembly- It uses fixed resources.
    ii) Dynamic Assembly- It supports dynamic creation of resouces or files at runtime programatically.
(C) With Respect to Deployment.
     i) Satellite Assembly- Easily Deployable. (Visual Studio 2005).
    ii) Resource-Only Assembly- In Visual Studio 2003.
(D) With Respect to Number of Assemblies.
     i) Single File Assembly- /Bin/x.dll
    ii) Multi File Assembly- /Bin/x.dll
                                  y.dll
                                  z.dll 
                                  ---

->What are delegates?where are they used ?
A delegate defines a reference type that can be used to encapsulate a method with a specific signature. A delegate instance encapsulates a static or an instance method. Delegates are roughly similar to function pointers in C++; however, delegates are type-safe and secure.

When do you use virutal keyword?
When we need to override a method of the base class in the sub class, then we give the virtual keyword in the base class method. This makes the method in the base class to be overridable. Methods, properties, and indexers can be virtual, which means that their implementation can be overridden in derived classes.
When a virtual method is invoked, the run-time type of the object is checked for an overriding member. The overriding member in the most derived class is called, which might be the original member, if no derived class has overridden the member.
By default, methods are non-virtual. You cannot override a non-virtual method.
You cannot use the virtual modifier with the static, abstract, private or override modifiers.
Virtual properties behave like abstract methods, except for the differences in declaration and invocation syntax. It is an error to use the virtual modifier on a static property.A virtual inherited property can be overridden in a derived class by including a property declaration that uses the override modifier.

What Is Boxing And Unboxing?
Boxing :- Boxing is an implicit conversion of a value type to the type object type
Eg:-
Consider the following declaration of a value-type variable:
int i = 123;
object o = (object) i;
Boxing Conversion
UnBoxing :- Unboxing is an explicit conversion from the type object to a value type
Eg:
int i = 123; // A value type
object box = i; // Boxing
int j = (int)box; // Unboxing

What is Value type and refernce type in .Net?
Value Type : A variable of a value type always contains a value of that type. The assignment to a variable of a value type creates a copy of the assigned value, while the assignment to a variable of a reference type creates a copy of the reference but not of the referenced object.
The value types consist of two main categories:
* Stuct Type
* Enumeration Type
Reference Type :Variables of reference types, referred to as objects, store references to the actual data. This section introduces the following keywords used to declare reference types:
* Class
* Interface
* Delegate
This section also introduces the following built-in reference types:
* object
* string

What is the difference between structures and enumeration?
Unlike classes, structs are value types and do not require heap allocation. A variable of a struct type directly contains the data of the struct, whereas a variable of a class type contains a reference to the data. They are derived from System.ValueType class.
Enum->An enum type is a distinct type that declares a set of named constants.They are strongly typed constants. They are unique types that allow to declare symbolic names to integral values. Enums are value types, which means they contain their own value, can't inherit or be inherited from and assignment copies the value of one enum to another.
public enum Grade
{
A,
B,
C
}

What is namespaces?
Namespace is a logical naming scheme for group related types.Some class types that logically belong together they can be put into a common namespace. They prevent namespace collisions and they provide scoping. They are imported as "using" in C# or "Imports" in Visual Basic. It seems as if these directives specify a particular assembly, but they don't. A namespace can span multiple assemblies, and an assembly can define multiple namespaces. When the compiler needs the definition for a class type, it tracks through each of the different imported namespaces to the type name and searches each referenced assembly until it is found.
Namespaces can be nested. This is very similar to packages in Java as far as scoping is concerned.

What is global assembly cache?
Each computer where the common language runtime is installed has a machine-wide code cache called the global assembly cache. The global assembly cache stores assemblies specifically designated to be shared by several applications on the computer.
There are several ways to deploy an assembly into the global assembly cache:
· Use an installer designed to work with the global assembly cache. This is the preferred option for installing assemblies into the global assembly cache.
· Use a developer tool called the Global Assembly Cache tool (Gacutil.exe), provided by the .NET Framework SDK.
· Use Windows Explorer to drag assemblies into the cache.

What is MSIL?
When compiling to managed code, the compiler translates your source code into Microsoft intermediate language (MSIL), which is a CPU-independent set of instructions that can be efficiently converted to native code. MSIL includes instructions for loading, storing, initializing, and calling methods on objects, as well as instructions for arithmetic and logical operations, control flow, direct memory access, exception handling, and other operations. Before code can be run, MSIL must be converted to CPU-specific code, usually by a just-in-time (JIT) compiler. Because the common language runtime supplies one or more JIT compilers for each computer architecture it supports, the same set of MSIL can be JIT-compiled and run on any supported architecture.
When a compiler produces MSIL, it also produces metadata. Metadata describes the types in your code, including the definition of each type, the signatures of each type's members, the members that your code references, and other data that the runtime uses at execution time. The MSIL and metadata are contained in a portable executable (PE) file that is based on and extends the published Microsoft PE and common object file format (COFF) used historically for executable content. This file format, which accommodates MSIL or native code as well as metadata, enables the operating system to recognize common language runtime images. The presence of metadata in the file along with the MSIL enables your code to describe itself, which means that there is no need for type libraries or Interface Definition Language (IDL). The runtime locates and extracts the metadata from the file as needed during execution.

What is Jit compilers?.how many are available in clr?
Just-In-Time compiler- it converts the language that you write in .Net into machine language that a computer can understand. there are tqo types of JITs one is memory optimized & other is performace optimized.

What is tracing?Where it used.Explain few methods available
Tracing refers to collecting information about the application while it is running. You use tracing information to troubleshoot an application.
Tracing allows us to observe and correct programming errors. Tracing enables you to record information in various log files about the errors that might occur at run time. You can analyze these log files to find the cause of the errors.
In .NET we have objects called Trace Listeners. A listener is an object that receives the trace output and outputs it somewhere; that somewhere could be a window in your development environment, a file on your hard drive, a Windows Event log, a SQL Server or Oracle database, or any other customized data store.
The System.Diagnostics namespace provides the interfaces, classes, enumerations and structures that are used for tracing The System.Diagnostics namespace provides two classes named Trace and Debug that are used for writing errors and application execution information in logs.
All Trace Listeners have the following functions. Functionality of these functions is same except that the target media for the tracing output is determined by the Trace Listener.
Method Name
Result Fail Outputs the specified text with the Call Stack.
Write Outputs the specified text.
WriteLine Outputs the specified text and a carriage return.
Flush Flushes the output buffer to the target media.
Close Closes the output stream in order to not receive the tracing/debugging output.

What is the property available to check if the page posted or not?
The Page_Load event handler in the page checks for IsPostBack property value, to ascertain whether the page is posted. The Page.IsPostBack gets a value indicating whether the page is being loaded in response to the client postback, or it is for the first time. The value of Page.IsPostBack is True, if the page is being loaded in response to the client postback; while its value is False, when the page is loaded for the first time. The Page.IsPostBack property facilitates execution of certain routine in Page_Load, only once (for e.g. in Page load, we need to set default value in controls, when page is loaded for the first time. On post back, we check for true value for IsPostback value and then invoke server-side code to
update data).

Which are the abstract classes available under system.xml namespace?
The System.XML namespace provides XML related processing ability in .NET framework. XmlReader and XMLWriter are the two abstract classes at the core of .NET Framework XML classes:
1. XmlReader provides a fast, forward-only, read-only cursor for processing an XML document stream.
2. XmlWriter provides an interface for producing XML document streams that conform to the W3C's XML standards.
Both XmlReader and XmlWriter are abstract base classes, which define the functionality that all derived classes must support.

What are the derived classes from xmlReader and xmlWriter?
Both XmlReader and XmlWriter are abstract base classes, which define the functionality that all derived classes must support.
There are three concrete implementations of XmlReader:
1.XmlTextReader
2.XmlNodeReader
3.XmlValidatingReader
There are two concrete implementations of XmlWriter:
1.XmlTextWriter
2.XmlNodeWriter
XmlTextReader and XmlTextWriter support reading data to/from text-based stream, while XmlNodeReader and XmlNodeWriter are designed for working with in-memory DOM tree structure. The custom readers and writers can also be developed to extend the built-in functionality of XmlReader and XmlWriter.

What is managed and unmanaged code?
The .NET framework provides several core run-time services to the programs that run within it - for example exception handling and security. For these services to work, the code must provide a minimum level of information to the runtime. i.e., code executing under the control of the CLR is called managed code. For example, any code written in C# or Visual Basic .NET is managed code.
Code that runs outside the CLR is referred to as "unmanaged code." COM components, ActiveX components, and Win32 API functions are examples of unmanaged code.

Why do you need to serialize?
We need to serialize the object,if you want to pass object from one computer/application domain to another.Process of converting complex objects into stream of bytes that can be persisted or transported.Namespace for serialization is System.Runtime.Serialization.The ISerializable interface allows you to make any class Serializable..NET framework features 2 serializing method.
1.Binary Serialization 2.XML Serialization

Can a nested object be used in Serialization ?
Yes. If a class that is to be serialized contains references to objects of other classes, and if those classes have been marked as serializable, then their objects are serialized too.

Difference between int and int32 ?
Both are same. System.Int32 is a .NET class. Int is an alias name for System.Int32.