Tag Cloud

CRM 2011 (161) CRM 4.0 (144) C# (116) JScript (109) Plugin (92) Registry (90) Techpedia (77) PyS60 (68) WScript (43) Plugin Message (31) Exploit (27) ShellCode (26) FAQ (22) JavaScript (21) Killer Codes (21) Hax (18) VB 6.0 (17) Commands (16) VBScript (16) Quotes (15) Turbo C++ (13) WMI (13) Security (11) 1337 (10) Tutorials (10) Asp.Net (9) Safe Boot (9) Python (8) Interview Questions (6) video (6) Ajax (5) VC++ (5) WebService (5) Workflow (5) Bat (4) Dorks (4) Sql Server (4) Aptitude (3) Picklist (3) Tweak (3) WCF (3) regex (3) Config (2) LINQ (2) PHP (2) Shell (2) Silverlight (2) TSql (2) flowchart (2) serialize (2) ASHX (1) CRM 4.0 Videos (1) Debug (1) FetchXml (1) GAC (1) General (1) Generics (1) HttpWebRequest (1) InputParameters (1) Lookup (1) Offline Plug-ins (1) OutputParameters (1) Plug-in Constructor (1) Protocol (1) RIA (1) Sharepoint (1) Walkthrough (1) Web.config (1) design patterns (1) generic (1) iframe (1) secure config (1) unsecure config (1) url (1)

Pages

Friday, February 07, 2014

OOPS .Net Interview Questions

1. What is mean by Class?

Class is a structure that describes the state (property) and behavior (methods) of the object. It is a template or blueprint to create objects of the class. Class represents the noun and it can be used as type in programming language. E.g Car, Person etc

2. What is mean by Objects?

Object is an executable copy of a class. State and behavior of the objects are defined by class definition. We can create multiple objects for single class. It is also called as instance of the class. When an object is created from the class, memory will be allocated in RAM. e.g Car- Maruthi, Alto, Zen etc. Person- Ram, Sam, John etc

3. What is mean by Struture?

Structure is a light-weight class used to create user-defined types containing only public fields. Structure can't have implementation inheritance, but it can have interface inheritance. We cannot modify the default constructors as like a class. Structure is a value type holds their value in memory when they are declared.

4. What is difference between Class and Object?

Classes are the template or blueprint its state of how objects should be and behave, where as Object is an actual real term object. E.g CAR define state like it should have four wheel and body structure with moving, accelerating and break functionality. Maruthi, Alto or Zen is the real object which has different kind of state from one another.

5. What is difference between Class and Structure?
  • Class is Reference type(Reference types hold a reference to an object in memory) - Structure is a Value type(Value types hold their value in memory when they are declared)
  • User can modify default constructor and destructor of class- structure can't modify default constructor
  • Class supports inheritance - Structure will not support inheritance
  • Classes must be instantiated using the new operator - Structure can be instantiated without using the new operator
6. Which case we have to use Class and Structure?

Structure can be used for things that we no need for identity. Class can be used when we need the identity for an object.

7. What is the advantage of Structure over Class?

Since Stucture is a value type and if we use at the proper location, it will improve the performance.

9. What are advantages of using private constructor, method, property?

Due to security reason, methods and properties are not exposed outside the class using Private access modifier. For implementing Singleton pattern we go for Private Constructor, so we will not able to create instance. Separate method is used to create and return the instance.

10. What is mean by Partial class?

It is new features in .Net 2.0; partial classes mean that class definition can be split into multiple physical files. Logically, partial classes do not make any difference to the compiler. The compiler intelligently combines the definitions together into a single class at compile-time.

Example for Partial Class

partial class Employee
{
string m_Name;
public String Name
{
get { return m_Name; }
set { m_Name = value; }
}
}

partial class Employee
{
int m_Age;
public int Age
{
get { return m_Age; }
set { m_Age = value; }
}
}

public class ExampleofPartical
{
public void Method1()
{
Employee objClass1 = new Employee();
objClass1.Name="Name";
objClass1.Age = 12;
}
}

 


8. What are different access modifiers in .Net?


  • Private - The type or member can only be accessed by code in the same class or struct.
  • Protected - The type or member can only be accessed by code in the same class or struct, or in a derived class.
  • Internal - The type or member can be accessed by any code in the same assembly, but not from another assembly.
  • Procted Internal - The type or member can be accessed by any code in the same assembly, or by any derived class in another assembly.
  • Public -The type or member can be accessed by any other code in the same assembly or another assembly that references it.

Note: In VB.Net 'Internal' is called as 'Friend'

11. What is mean by Partial method?

Partial methods are methods defined in a partial class that are (optionally) divided across two files. With partial methods one file contains the method signature - the method name, its return type, and its input parameters - while the body is (optionally) defined in a separate file. If the partial method's body is not defined then the compiler automatically removes the partial method signature and all calls to the method at compile-time.

Example for Partial method

   {
string m_Name;
public String Name
{
get { return m_Name; }
set { m_Name = value; }
}
public partial string GetEmpDetails(string ID);

}

partial class Employee
{
int m_Age;
public int Age
{
get { return m_Age; }
set { m_Age = value; }
}
public partial string GetEmpDetails(string ID)
{
return "Employee1";
}
}

12. Why do we go for Partial method?

Partial methods are mainly useful in auto-generated code situations. A code generating tool might know that there are certain extension points that some users are going to be interested in customizing. For example, the objects created in LINQ to SQL have partial methods like OnLoaded, OnCreated, OnPropertyNameChanging, and OnPropertyNameChanged. The auto-generated code calls the OnCreated partial method from its constructor. If you want to run custom code when one of these objects is created you can create a partial class and define the body for the OnCreated partial method.

13. Why do we go for Partial class?


  1. Improve the readability of extremely large classes by partitioning related methods into separate files.
  2. Partial classes enable the code generator to generate code in one file while the developer who may need to extend the auto-generated logic can do so in a separate file, which eliminates the worry that the code generator might overwrite a developer's customizations.

14. Where we use Partial method and class?

Partial classes and partial methods are most commonly used in auto-generated code. It provides a simple and safe way to add new functionality or extend existing functionality of auto-generated code.

15. What are restrictions for Partial method?


  1. Partial definitions must preceded with the key word "Partial"
  2. Method signature should be same in both partial class file
  3. We cannot have partial implementation in one file and another implementation in other file. We can have declaration in one file and implementation in another file.

16. What is mean by Static class?

Static class is used to create attributes and methods that can be accessed without creating the instance of the class. Static classes are loaded automatically by the .NET Framework when application or assembly is loaded. 'Static' key word is used to mention the static class. e.g MyStaticClass.PI

Example for Static Class

public static class MyStaticClass
{
public static decimal PI = 3.14M;
public static int Add(int num1, int num2)
{
return num1 + num2;
}
public static string Append(string str1, string str2)
{
return str1 + str2;
}
}
MyStaticClass.PI


17. What is mean by Static method?

Static method can be accessed without creating the instance of the class. 'Static' key word is used to mention the static method. Static methods can be created inside the normal class or static class. If we create the static method inside the normal class, static method will not be able to access by creating instance of the class. e.g Math.Add()

18. Can we override static method?

No, compiler will not allow overriding the static method.

19. What are uses of static class and method?


  1. Compiler will not allow creating the instance of the class
  2. Static class also makes the implementation simpler and faster
  3. Cannot inherit a static class since it is sealed

20. What is static constructor?

A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.

Example:

public class MyStaticClass
{
static int count;

static MyStaticClass()
{
count = 0;
Console.WriteLine("Static class is initialized");
}

public static void MyMethod(string name)
{
Console.WriteLine("Static class is initialized " + name);
}
}

MyStaticClass.MyMethod("John");

Output:

Static class is initialized
Hello John

21. What are shared (VB.NET)/Static(C#) variables?

Static members are not associated with a particular instance of any class, which can be invoked directly from the class level, rather than from its instance

Example

public static double  PI = 3.1457;

22. What is Nested Classes?

Classes with in classes are called as Nested class.

Example

public class MyClassLevel_1
{
public void Display()
{
Console.WriteLine("Level_1");
}
public class MyClassLevel_2
{
public void Display()
{
Console.WriteLine("Level_2");
}

public class MyClassLevel_3
{
public void Display()
{
Console.WriteLine("Level_3");
}
}
}
}

Creating instance of the nested class

MyClassLevel_1 L1 = new MyClassLevel_1();
MyClassLevel_1.MyClassLevel_2 L2 = new MyClassLevel_1.MyClassLevel_2();
MyClassLevel_1.MyClassLevel_2.MyClassLevel_3 L3 = new
MyClassLevel_1.MyClassLevel_2.MyClassLevel_3();
L1.Display();
L2.Display();
L3.Display();

Output
Level_1
Level_2
Level_3


23. What are difference between Singleton and Static class?


  1. Singleton can extend classes and implement interfaces, while a static class cannot implement the interface.
  2. Singleton can be initialized lazily or asynchronously while a static class is generally initialized when it is first loaded.
  3. Singleton class can be extended and it's methods can be overridden.

24. Why Main () method is static?

To ensure there is only one entry point to the application.

25. What is mean by inheritance?

Inheritance is one of the concepts of object-oriented programming, where a new class is created from an existing class. Inheritance class is often referred to as subclasses, comes from the fact that the subclass (the newly created class) contains the attributes and methods of the parent class. This can be used to create a highly specialized hierarchical class structure.

Example of Inheritance

class Circle
{
private double m_radius;

public double Radius
{
get { return m_radius; }
set { m_radius = value; }
}
public double Diameter
{
get { return Radius * 2; }
}
public double Circumference
{
get { return Diameter * 3.14; }
}
public double Area
{
get { return Radius * Radius * 3.14; }
}
}

class Sphere : Circle
{
new public double Area
{
get { return 4 * Radius * Radius * 3.14; }
}

public double Volume
{
get { return 4 * 3.14 * Radius * Radius * Radius / 3; }
}
}


26. Can we inherit multiple classes?

No, multiple inheritances are not supported in .Net. Because consider the provided example. Here there are two Parent class Paretn1 and Parent2. This is inherited by Child class, In GetData method, child call the parent class method PrintData(). In this case which method will be executed? It is very difficult for CLR to identify which method to call. It shows that we multiple inheritance create ambiguity to oops concept. In order to avoid this ambiguity we are going for multiple interface implementations.

public class Parent1
{
public string PrintData()
{
return "This is parent1";
}
}
public class Parent2
{
public string PrintData()
{
return "This is parent2";
}
}

public class Child1 : Parent1, Parent2
{
public string GetData()
{
return this.PrintData();
}
}

27. What is mean by Shadowing?

When the method is defined in base class are not override able and we need to provide different implementation for the same in derived class. In this kind of scenario we can use hide the base class implementation and provide new implementation using Shadows (VB.Net)/new(C#) keyword.

Example:

Public Class ParentClass
Public Sub Display()
Console.WriteLine("Parent class")
End Sub

End Class

Public Class ChildClass
Inherits ParentClass

Public Shadows Sub Display()
Console.WriteLine("Child class")
End Sub
End Class


Dim p As New ParentClass
Dim c As New ChildClass
Dim pc As ParentClass = New ChildClass
p.Display()
c.Display()
pc.Display()

Output:
Parent class
Child class
Parent class


28. How a base class method is hidden?

Using new keyword in the derived class, base class method can be hidden or suppressed. New implementation can be added to the derived class.

29. What does the keyword virtual mean in the method definition?

The method can be over-ridden.

30. How method overriding different from overloading?

If we are overriding the method, derived class method behavior is changed from the base class. In Overloading, method with same name by different signature is used.

Example:

{
public virtual void Display()
{
Console.WriteLine("ParentClass");
}
}

public class ChildClass : ParentClass
{
//Example for method override
public override void Display()
{
Console.WriteLine("ChildClass");
}

//Example for method overload
public void Display(string name)
{
Console.WriteLine(name);
}
//Example for method overload
public void Display(string name, string country)
{
Console.WriteLine("Name:"+name +"Country: "+ country );
}
}


ParentClass p = new ParentClass();
ChildClass c = new ChildClass();
ParentClass pc = new ChildClass();
p.Display();
c.Display();
pc.Display();
 
OutPut:
ParentClass
ChildClass
ChildClass


31. Can you declare the override method static while the original method is non-static?

No

32. What is mean by Sealed Class?

Class which cannot be inherited is called as sealed class. If we need to prevent a class from being inherited, use “Sealed” keyword. But sealed class can inherited from other classes.

Example:

public class MyBaseClass
{
public void Display()
{
Console.WriteLine("Base class");
}
}

//Compile Success: This class cannot be inherited
public sealed class MySealedClass:MyBaseClass
{
public void Display()
{
base.Display();
Console.WriteLine("Sealed class");
}
}

//Compilation Error: cannot derive from sealed type MySealedClass
public class MyChildClass : MySealedClass
{

}

33. Can you allow class to be inherited, but prevent the method from being over-ridden?

Yes, just leave the class public and make the method sealed.

34. Will sealed class allows inheritance, if not why?

Sealed means it is not inheritable

35. What are the advantages of Private constructor?


  1. Private constructor will prevent the user from creating the instance of the class which contains only static members.
  2. Private constructor are used for implementing the singleton pattern

36. While using inheritance, derived class construct will call base class constructor?

Yes, base class constructor will be called before child class constructor

37. Overloaded constructor will call default constructor internally?

No, overload constructor will not call default constructor

38. What is difference between Overrides and Overridable?

Overridable (VB.Net)/ virtual (C#) is used in parent class to indicate that a method can be overridden. Overrides(VB.Net)/ override(C#) is used in the child class to indicate that you are overriding a method.

39. What is Method overloading?

Method overloading occurs when a class contains two methods with the same name, but different signatures.

40. What is operator overloading?

Operator overloading is used to provide a custom functionality to existing operators. For Example +,-,* and / operators are used for mathematical functionality. But we can overload these operators to perform custom operation on classes or structure.

Example:

To concatenate the two strings we have to use Concat method

Dim str1, str2, str3 As String
str1 = "Hello"
str2 = "world"
str3 = String.Concat(str1, str2)

But .Net provides in build operator overloading for string we can use ‘+’ operator for concatenating the string value

str3=str1+str2

Similarly we can also implement operator overloading for classes or structure

Employee3= Employee1 + Employee2

41. What is mean by abstraction?

Abstraction is the process of showing necessary information and hiding unwanted information. Let us consider the "CalculateSalary" in your Employee class, which takes EmployeeId as parameter and returns the salary of the employee for the current month as an integer value. Now if someone wants to use that method. He does not need to care about how Employee object calculates the salary? An only thing he needs to be concern is name of the method, its input parameters and format of resulting member

42. What is mean by abstraction class?

Abstract classes contain one or more abstract methods that do not have implementation. An abstract class is a parent class that allows inheritance but can never be instantiated. Abstract classes allow specialization of inherited classes.

43. What id mean by Interface?

Interface defines the set of properties, signature of the methods and events. It does not include any implementation. Class which implements the interface can provide the behavior to the implemented method. For example two class MyEnglishClassand MyFreanchClass implementing same interface and provide two different set of behavior in their implementation.

public interface IMyInterface
{
string Hello(string name);
}

public class MyEnglishClass:IMyInterface
{
public string Hello(string name)
{
return "Hello " + name;
}
}

public class MyFrenchClass : IMyInterface
{
public String Hello(string name)
{
return "allo " + name;
}
}


44. What is difference between Abstract class and Interface?


  • In Interface all the method must be abstract; in abstract class we can have both abstract and concrete methods.
  • Access modifiers cannot be specified in interface because it should always be public; in Abstract class, we can specify the access modifier.

45. In which Scenario you will go for Abstract or Interface Class?

Abstract classes are useful when creating components because they allow you specify an invariant level of functionality in some methods, but leave the implementation of other methods until a specific implementation of that class is needed. They also version well, because if additional functionality is needed in derived classes, it can be added to the base class without breaking code.

Interfaces are often used to describe the peripheral abilities of a class, not its central identity, e.g. an Automobile class might implement the Recyclable interface, which could apply to many otherwise totally unrelated objects.

46. What is mean by polymorphism?

Polymorphism means the ability to take more than one form. An operation may exhibit different behaviors in different instances. The behavior depends on the data types used in the operation. Polymorphism is extensively used in implementing Inheritance.

47. What are different types of polymorphism?

There are two types of polymorphism

Static polymorphism - defining the method with same name and different signature is called as static polymorphism. In the below example there are three different Add() functionality this Add() will be executed based on the parameter passed.

Example :

public int Add(int a, int b)
{
return a + b;
}

public double Add(double a, double b)
{
return a + b;
}

public long Add(long a, long b)
{
return a + b;
}


Dynamic polymorphism – Dynamic polymorphism can be implemented using Virtual and Override keyword. By using polymorphism, each derived class can have its own behavior, Even though classes are derived or inherited from the same parent class

Example:

In the below example ClassB is inherited from ClassA. ClassB can have its own behavior by overriding the parent class method. Parent class method should be represented with virtual keyword to override the same method in derived class.

public class ClassA
{
public virtual void Display()
{
Console.WriteLine ( "ClassA");
}
}

public class ClassB:ClassA
{
public override void Display()
{
Console.WriteLine ( "ClassB");
}
}

static void Main(string[] args)
{
ClassA a = new ClassA();
ClassB b = new ClassB();
ClassA c = new ClassB();
a.Display();
b.Display();
c.Display();
Console.ReadLine();

}

OutPut:
ClassA
ClassB
ClassB



48. What you mean by Encapsulation?

Encapsulation is the procedure of covering up of data and functions into a single unit and protects the data from the outside world. Example “Class” only public functions and properties are exposed; functions implementation and private variables are hidden from outside world.

49. What is difference between data encapsulation and abstraction?

Abstraction refers to the act of representing essential features without including the background details or explanations. Storing data and functions in a single unit is called as encapsulation.

50. What is mean by Delegate?

Delegate is a type that holds a reference to a method or a function. . Once a delegate is assigned a method, it behaves exactly like that method. We can call the method using delegate instead of directly calling the method. Using delegate, we can also pass the parameter and get return value. Any method with matched the signature of the delegate can be assigned. Simply we can say .NET implements the concept of function pointers using delegate.

Example:

There are three step to following for using Delegate


  • Declaration
  • Instantiation
  • Invocation

In the below example we have declared the new delegate “MyDelegate”, which accept string as parameter and return value as string. Two methods SayHello and SayBye function will be called using delegate.

//Declaring the delegate
delegate string MyDelegate(string name);

//function called by delegate dynamically
private static string SayHello(string name)
{
return "Hello " + name;
}

private static string SayBye(string name)
{
return "Bye " + name;
}


After declaration of delegate, we have initialized with SayHello function. Now this delegate will hold reference to specified function. Function will be called using Invoke () method of delegate. In this example we have called two methods (SayHello and SayBye) with same signature(parameter type and return type).

static void Main(string[] args)
{

//Initialllizing delegate with function name
MyDelegate delg = new MyDelegate(SayHello);
//Invoking function using delegate
Console.WriteLine(delg.Invoke("Sam"));

delg = new MyDelegate(SayBye);
//Invoking diffent function using same delegate
Console.WriteLine(delg.Invoke("Sam"));

Console.ReadLine();
}

OutPut:
Hello Sam
Bye Sam


51. What’s a multicast delegate?

It’s a delegate that stores the address of multiple methods and eventually fires off several methods. Multicast delegate must have a return type of void.

52. What is an Asynchronous delegate?

When you invoke a delegate asynchronously, no new thread is created. Instead, the CLR automatically assigns a free thread from a small thread pool that it maintains. Typically, this thread pool starts with one thread and increases to a maximum of about 25 free threads on a single-CPU computer. As a result, if you start 50 asynchronous operations, one after the other, the first 25 will complete first. As soon as one ends, the freed thread is used to execute the next asynchronous operation.

53. What is mean by Events?

Events are nothing but a publisher and subscriber model. Any subscriber who is interested in receiving notification from the publisher can subscribe the events. If source event is fired or publisher raises the event, a notification will be send to all subscribers. One publisher can have multiple subscribers. Internally events will try to make use of delegate for this publisher, subscription model.

Example:

In the below example, we have created new event called "SampleEvent" and this event will be fired once MyMethod() is called. Anyone who wants to subscribe to this event can create a instance of the MyClassWithEvent and add handler to the event. So when ever event is raised, add handler method will be called.

Public Class MyClassWithEvent

'Created New Event, which will return a message to all subscriber
Event SampleEvent(ByVal message As String)

'Event will be fired once this method is called
Public Sub MyMethod()
Console.WriteLine("MyMethod is called")
'Raising the event with message
RaiseEvent SampleEvent("Event is Raised from MyClassWithEvent")
End Sub
End Class

Module Module1

Sub Main()

Dim c As New MyClassWithEvent
'First subscriber of the event
AddHandler c.SampleEvent, AddressOf EventSubscriber1
'Second subscriber of the event
AddHandler c.SampleEvent, AddressOf EventSubscriber2
c.MyMethod()
Console.ReadLine()
End Sub

Private Sub EventSubscriber1(ByVal message As String)
Console.WriteLine("Subscriber 1")
Console.WriteLine("Message: " + message)
End Sub

Private Sub EventSubscriber2(ByVal message As String)
Console.WriteLine("Subscriber 2")
Console.WriteLine("Message: " + message)
End Sub
End Module

OutPut:
MyMethod is called
Subscriber 1
Message: Event is Raised from MyClassWithEvent
Subscriber 2
Message: Event is Raised from MyClassWithEvent


54. Can event’s have access modifiers?

Yes, Event’s can have access modifier, if we mention it as Protected events can be subscribed only within inherited class, If you mention it as Internal(C#)/Friends(VB.Net) it can be subscribed by all class inside the assembly. If you mention it as Private it can subscribed with in class where it is declared.

55. Can we have static/shared events?

Yes, we can have static(C#)/shared(VB.Net) event, but only shared method can raise shared events.

56. Can we have different access modifier for Get/Set of the properties?

Yes, in C# 3.0 and above, we can use different access modifier for Get/Set of the properties, but this is not possible in C#2.0 and lower

57. What is an indexer?

An indexer is an accessor that enables an object to be treated in the same way as an array. An indexer is considered when a class is better represented as a virtual container of data that can be retrieved or set using indices. Since an indexer is nameless, its signature is specified by the keyword “this” followed by its indexing parameters within square brackets.

Example:

In the below example we have created new index for class of type string. During get and set operation string manipulations are done.

public class MyClassForIndexer
{
private string m_Name = "This is example for indexer";
public string this[int index]
{
get
{
return m_Name.Substring( index);
}
set
{
m_Name = m_Name.Insert(index, value);
}
}
}
MyClassForIndexer ind = new MyClassForIndexer();
Console.WriteLine (ind[0]);
ind[7] = "Appended String";
Console.WriteLine(ind[0]);
Output:
This is example for indexer
This isAppended String example for indexer


58. What is ENUM?

ENUM means Enumeration; it is used to group related sets of constants. To create a enumeration you use the Enum statement

Example:

Enum Months
January = 1
Feburary = 2
March = 3
April = 4
May = 5
June = 6
July = 7
August = 8
September = 9
October = 10
November = 11
December = 12
End Enum


LINQ Interview Questions

1. What is mean by LINQ?

LINQ stands for Language Integrated Query. It is a uniform platform for any kind data. It allows us to write a query against Object Collection, Database, XML or other Data source in a standard form without having a separate Query Language.

2. How LINQ works?

Consider the sample customer class with two public members Name and City.

public class Customer
{
public string Name;
public string City;
}


In a console application, customer list with different Name and city are added. Using LINQ retrieve all the customers located in "Coimbatore" city and displays the name of the customer.

//Added a list of customers to the Customers collection list
List Customers = new List(){
new Customer(){Name="Sam",City="Coimbatore"}
,new Customer(){Name="Ram",City="Chennai"}
,new Customer(){Name="Sasi",City="Coimbatore"}};
//Using LINQ to retrive all the customers located in Coimbatore city
var query = from c in Customers
where c.City == "Coimbatore"
select c;
//Displaying all the customer located in Coimbatore city
foreach (Customer c in query)
{
Console.WriteLine(c.Name);

}
Console.ReadLine();
}



The compiler generates the following query for the LINQ

IEnumerable query = Customers.Where(c => c.City == "Coimbatore");

In this compiler generated code, "Where" is a extension method features introduced in C# 3.0 to filter the data based on condition. LINQ make use of these features to query data from object collection. Similar to the Where, we have Select, OrderBy, etc extension methods supported for object collection.

This query will be executed to retrieve data from the collection

3. How will you work with relative model using LINQ?

Using "Join" keyword we can describe relation between two entities as like SQL join statement. E.g In the below query we are joining the Customer collection with Orders collection using CustomerID members. End result we are returning new anonymous type with CustomerID, customer name, orderID as member.

var query = from c in Customers
join o in Orders
on c.CustomerID equals o.Customer.CustomerID
select new { c.CustomerID, c.Name, o.OrderID };


4. In given line of LINQ, when actual query will be executed and why?

In general, a LINQ query is not really executed until there is access the query result, because it describes set of operations that will be performed when necessary. In the below example actual query is executed only in the foreach loop

//Added a list of customers to the Customers collection list
List Customers = new List(){
new Customer(){Name="Sam",City="Coimbatore"}
,new Customer(){Name="Ram",City="Chennai"}
,new Customer(){Name="Sasi",City="Coimbatore"}};
//Using LINQ to retrive all the customers located in Coimbatore city
var query = from c in Customers
where c.City == "Coimbatore"
select c;
//Displaying all the customer located in Coimbatore city
foreach (Customer c in query)
{
Console.WriteLine(c.Name);

}


5. What is mean by declarative programming?

Declarative programming is a programming paradigm that expresses the logic of a computation without describing its control flow. There is main difference between filtering data using SQL query and C# (2.0) language such as table for SQL or an array for C# or VB.net. SQL describes what you want, where as in C# describe how to obtain the expected result. In SQL the selection of the best algorithm to implement the "How" is the responsibility of the query engine. It shows that SQL query engine has more freedom to apply optimization than c#.

6. Is LINQ is Type safe or not?

Data used in the LINQ area always strongly typed, including both the queried collections and the singe entities that are read and returned.

7. What is the use of "Yield" type?

Yeild key word is used to iterate through objects returned by a method. Method with IEnumerable return type can be used with Yeild type.

Example:

public static IEnumerable Power(int num, int exponent)
{
int counter = 1;
int result = 1;
//Loop till the power count reach exponent value
while (counter < exponent)
{
result = result * num;
counter++;
//Returns power of num at each level e.g num, num^2, num^3....
yield return result;
}
}


8. How will you map class with database table in LINQ? Or How will you create Entity class in LINQ?

Class and Database table can be mapped using Table and Column attribute. Table Attribute has Name property to specify the name of the database table. If Name property is not supplied then LINQ-> SQL will assume database table has the same name as the class.Column attribute has few properties which is used to customize the exact mapping between entity and database.

[Table(Name = "Customers")]
public class Customer
{
[Column(IsPrimaryKey = true)]
public string CustomerID;
[Column]
public string Name;
[Column]
public string City;
}


9. Why "from" clause is stated before "select" clause in LINQ which is not available in SQL?

In LINQ, all the query starts with a "from" clause and ends with "Select" clause because Microsoft want to provide IntelliSense capabilities within the remaining part of the query which make writing rest part of the query easier.

10. What is difference between LINQ->SQL and LINQ->Entity?


  • Linq-to-SQL is for direct queries using SQL Server. It's a mapping technology to map SQL Server database tables to .NET objects.
  • Linq-to-Entities is Linq used while using Microsoft's Entity Framework, regardless of db server

11. What are different operators used in LINQ?


  1. Where Operators - Where
  2. Projection Operators - Select, SelectMany
  3. Ordering Operators - OrderBy , OrderByDescending, ThenBy, ThenByDescending, Reverse
  4. Grouping Operators - Group By
  5. Join Operators - Join, GroupJoin
  6. Set Operators - Distinct, Union, Intersect, Except
  7. Aggregate Operators - count, LongCount, Sum,Min,Max, Avagrage, aggregate
  8. Generation Operators - Range, Repeat, Empty
  9. Qualifiers Operators -Any, All, Contains,
  10. Partitioning Operators -Take, TakeWhile, Skip, SkipWhile
  11. Element Operators - First, FirstOrDefault,Single, SingleOrDefault, ElementAt, ElementAtOrDefault, DefaultEmpty
  12. Other Operators - Concat, SequenceEqual

12. What are two main concepts in LINQ?

Two main concepts which is used to understand the LINQ are Deferred query evaluation and Extension method


  • Deferred Query Evaluation - LINQ queries are not evaluated when it is defined but when it is used. It is useful by defining once and used many times when it is required. Result of the query expression will always be based on latest updated content.
  • Extension Method - This allows developer to add functionality in existing class without modifying the existing class or recompiling the existing class or extending the existing class. LINQ make use of this extension method for manipulating data e.g Where, Select...etc

13. What is mean by DLINQ?

DLINQ stands for Data Language Integrated Query, it is also referred to as LINQ to SQL. It is specifically the version of LINQ that focuses on querying data from relational data sources. In Dlinq, DataContext is the main object through which we will be retrieve objects from the database and submit changes back to DB.

14. How SQL query generated from Linq query?

In LINQ, DataContext class is used to communicate between LINQ and SQL. It accept and IConnection class to establish connection with SQL. It uses metadata information to map the Entity with physical structure of database.

[Table(Name = "Customers")]
public class Customer
{
[Column(IsPrimaryKey = true)]
public string CustomerID;
[Column]
public string Name;
[Column]
public string City;
}


15. How will you read data from SQL using Dlinq?

Using DLINQ user can easily read the data from SQL. Visual studio provides inbuilt template to create link between LINQ and SQL.

Example:


  • Create a sample console application and add new item to the project
  • In the shown template select "LINQ to SQL Classes". A new dbml file will be added to your project.
  • Connect to the SQL server using Server Explorer and drag and drop any folder that we need to read the data.
  • This ".dbml" file create a "Employee" Entity mapping to database table. Database column will be mapped to property of the Employee class.


  • Once Table are mapped to Entity, automatically connection string will be added to your application as shown below.

    <connectionStrings>

    <add name="AdventureWorksConnectionString"

    connectionString="Data Source=SARAVANAK-6930\SQLEXPRESS;



    • Initial Catalog=AdventureWorks;Integrated Security=True"


    providerName="System.Data.SqlClient" />

    </connectionStrings>


  • As we discuss DataContext instance is root, through which we can access the corresponding table in database. In the below example I try to read the Employee table with employeeId 1 to 10.
    //Creating connection string for DataContext object
    SqlConnection conn = new SqlConnection();
    string connString = System.Configuration.ConfigurationManager
    .ConnectionStrings["AdventureWorksConnectionString"].ToString();
    conn.ConnectionString = connString;
    //Get the object of the Datacontext
    AdventureWorksDBDataContext adWorksDC = new AdventureWorksDBDataContext(conn);

    //Query from table
    //Read the employee with ID between 1 and 10
    var employees = from emp in adWorksDC.Employees
    where emp.EmployeeID >=1 && emp.EmployeeID<10
    select emp;

    foreach (Employee e in employees )
    {
    Console.WriteLine(String.Format("LoginName: {0}", e.LoginID) );
    }


    Output:


16. How will you Insert record to DB table using LINQ?

A new data record can be inserted to Database table using InsertOnSubmit() method available in DataContext instance. Developer should call the SubmitChanges() method to commit the database transaction else data will not be insert in database table.

Example:

Below sample code shows to insert new Product Category record to database using LINQ.

        //Inserting the Product category into table
ProductCategory cate = new ProductCategory();
cate.ProductCategoryID = 5;
cate.Name = "New Category";
cate.rowguid = System.Guid.NewGuid();
cate.ModifiedDate = DateTime.Now;
adWorksDC.ProductCategories.InsertOnSubmit (cate);
adWorksDC.SubmitChanges();



17. How to update data using linq?

Database update can be done using "SubmitChanges()" method in DataContext instance.

18. How will you call Store procedure using LINQ?

We can call the store procedure define in DB using "Function" and "Parameter" attribute. Consider the below example where user need to call the store procedure "uspGetEmployeeManagers" using LINQ->SQL, for which method "GetEmployeeManagers" will be decorated with Function attribute which requires "Name" property to mention to which SP need to call. If SP requires parameter value, these values can be passed using "Parameter" attribute. SP can return single or multiple result set. For Single result set we will be mapping with ISingleResult return type for multiple result set method it will return IMultipleResults return type of collection. Objects return by the SP will be mapped to new class with columns are mapped to property of the class.

SP mapped to Method

[System.Data.Linq.Mapping.Function(Name="dbo.uspGetEmployeeManagers")]
public ISingleResult GetEmployeeManagers([System.Data.Linq.Mapping.
Parameter(Name="EmployeeID", DbType="Int")] System.Nullable employeeID)
{
IExecuteResult result = this.ExecuteMethodCall(this,
((MethodInfo)(MethodInfo.GetCurrentMethod())), employeeID);
return ((ISingleResult)(result.ReturnValue));
}


Calling SP using method

////Creating connection string for DataContext object
SqlConnection conn = new SqlConnection();
string connString = System.Configuration.ConfigurationManager
.ConnectionStrings["AdventureWorksConnectionString"].ToString();
conn.ConnectionString = connString;
//Get the object of the Datacontext
AdventureWorksDBDataContext adWorksDC = new AdventureWorksDBDataContext(conn);

//Calling SP using method and iterating through values
foreach (uspGetEmployeeManagersResult e in adWorksDC.GetEmployeeManagers(1))
{
Console.WriteLine(String.Format("EmpID: {0} Name: {1}", e.EmployeeID, e.FirstName));
}
Console.ReadLine();


19. How will you call User Define Function using LINQ?

Similar to calling store procedure, functions also called using "Function" and "Parameter" attribute.

Please refer "How will you call Store procedure using LINQ?" for more information

Example:Function mapped to a method

[System.Data.Linq.Mapping.Function(Name="dbo.ufnGetContactInformation", IsComposable=true)]
public IQueryable GetContactInformation
([global::System.Data.Linq.Mapping.Parameter(Name="ContactID", DbType="Int")] System
.Nullable contactID)
{
return this.CreateMethodCallQuery(
this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), contactID);
}


Calling function using LINQ

//Creating connection string for DataContext object
SqlConnection conn = new SqlConnection();
string connString = System.Configuration.ConfigurationManager
.ConnectionStrings["AdventureWorksConnectionString"].ToString();
conn.ConnectionString = connString;
//Get the object of the Datacontext
AdventureWorksDBDataContext adWorksDC = new AdventureWorksDBDataContext(conn);

//Calling Function by passing parameter as '1'
foreach (ufnGetContactInformationResult c in adWorksDC.GetContactInformation (1))
{
Console.WriteLine(String.Format("ContactID: {0} Name: {1}", c.ContactID , c.FirstName));
}


20. How to provide Ready only access to DB?

Suppose if we need to access data only in a read-only way and if we need to improve performance by disabling DataContext class to modify by using ObjectTrackingEnabled property of the Datacontext class

AdventureWorksDBDataContext adWorksDC = new AdventureWorksDBDataContext(conn);
adWorksDC.ObjectTrackingEnabled = false;


21. How will you enable transaction in LINQ->SQL?

A SubmitChanges() in DataContext call automatically starts a database explicit transaction. Using the TransactionScope class contained in the System.Transaction library will be transparently promoted to a distributed transaction.

Example:

    using (TransactionScope ts = new TransactionScope())
{
//Inserting the Product category into table
ProductCategory cate = new ProductCategory();
cate.ProductCategoryID = 5;
cate.Name = "New Category";
cate.rowguid = System.Guid.NewGuid();
cate.ModifiedDate = DateTime.Now;
adWorksDC.ProductCategories.InsertOnSubmit(cate);
adWorksDC.SubmitChanges();
ts.Complete();
}


22. How to create and delete DB from LINQ?

We can create database using DataContext class, if we have a class derived from DataContext that contains entity definition decorated with Table and Column attributes, we can create the corresponding batabase by calling the "CreateDatabase" method.

Example:

MyDatabaseContext myDBContext = new MyDatabaseContext("Data Source=SARAVANAK-6930;
Initial Catalog=MyNewDatabase;Integrated Security=True");
myDBContext.CreateDatabase();



23. What is the LINQ file extension that interacts with Code Behind's objects?

*.dbml

24. What are the error reporting options during concurrency conflicts?

There are two ways to report conflicts while summiting changes to database using linq.

ContinueOnConflict :- Specifies that all the update to the database to be tried and finally return all conflicts at the end of the process.

FailOnFirstConflict :- Specifies that attempts to update database should stop immediately when first concurrency conflicts are detected and return all the conflicts at that moment. In other words LINQ engine does not continue ahead executing the code.

Example:

adWorksDC.SubmitChanges(ConflictMode.FailOnFirstConflict);

25. What are advantages of LINQ over Store procedure?


  • Debugging SP is very difficult, where as LINQ is simple by using visual studio
  • Compile time safety when your schema changes
  • Deployment is easier in linq everything is compiled to dll, where as in DB we need to manage deployment script.

26. What are disadvantage of LINQ over Store procedure?


  • Store procedure can take full advantage of SQL features where as there will be some features missing in LINQ
  • Store process need only serialize SP name and argument data over the wire while LINQ sends the entire query.
  • Redeployment, if we need any modification, we need to recompile assembly in LINQ, where as in SP it is not the case.

27. What is XLINQ?

XLINQ = LINQ->XML, it is XML programming API to query XML data using LINQ. XLINQ provides power of both DOM and XQuery/XPath through LINQ extension methods to manage and query in-memory XML nodes.

28. How will you create xml document object using XLINQ?

XML Document can be created using XDocument, XDeclaration , XElement, XAttribute instance

Example:

XDocument xDocEmployee = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement("Employee",
new XAttribute("ID", "2012"),
new XElement("FirstName", "Ram"),
new XElement("LastName", "Kumar"),
new XElement("Salary", 10000)));


XML document

<?xml version="1.0" encoding="utf-8" standalone="yes" ?>

<Employee ID="2012">

<FirstName>Ram</FirstName>

<LastName>Kumar</LastName>

<Salary>10000</Salary>

</Employee>

29. How will you read xml content using LINQ?

Consider the xml document with list of employee. Below example gives filtering and reading the employee details based on designation.

XML Document

<?xml version="1.0" encoding="utf-8" ?>

<Employees>

  <Employee ID="101">

    <FirstName>Ram</FirstName>

    <LastName>Kumar</LastName>

    <Designation>SE</Designation>

  </Employee>

  <Employee ID="102">

    <FirstName>Sasi</FirstName>

    <LastName>Kumar</LastName>

    <Designation>SSE</Designation>

  </Employee>

  <Employee ID="103">

    <FirstName>Praveen</FirstName>

    <LastName>prakash</LastName>

    <Designation>SSE</Designation>

  </Employee>

</Employees>

LINQ Query

var employees = 
from e in xDocEmployee.Elements("Employee")
where e.Element("Designation").Value == "SSE"
select new { Name = e.Element("FirstName").Value, ID = e.Attribute("ID").Value };


30. How can we do an order by using LINQ query?

Order by in LINQ is pretty simple. We just need to insert order by before the 'Select' query.

var employees = from emp in adWorksDC.Employees 
where emp.EmployeeID >=1 && emp.EmployeeID<10
orderby emp.EmployeeID
select emp;


31. What is the purpose of LINQ Providers in LINQ?

LINQ Providers are a set of classes that takes a LINQ query and dynamically generates a method that executes an equivalent query against a specific data source.

.Net Threading Interview Questions

1. What is mean by process?

A process is a collection of threads that share the same virtual memory. A process has at least one thread of execution, and a thread always run in a process context.

2. What is Thread?

Threads are the basic unit to which an operating system allocates processor time, and more than one thread can be executing code inside that process.

3. What is Multi-threading?

Multi threading is the collection of thread executed with in the same program to generate the output.

4. What is Multi-tasking?

It's a feature of modern operating systems with which we can run multiple programs at same time example Word, Excel etc.

5. What is the namespace used for threading?

System.Threading

Note: - .NET program always has at least two threads running one is the main program and second is the garbage collector.

6. What is mean by AppDomain?

Operating system process are subdivides into lightweight managed sub processes called application domains. One or more managed threads (represented by System.Threading.Thread) can run in one or any number of application domains within the same managed process. Although each application domain is started with a single thread, code in that application domain can create additional application domains and additional threads.

7. Can you explain in brief how can we implement threading?

This sample explains about the implementation of the threading. Let start this example by creating a class with two methods called "Thread1()", "Thread2()"

  class TestClass
{
public void Thread1()
{
int index = 0;
for (index = 0; index < 100; index++)
{
Console.WriteLine("This is from first thread: {0}", index.ToString());
}
}

public void Thread2()
{
int index = 0;
for (index = 0; index < 100; index++)
{
Console.WriteLine("This is from second thread: {0}", index.ToString());
}
}
}


Create a new console application; in the main method we will be creating the new instance of the Thread and pass the address of the TestClass method as constructor parameter to the Thread class.

Start the Thread by calling the Thread.Start() method.

class Program
{
static void Main(string[] args)
{
TestClass _objTestClass = new TestClass();
Thread th1 = new Thread(new ThreadStart(_objTestClass.Thread1 ));
Thread th2 = new Thread(new ThreadStart(_objTestClass.Thread2));
th1.Start();
th2.Start();
Console.ReadLine();
}


}

Output of the windows is shown below. In which we can identify that Thread1 and Thread 2 are called simultaneously. We cannot define when Thread1 or Thread2 is called.


8. What are different levels of threading priorities are available?

Priority of the thread execution can be changed by using the "Priority" property of the thread instance.

Example:

ThreadName.Priority = ThreadPriority.BelowNormal

Following are the different level of the Thread priority available


  • ThreadPriority.Highest
  • ThreadPriority.AboveNormal
  • ThreadPriority.Normal
  • ThreadPriority.BelowNormal
  • ThreadPriority.Lowest

9. What is mean by Theard.Sleep()?

The Thread.sleep() method effectively "pauses" the current thread execution for a given period of time. This method takes an integer value as parameter that determines how long the thread needs to be paused.

Example:

System.Threading.Thread.Sleep(4000);

10. How can we make a thread sleep for infinite period?

You can also place a thread into the sleep state for an indeterminate amount of time by calling Thread.Sleep (System.Threading.Timeout.Infinite). To interrupt this sleep you can call the Thread.Interrupt method.

11. What is mean by Thread.Suspend and Resume?


  • Thread.Suspend() - this method is used to suspend the thread execution. If the method is already suspended, it does not have any effect.
  • Thread.Resume() - Suspended thread can be resumed using this method call.

12. What is difference between Thread.Sleep and Thread.Suspend()?


  • Thread.Sleep() method will immediately place the thread under wait state, where as
  • Thread.Suspend() method will not go into wait state until .net determines that it is in a safe place to suspend it.

13. What the way to stop a long running thread?

Thread.Abort() stops the thread execution at that moment itself.

14. How will we get current thread?

Using System.Threading.Thread.CurrentThread we will be able to get the current thread instance.

15. How we can make the thread run in background?

By setting ThreadName.IsBackground = true will run the Thread in background process.

Example:

TestClass _objTestClass = new TestClass();
Thread th1 = new Thread(new ThreadStart(_objTestClass.Thread1 ));
th1.IsBackground = true;
th1.Start();

16. What are Daemon threads and how can a thread is created as Daemon?

Daemon thread's are threads run in background and stop automatically when nothing is running program. Example of a Daemon thread is "Garbage collector". Garbage collector runs until some .NET code is running or else it's idle. Thread can be made as Daemon by Thread.Isbackground=true

17. How to debug the thread?

Threading application can be debugged using Debug->Windows->Threads or "Ctrl+Alt+H"


18. How we can use the same variable by multiple thread or Thread safe?

In certain scenario, multiple threads must need to access the same variable at the same time; this will leads to some other problem. This can be avoided by using SynchLock. So until first thread released its variable, other thread will not be able to access the variable.

Example:

SyncLock (X)
'some operation with "X"
End SyncLock

19. What are different states of a thread?

Thread status can be known by using ThreadName.ThreadState property. ThreadState enumeration has all the values to detect a state of thread. Some sample states are Aborted, Running, Suspended, etc

Followings are the list of state of a thread.


  • ThreadState.Aborted
  • ThreadState.AbortRequested
  • ThreadState.Background
  • ThreadState.Running
  • ThreadState.Stopped
  • ThreadState.StopRequested
  • ThreadState.Suspended
  • ThreadState.SuspendRequested
  • ThreadState.Unstarted
  • ThreadState.WaitSleepJoin

20. Can we use events with threading?

Yes, we can use events with thread; this is one of the techniques to synchronize one thread with other.

21. What is Event Wait Handle in threading?

Event Wait Handle allows threads to communicate with each other by signaling and by waiting for signals. Event wait handles are wait handles that can be signaled in order to release one or more waiting threads.

22. What is difference between Monitor object and EventWaitHandle?

Both EventWaitHandles and Monitors are used to synchronize activities But Named event wait handles can be used to synchronize activities across application domains and processes, whereas monitors are local to an application domain.

23. What is mean by ManualResetEvent and AutoResetEvent?

Threads that call one of the wait methods of a synchronization event must wait until another thread signals the event by calling the Set method. There are two synchronization event classes. Threads set the status of ManualResetEvent instances to signaled using the Set method. Threads set the status of ManualResetEvent instances to no signaled using the Reset method or when control returns to a waiting WaitOne call. Instances of the AutoResetEvent class can also be set to signaled using Set, but they automatically return to nonsignaled as soon as a waiting thread is notified that the event became signaled.

24. What is mean by Deadlock in Threading?

Dead lock issue will be raised when multi thread try to access the same variable. Example when both the threads try to hold and monitor the variable at same time. Each thread monitor and wait for another thread to release the variable. Since no one is hold the variable and both the threads are waiting for the other thread to release each other, at last application hangs. This is called as Deadlock.

Thursday, February 06, 2014

Retrive DynamicEntity from FetchXml query

Hi everyone , some times you need to supply a query form outside the code in a MS CRM solution. Using the following code snippet we can create the query dynamically and pass it to the code to get dynamic entities.

Now suppose i need to execute this query

<fetch mapping='logical'>
    <entity name='contact'>
        <filter type='and'>
            <condition attribute='lastname' operator='eq' value='xyz’/>
        </filter>
    </entity>
</fetch>

to get a list of dynamic entitles

Now either we can break the query and let the code just to have the logical section form this fetchXml or we can use the fetchXml as a whole. Now if i break the query  like

<entity name='contact'>
<filter type='and'>
<condition attribute='lastname' operator='eq' value='xyz’/>
</filter>
</entity>
And inside the code i can

		// here new_criteria contains the logical section from fetch xml(see above)
StringBuilder QueryBuilder = new StringBuilder(new_criteria);
QueryBuilder.Insert(0, "", 1);
QueryBuilder.Insert(QueryBuilder.Length, "
", 1);





Now the next thing i need to do is to convert his query to a CRM QueryExpression, thankfully CRM SDK contains some request & response classes to help






//This is the request/response object to Convert the FetchXML into a query expression.
FetchXmlToQueryExpressionRequest conversionRequest = new FetchXmlToQueryExpressionRequest
{
FetchXml = QueryBuilder.ToString()
};

// and here is the response
FetchXmlToQueryExpressionResponse conversionResponse =
(FetchXmlToQueryExpressionResponse)crmService.Execute(conversionRequest);




Now as we know that the query will results multiple records we will use it in RetriveMultiple


//Retrive Multiple Request
RetrieveMultipleRequest retrieve = new RetrieveMultipleRequest();
retrieve.Query = conversionResponse.Query;
retrieve.ReturnDynamicEntities = true;

//Retrieve Multiple Response
RetrieveMultipleResponse retrieved = (RetrieveMultipleResponse)crmService.Execute(retrieve);

if (retrieved.BusinessEntityCollection.BusinessEntities.Count > 0 )
{
for (int entityCount = 0; entityCount < retrieved.BusinessEntityCollection.BusinessEntities.Count; entityCount++)
{
// retrive the first entity form the collection
DynamicEntity entity = (DynamicEntity)retrieved.BusinessEntityCollection.BusinessEntities[entityCount];


}
}



Converting a JavaScript Date object into the proper XML string


function SwConvertDateTimeToXml(dateTime) {

var offset = (ORG_TIMEZONE_OFFSET < 0) ? -ORG_TIMEZONE_OFFSET : ORG_TIMEZONE_OFFSET;
var timezoneOffsetHours = Math.floor(offset / 60);
var timezoneOffsetMinutes = offset - timezoneOffsetHours * 60;

var s =
dateTime.getYear().toString() + "-" +
SwGetFormattedDatePart(dateTime.getMonth() + 1) + "-" +
SwGetFormattedDatePart(dateTime.getDate()) + "T" +
SwGetFormattedDatePart(dateTime.getHours()) + ":" +
SwGetFormattedDatePart(dateTime.getMinutes()) + ":" +
SwGetFormattedDatePart(dateTime.getSeconds()) +
((ORG_TIMEZONE_OFFSET < 0) ? "-" : "+") +
SwGetFormattedDatePart(timezoneOffsetHours) + ":" +
SwGetFormattedDatePart(timezoneOffsetMinutes);

return s;
}

function SwGetFormattedDatePart(value) {
return (value < 10) ? ("0" + value.toString()) : value.toString();
}

Converting an XML date string to a JavaScript Date object


function SwConvertXmlToDateTime(crmDateTimeString) {
var dateTimeParts = crmDateTimeString.split("T");
var dateString = dateTimeParts[0];
var timeString = dateTimeParts[1];
var dateParts = dateString.split("-");
var timeZoneSeparator = (timeString.indexOf("-") != -1) ? "-" : "+";
var timeZoneParts = timeString.split(timeZoneSeparator);
var timeParts = timeZoneParts[0].split(":");

var date = new Date(SwParseInt(dateParts[0]), SwParseInt(dateParts[1]) - 1, SwParseInt(dateParts[2]), SwParseInt(timeParts[0]), SwParseInt(timeParts[1]), SwParseInt(timeParts[2]));
return date;
}

function SwParseInt(value) {
if ((value.length == 2) && (value.substr(0, 1) == "0")) {
value = value.substr(1, 1);
}

return parseInt(value);
}

CrmService proxy for plug-ins that execute in the child pipeline.

We always come across creating a CrmService Proxy for plug-ins that execute in the child pipeline. In a Child pipeline, you must instantiate the CrmService or MetadataService manually. We just need to check the InvocationSource Property (Child = 1, Parent = 0) of the IPluginExecutionContext. Pass the InvocationSource Property value to the below method.

Below is very simple code which creates a proxy.




public class CRM4_ServiceProx
{


/// The execution context that was passed to the plug-in's Execute method.
/// Set to True to use impersonation.
/// A CrmServce instance.
private CrmService CreateCrmService(IPluginExecutionContext context, Boolean flag)
{
CrmAuthenticationToken authToken = new CrmAuthenticationToken();
authToken.AuthenticationType = 0;
authToken.OrganizationName = context.OrganizationName;

// Include support for impersonation.
if (flag)
authToken.CallerId = context.UserId;
else
authToken.CallerId = context.InitiatingUserId;

CrmService service = new CrmService();
service.CrmAuthenticationTokenValue = authToken;
service.UseDefaultCredentials = true;

// Include support for infinite loop detection.
CorrelationToken corToken = new CorrelationToken();
corToken.CorrelationId = context.CorrelationId;
corToken.CorrelationUpdatedTime = context.CorrelationUpdatedTime;
corToken.Depth = context.Depth;
//Get the server name form registry
RegistryKey regkey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\MSCRM");

service.Url = String.Concat(regkey.GetValue("ServerUrl").ToString(), "/2007/crmservice.asmx");
service.CorrelationTokenValue = corToken;

return service;
}

}


List of Webservices in Dynamics CRM 2011

Here is the list of services avaialable in CRM 2011. May sametimes you make use of some of it http:// crmserver:5555/AppWebServices/ActivitiesWebService.asmx http:// crmserver:5555/AppWebServices/AdvancedFind.asmx http:// crmserver:5555/AppWebServices/Annotation.asmx http:// crmserver:5555/AppWebServices/AppGridWebService.asmx http:// crmserver:5555/AppWebServices/AssociateRecords.asmx http:// crmserver:5555/AppWebServices/BulkDelete.asmx http:// crmserver:5555/AppWebServices/Connection.asmx http:// crmserver:5555/AppWebServices/Currency.asmx http:// crmserver:5555/AppWebServices/CustomerService.asmx http:// crmserver:5555/AppWebServices/DashboardWebService.asmx http:// crmserver:5555/AppWebServices/DateTimeService.asmx http:// crmserver:5555/AppWebServices/DialogList.asmx http:// crmserver:5555/AppWebServices/DocumentManagementWebService.asmx http:// crmserver:5555/AppWebServices/DuplicateDetection.asmx http:// crmserver:5555/AppWebServices/EmailTemplateService.asmx http:// crmserver:5555/AppWebServices/FormEditorWebService.asmx http:// crmserver:5555/AppWebServices/GanttControlWebService.asmx http:// crmserver:5555/AppWebServices/GoalManagement.asmx http:// crmserver:5555/AppWebServices/ImportJob.asmx http:// crmserver:5555/AppWebServices/ImportWebService.asmx http:// crmserver:5555/AppWebServices/InteractiveWorkflowWebService.asmx http:// crmserver:5555/AppWebServices/LookupMruWebService.asmx http:// crmserver:5555/AppWebServices/LookupService.asmx http:// crmserver:5555/AppWebServices/MailMerge.asmx http:// crmserver:5555/AppWebServices/MarketingAutomation.asmx http:// crmserver:5555/AppWebServices/MergeRecords.asmx http:// crmserver:5555/AppWebServices/MessageBar.asmx http:// crmserver:5555/AppWebServices/MruWebService.asmx http:// crmserver:5555/AppWebServices/OwnerManager.asmx http:// crmserver:5555/AppWebServices/PaneWebService.asmx http:// crmserver:5555/AppWebServices/PresenceService.asmx http:// crmserver:5555/AppWebServices/QueueItem.asmx http:// crmserver:5555/AppWebServices/RecentlyViewedWebService.asmx http:// crmserver:5555/AppWebServices/RegionalOptions.asmx http:// crmserver:5555/AppWebServices/RelatedInformation.asmx http:// crmserver:5555/AppWebServices/RelationshipRolePicklist.asmx http:// crmserver:5555/AppWebServices/reports.asmx http:// crmserver:5555/AppWebServices/ResourceGroupUI.asmx http:// crmserver:5555/AppWebServices/ResourceSpecTree.asmx http:// crmserver:5555/AppWebServices/Ribbon.asmx http:// crmserver:5555/AppWebServices/SalesForceAutomation.asmx http:// crmserver:5555/AppWebServices/SavedQuerySelectorWebService.asmx http:// crmserver:5555/AppWebServices/SchedulePlanning.asmx http:// crmserver:5555/AppWebServices/ScheduleService.asmx http:// crmserver:5555/AppWebServices/ScriptError.asmx http:// crmserver:5555/AppWebServices/Service.asmx http:// crmserver:5555/AppWebServices/Solution.asmx http:// crmserver:5555/AppWebServices/SubjectManager.asmx http:// crmserver:5555/AppWebServices/SystemCustomization.asmx http:// crmserver:5555/AppWebServices/TransactionCurrencyWebService.asmx http:// crmserver:5555/AppWebServices/UserEntityUISettings.asmx http:// crmserver:5555/AppWebServices/UserManager.asmx http:// crmserver:5555/AppWebServices/UserQuery.asmx http:// crmserver:5555/AppWebServices/View.asmx http:// crmserver:5555/AppWebServices/Workflow.asmx http:// crmserver:5555/MSCRMServices/Metadata.asmx http:// crmserver:5555/MSCRMServices/2007/CrmService.asmx http:// crmserver:5555/MSCRMServices/2007/MetadataService.asmx http:// crmserver:5555/MSCRMServices/2007/AD/CrmDiscoveryService.asmx

Wednesday, February 05, 2014

Passing Data Between Plug-ins [Microsoft Dynamics CRM 4.0]

The message pipeline model provides for a PropertyBag of custom data values in the execution context that is passed through the pipeline and shared among registered plug-ins. This collection of data can be used by different plug-ins to communicate information between plug-ins and enable chain processing where data processed by one plug-in can be processed by the next plug-in in the sequence and so on. This feature is especially useful in pricing engine scenarios where multiple pricing plug-ins pass data between one another to calculate the total price for a sales order or invoice. Another potential use for this feature is to communicate information between a plug-in registered for a pre-event and a plug-in registered for a post-event.

The name of the parameter that is used for passing information between plug-ins is SharedVariables. This is a collection of System.Object. A common type of object that is used to fill the collection is DynamicEntity. At run time, plug-ins can add, read, or modify properties in the SharedVariables property bag. This provides a method of information communication among plug-ins.

Note Only types that are XML serializable should be placed in SharedVariables. All types derived from BusinessEntity are XML serializable.

The following code example shows how to use SharedVariables to pass data from a pre-event registered plug-in to a post-event registered plug-in.



using System;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.SdkTypeProxy;

public class AccountSetStatePreHandler : IPlugin
{
public void Execute(IPluginExecutionContext context)
{
// Create or retrieve some data that will be needed by the post event
// handler. You could run a query, create an entity, or perform a calculation.
//In this sample, the data to be passed to the post plug-in is
// represented by a GUID.
Guid contact = new Guid("{74882D5C-381A-4863-A5B9-B8604615C2D0}");

// Pass the data to the post event handler in an execution context shared
// variable named PrimaryContact.
context.SharedVariables.Properties.Add(
new PropertyBagEntry("PrimaryContact", (Object)contact.ToString()));
// Alternate code: context.SharedVariables["PrimaryContact"] = contact.ToString();
}
}

public class AccountSetStatePostHandler : IPlugin
{
public void Execute(IPluginExecutionContext context)
{
// Obtain the contact from the execution context shared variables.
if (context.SharedVariables.Contains("PrimaryContact"))
{
Guid contact =
new Guid((string)context.SharedVariables["PrimaryContact"]);
// Do something with the contact.
}
}
}




Monday, January 13, 2014

Showing/Hiding tabs based on the selection in a picklist

The next script shows one out of three tabs based on the selection in the new_combo field. It hides all tabs if no selection is made or a different value is selected. OnLoad:


// Jscript
//Sanity check: if new_combo is not present on the form, then don't call FireOnChange
if (crmForm.all.new_combo != null) {
crmForm.all.new_combo.FireOnChange();
}

Sunday, January 12, 2014

WCF Interview Questions

1. What is mean by WCF?

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

2. What is the difference between WCF and Web Service?

Features
Web Service
WCF

Hosting
It can be hosted in IIS
It can be hosted in IIS, windows activation service, Self-hosting, Windows service

Programming
[WebService] attribute has to be added to the class
[ServiceContraact] attribute has to be added to the class

Model
[WebMethod] attribute represents the method exposed to client
[OperationContract] attribute represents the method exposed to client

Operation
One-way, Request- Response are the different operations supported in web service
One-Way, Request-Response, Duplex are different type of operations supported in WCF

XML
System.Xml.serialization name space is used for serialization
System.Runtime.Serialization namespace is used for serialization

Encoding
XML 1.0, MTOM(Message Transmission Optimization Mechanism), DIME, Custom
XML 1.0, MTOM, Binary, Custom

Transports
Can be accessed through HTTP, TCP, Custom
Can be accessed through HTTP, TCP, Named pipes, MSMQ,P2P, Custom

Protocols
Security
Security, Reliable messaging, Transactions

3. What is mean by Endpoint?

WCF Services exposes a collection of Endpoints, each Endpoint is a portal for communicating with the world. Endpoint is used to identify the service; it is more are like an address for your home. Each endpoint is used to identify the specific service. One service can have multiple endpoints. Client application will use this endpoint for communication with service. All the WCF communications are take place through end point. End point consists of three components. Address, Binding and Contract

Address - Basically URL, specifies where this WCF service is hosted .Client will use this url to connect to the service. e.g

http://localhost:8090/MyService/SimpleCalculator.svc

Binding - Binding will describes how client will communicate with service. There are different types of protocols available for the WCF to communicate with the Client.e.g: BasicHttpBinding, WSHttpBinding etc

Contract - Contract specifies the what are the collection of operations that are exposed to the outside world. Usually name of the Interface will be mentioned in the Contract, so the client application will be aware of the operations which are exposed to the client.


4. What is mean by Service contract and its use?

Service contract describes the operation (functionality) that service provides. A Service can have more than one service contract but it should have at least one Service contract.

Service Contract can be define using [ServiceContract] and [OperationContract] attribute. [ServiceContract] attribute is similar to the [WebServcie] attribute in the WebService and [OpeartionContract] is similar to the [WebMethod] in WebService. Attributes mentioned in the service contract are optional.

[ServiceContract(SessionMode=SessionMode.Allowed,
ProtectionLevel=System.Net.Security.ProtectionLevel.EncryptAndSign)]
public interface IMathService
{

[OperationContract]
int Add(int a, int b);

[OperationContract]
int Subtract(int a, int b);

// TODO: Add your service operations here
}


5. What is mean by Operational contract and its use?

Operation contract describers the client-callable operations (functions) exposed as service. Only the functions which are decorated with OperationContract will be exposed to outside world. [OpeartionContract] is similar to the [WebMethod] attribute in WebService implementation.

In the below example only Add() and Subtract() methods are decorated with [OperationContract] and So only these two method will be exposed and used by client application.

[ServiceContract()]
public interface IMathService
{
[OperationContract]
int Add(int num1, int num2);

[OperationContract]
int Subtract(int num1, int num2);

int Multiply(int num1, int num2);

int Divide(int num1, int num2);
}

public class MathService : IMathService
{
public int Add(int num1, int num2)
{
return num1 + num2;
}

public int Subtract(int num1, int num2)
{
return num1 - num2;
}

public int Multiply(int num1, int num2)
{
return num1 * num2;
}

public int Divide(int num1, int num2)
{
return num1 / num2;
}
}


6. What is mean by DataContract and its use?

A data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged. Data contract can be explicit or implicit. Simple type such as int, string etc has an implicit data contract. User defined object are explicit or Complex type, for which we need to define a Data contract using [DataContract] and [DataMember] attribute.

A data contract can be defined as follows:


  • It describes the external format of data passed to and from service operations
  • It defines the structure and types of data exchanged in service messages
  • It maps a CLR type to an XML Schema
  • It defines how data types are serialized and deserialized

Example: Create user defined data type called Employee. This data type should be identified for serialization and deserialization by mentioning with [DataContract] and [DataMember] attribute.

[ServiceContract]
public interface IEmployeeService
{
[OperationContract]
Employee GetEmployeeDetails(int EmpId);
}

[DataContract]
public class Employee
{
private string m_Name;
private int m_Age;
private int m_Salary;
private string m_Designation;
private string m_Manager;

[DataMember]
public string Name
{
get { return m_Name; }
set { m_Name = value; }
}

[DataMember]
public int Age
{
get { return m_Age; }
set { m_Age = value; }
}

[DataMember]
public int Salary
{
get { return m_Salary; }
set { m_Salary = value; }
}

[DataMember]
public string Designation
{
get { return m_Designation; }
set { m_Designation = value; }
}

[DataMember]
public string Manager
{
get { return m_Manager; }
set { m_Manager = value; }
}

}


7. What is mean by FaultContract?

Fault contract is used to describe the custom exception thrown by service to client. Only if exception class decorated with Fault contract, it can view in client application.

Service that we develop might get error in come case. This error should be reported to the client in proper manner. Basically when we develop managed application or service, we will handle the exception using try- catch block. But these exceptions handlings are technology specific.

In order to support interoperability and client will also be interested not on how and where cause the error, what went wrong?

By default when we throw any exception from service, it will not reach the client side. WCF provides the option to handle and convey the error message to client from service using SOAP Fault contract.

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

Example:

You can also create your own Custom type and send the error information to the client using FaultContract. These are the steps to be followed to create the fault contract.


  • Define a type using the data contract and specify the fields you want to return.
  • Decorate the service operation with the FaultContract attribute and specify the type name.
  • Raise the exception from the service by creating an instance and assigning properties of the custom exception.

Step 1: Defining the type using Data Contract

[DataContract()]
public class CustomException
{
[DataMember()]
public string Title;
[DataMember()]
public string ExceptionMessage;
[DataMember()]
public string InnerException;
[DataMember()]
public string StackTrace;
}


Step 2: Decorate the service operation with the FaultContract

    [ServiceContract()]
public interface ISimpleCalculator
{
[OperationContract()]
[FaultContract(typeof(CustomException))]
int Add(int num1, int num2);
}


Step 3: Raise the exception from the service

    public int Add(int num1, int num2)
{
//Do something
CustomException ex = new CustomException();
ex.Title = "Error Funtion:Add()";
ex.ExceptionMessage = "Error occur while doing add function.";
ex.InnerException = "Inner exception message from serice";
ex.StackTrace = "Stack Trace message from service.";
throw new FaultException(ex, "Reason: Testing the Fault contract");

}


8. What is mean by Hosting WCF service?

WCF service cannot exist on its own; it has to be hosted in windows process called as host process. Single host process can host multiple services and same service type can be hosted in multiple host process. There are mainly four different way of hosting the WCF service.


  • IIS hosting
  • Self hosting
  • Windows Activation Service
  • Windows Service

9. What are different types of hosting available in WCF?

WCF service can be hosted in four different ways


  • IIS hosting
  • Self hosting
  • Windows Activation Service
  • Windows Service

Multiple hosting and protocols supported by WCF.Microsoft has introduced the WCF concept in order to make distributed application development and deployment simple.

Hosting Environment
Supported protocol

Windows console and form application
HTTP,net.tcp,net.pipe,net.msmq

Windows service application (formerly known as NT services)
HTTP,net.tcp,net.pipe,net.msmq

Web server IIS6
http, wshttp

Web server IIS7 - Windows Process Activation Service (WAS)
HTTP,net.tcp,net.pipe,net.msmq

10. How will you host the WCF using Windows application?

WCF service can be hosted in windows application using "ServiceHost host" class.

Below example describes the hosting of the CalculatorService in windows application

static void Main(string[] args)
{
//Create a URI to serve as the base address
Uri httpUrl = new Uri("http://localhost:8090/MyService/SimpleCalculator");
//Create ServiceHost
ServiceHost host
= new ServiceHost(typeof(MyCalculatorService.SimpleCalculator), httpUrl);
//Add a service endpoint
host.AddServiceEndpoint(typeof(MyCalculatorService.ISimpleCalculator)
, new WSHttpBinding(), "");
//Enable metadata exchange
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
host.Description.Behaviors.Add(smb);
//Start the Service
host.Open();

Console.WriteLine("Service is host at " + DateTime.Now.ToString());
Console.WriteLine("Host is running... Press key to stop");
Console.ReadLine();

}


11. What are different types of binding supported by WCF?


  • BasicHttpBinding
  • WSHttpBinding
  • WSDualHttpBinding
  • WSFederationHttpBinding
  • NetTcpBinding
  • NetNamedPipeBinding
  • NetMsmqBinding
  • NetPeerTcpBinding
  • CustomBinding

12. What is used of different types of binding in WCF?

The real power of wcf resides in binding; each binding are used in different communication scenario. Example BasicHttpBinding are used to communicate outside the firewall or network. Whereas NetTcpbinding are used to communicate between the systems present inside the Local Area Network. The performance for the communication will be increased if we use the NetTcpBinding inside the network. If we use the BasicHttpBinding inside the network, then the performance will degrade. So selection of the right binding of the right communication is very important.

13. What is mean by Message exchange endpoint?

WCF provides rich infrastructure for Exporting, Publishing, retrieving and Importing the metadata (information about the service). WCF uses the Metadata to describe how to interact with the service endpoint. This metadata information of the service is exposed using default endpoint called Message exchange endpoint.

14. What is use of MEX?

Message Exchange Endpoint is used by client application to create the proxy of the service using metadata exposed by MEX.

15. What are different types of bindings supported by MEX?

mexHttpBinding, mexHttpsBinding, mexNamedPipesBinding, mexTcpBinding

16. What is mean by Proxy creation?

The proxy is a class that exposes a single CLR interface representing the service contract. If the service supports several contracts, the client needs a proxy per contract type. The proxy provides the same operations as service's contract, but also has additional methods for managing the proxy life cycle and the connection to the service.

17. What are different types of Proxy creation?

There are different methods available to create the proxy class. These methods are explained by creating the proxy class for the MathService with all some mathematical operation exposed as service.

Method 1:

Using service utility command in visual studio command prompt, we can generate the proxy

Example:

Svcutil "http://localhost:56248/MyMathService/MathService.svc"

Proxy files and its configuration files are generated in default directory of the command prompt MathService.cs and output.config


Method 2: Add Service Reference to the project file

Right click the project file and select "Add Service Reference". Specify the service endpoint address and click "Go" and Math service will be identified and listed. Click OK to create proxy class inside the project application.


Method 3:

By Inheriting ClientBase class

Below example describes the creating the proxy class using Contract information and Channel property of the ClientBase

[ServiceContract]
public interface IMathService
{

[OperationContract]
int Add(int a, int b);

[OperationContract]
int Subtract(int a, int b);
}


public class MyMathServiceProxy : ClientBase
{

public int Add(int a, int b)
{
return this.Channel.Add(a, b);
}

public int Subtract(int a, int b)
{
return this.Channel.Subtract(a, b);
}
}


18. Can we able to call the WCF service without creating Proxy class?

Yes, using "ChannelFactory" we can call the service operation

Example:

private ChannelFactory cf;
private IHelloChannel client;

private void btnSayIt_Click(object sender, EventArgs e)
{
cf = new ChannelFactory("*");
client = cf.CreateChannel();
MessageBox.Show(client.SayHello(txtName.Text));
client.Close();

}



19. What are different types of Behaviors available in WCF?

WCF defines two types of service-side behaviors


  • ServiceBehaviors - It is used to configure service behavior and it will affect all endpoins of the service

    Example: Below service behavior will enable the exposing of service metadata

    <serviceBehaviors>

    <behavior name="ServiceBehavior">

    <serviceMetadata httpGetEnabled="true"/>

    </behavior>

    </serviceBehaviors>


  • EndpointBehaviors - It is used to configure specific endpoint behavior

20. How will you implement function overloading in WCF?

By default WCF will not provide option to overload a function. But method overloading can be achieved using "Name" attribute of the OperationContract.

Below examples describes implementation of function overloading.

[ServiceContract]
public interface IMathService
{

[OperationContract]
int Add(int a, int b);

[OperationContract(Name = "AddDecimal")]
decimal Add(decimal a, decimal b);
}


If we don’t specify the "Name" attribute for the OperationContract. Following error will be displayed while the running the service

Server Error in '/MyMathService' Application.


Cannot have two operations in the same contract with the same name, methods Add and Add in type IMathService violate this rule. You can change the name of one of the operations by changing the method name or by using the Name property of OperationContractAttribute.


21. Will WCF service returns the dataset?

Yes, dataset are serializable object, so WCF service will be able to return the result in dataset format.

22. What is the use of ServiceKnownType attribute?

ServiceKnownType attribute is used to describe the inherited class of the DataContract of the service. Consider a base class and derived class which are decorated with DataContract, when we use base class inside the wcf service, service will be it will able to understand and serialize only the Base class not the derived class. In order to service to know the derived class has to be serialized we need to mention the class name using ServiceKnowType attribute.

Example:

[DataContract]
class Contact
{...}

[DataContract]
class Customer : Contact
{...}

[DataContract]
class Person : Contact
{...}

[ServiceContract]
[ServiceKnownType(typeof(Customer))]
[ServiceKnownType(typeof(Person))]
interface IContactManager
{
[OperationContract]
Contact[] GetContacts( );
}


23. If you use [DataMember] for the private property of the class, will it be exposed to the client application?

No, only public member of the DataContract, which is decorated with DataMember attribute will be exposed to the client.

24. How will you use Enum in WCF?

Enum can be mention in WCF using [EnumMember] attribute

[DataContract]
enum ContactType
{
[EnumMember]
Customer,

[EnumMember]
Vendor,

//Will not be part of data contract
Partner
}


25. What are different levels of service Instance can be managed in WCF?

Instance management refers to the way a service handles a request from a client. Instance management is set of techniques WCF uses to bind client request to service instance, governing which service instance handles which client request.

Basically there are three instance modes in WCF:


  • Per-Call instance mode
  • Per-Session instance mode
  • Singleton Instance Mode

26. What is the mean by Per-Call session?

When WCF service is configured for Per-Call instance mode, Service instance will be created for each client request. This Service instance will be disposed after response is sent back to client.


Example :

[ServiceContract()]
public interface IMyService
{
[OperationContract]
int MyMethod();
}

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class MyService : IMyService
{
public int MyMethod()
{
...
}
}


27. What is mean by Per-Session instance?

When WCF service is configured for Per-Session instance mode, logical session between client and service will be maintained. When the client creates new proxy to particular service instance, a dedicated service instance will be provided to the client. It is independent of all other instance.

Following diagram represent the process of handling the request from client using Per-Session instance mode.


Example :

[ServiceContract()]
public interface IMyService
{
[OperationContract]
int MyMethod();
}

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession )]
public class MyService : IMyService
{
public int MyMethod()
{
...
}
}


28. What is mean by Singleton instance?

When WCF service is configured for Singleton instance mode, all clients are independently connected to the same single instance. This singleton instance will be created when service is hosted and, it is disposed when host shuts down.

Following diagram represent the process of handling the request from client using Singleton instance mode.


Example:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single )]
public class MyService : IMyService
{
public int MyMethod()
{
...
}
}


29. What is the default Instance Management supported by WCF?

Per-Session instance management

30. What are the different ways to deactivate the service Instance?

When service is configured to use Per-Session instance, WCF provides the option of disposing and recreating the instance within same session.

ReleaseInstanceMode property of the OberationalBehavior attribute used to control the instance in relation to the method call.

Followings are the list Release mode available in the ReleaseInstanceMode


  • RealeaseInstanceMode.None
  • RealeaseInstanceMode.BeforeCall
  • RealeaseInstanceMode.AfterCall
  • RealeaseInstanceMode.BeforeAndAfterCall

Example:

[ServiceContract()]
public interface ISimpleCalculator
{
[OperationContract()]
int Add(int num1, int num2);
}
[OperationBehavior(ReleaseInstanceMode=ReleaseInstanceMode.BeforeCall]
public int Add(int num1, int num2)
{
return num1 + num2;
}


31. What is mean by Durable service?

Durable services are WCF services that persist service state information even after service host is restarted or Client. It means that durable services have the capability to restore their own state when they are recycled. It can use data store like SQL database for maintain instance state. It is new feature in .Net 3.5

32. How will you implement the durable service?

Durable service can be created using following steps


  1. Add "DurableService" attribute to the service class
    [DurableService()]
    public class SimpleCalculator : ISimpleCalculator
    {
    }

  2. Use "wsHttpContextBinding" binding for the endpoint address

      <endpoint address="" binding="wsHttpContextBinding"

    bindingConfiguration="browConfig" contract="ISimpleCalculator">


  3. Add <persistenceProvider> tag in web.config, it is used to configure the persistence provider

    <persistenceProvider

      type="System.ServiceModel.Persistence.SqlPersistenceProviderFactory,

           System.WorkflowServices, Version=3.5.0.0, Culture=neutral,

            PublicKeyToken=31bf3856ad364e35" connectionStringName="DurableServiceStore"

                                persistenceOperationTimeout="00:00:10"

                                lockTimeout="00:01:00"

                                serializeAsText="true"/>


33. What is mean by Throttling in WCF?

WCF throttling provides some properties that you can use to limit how many instances or sessions are created at the application level. Performance of the WCF service can be improved by creating proper instance.

Attribute
Description

maxConcurrentCalls
Limits the total number of calls that can currently be in progress across all service instances. The default is 16.

maxConcurrentInstances
The number of InstanceContext objects that execute at one time across a ServiceHost. The default is Int32.MaxValue.

maxConcurrentSessions
A positive integer that limits the number of sessions a ServiceHost object can accept. The default is 10.

34. Will the Callback operation is supported in WCF?

Yes, Service can also call the functions located at the client side.

35. How will you implement Call back service in WCF?

Call back service can be implemented using "wsDualHttpBinding" binding and CallbackContract property in the ServiceContractattribute.

36. What are mean by Two-phase committed protocol?

Consider the scenario where I am having single client which use single service for communication and interacting with single database. In which service starts and manage the transaction, now it will be easy for the service to manage the transaction.

Consider for example client calling multiple service or service itself calling another service, this type of system are called as Distributed Service-oriented application. Now the questions arise that which service will begin the transaction? Which service will take responsibility of committing the transaction? How would one service know what the rest of the service feels about the transaction? Service could also be deployed in different machine and site. Any network failure or machine crash also increases the complexity for managing the transaction.


In order to overcome these situations, WCF come up with distributed transaction using two way committed protocol and dedicated transaction manager.

Transaction Manager is the third party for the service that will manage the transaction using two phase committed protocol.

37. What are different types of Transaction protocol?

There are three different types of transaction protocol


  1. Lightweight protocol

    • This protocol is used to manage the transaction within same Application Domain
    • Best performance compare to other

  2. OleTx protocol

    • This protocol is used to manage the transaction in an intranet and in a windows environment

  3. WS-Atomic Transaction (WSAT) protocol

    • It can propagate the transaction across the firewalls
    • Primarily used in Internet with multiple transaction managers are involved.

38. What are different types of Transaction manager?


  • Lightweight Transaction Manager (LTM)
  • Kernel Transaction Manager (KTM)
  • Distributed Transaction Coordinator (DTC)

39. What is the use of Lightweight Transaction Manager (LTM)?

LTM can only manage a local transaction; that is, a transaction inside a single app domain. The LTM uses the lightweight transaction protocol to manage the two-phase commit protocol.

40. What is the use of Kernel Transaction Manager (KTM)?

The KTM can be used to manage transactional kernel resource managers (KRM) on Windows Vista, specifically the transactional filesystem (TXF) and the transactional registry (TXR). Transaction can involve at most one service, as long as that service does not propagate the transaction to other services.

41. What is the use of Distributed Transaction Coordinator (DTC)?

The DTC is the transaction manager used when transactions flow across the service boundary. The DTC is a system service available by default on every machine running WCF. Each DTC will communicate with other DTC in different machine to maintain the transaction across the network.

42. What are different levels of Currency mode supported in WCF?

Concurrent access to the service instance is governed by the ConcurrencyMode property of the ServiceBehavior attribute. There are three different types of currency mode


  • Single - Only one caller is allowed to access the service instance
  • Multiple - Concurrent calls are allowed on the service instance
  • Reentrant - concurrent calls on the same instance are never allowed but the reentrant service calls out to another service are allowed.

43. What is the use of dispatcher in WCF?

Dispatcher will receive the message from channel and converts the message to a stack frame and calls the service instance for processing.

44. What is Volatile Queued Communication?

In queued communication, the client communicates to the service using a queue. More precisely, the client sends messages to a queue. The service receives messages from the queue. The service and client therefore, do not have to be running at the same time to communicate using a queue.

When you send a message with no assurances, MSMQ only makes a best effort to deliver the message, unlike with Exactly Once assurances where MSMQ ensures that the message gets delivered or, if it cannot be delivered, lets you know that the message cannot be delivered.

In certain scenarios, you may want to send a volatile message with no assurances over a queue, when timely delivery is more important than losing messages.