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

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.
}
}
}




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();
}

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.

Knowing if you are running in CRM 3.0 or CRM 4.0

It's fairly easy to differentiate if your code is running on CRM 4.0 or not. Just pick a method or variable that did not exist in CRM 3.0 and check if it is available:

if (typeof(GenerateAuthenticationHeader) == "undefined") {
alert("Version 3");
}

Reusing code in OnLoad and OnChange event handlers

Somtimes we need to execute the same set of twice once in OnLoad and in OnChange which calls for maintaining two set of codes or copying the same code for other. Again if there is some change in the first one we need to change the second one also.

Here is a simple implementation to avoid it. We will make use of the HTML DOM and include a function it, this function lives until the window is open accessable form all over the form.



var Hello = Function(){
alert("Say hello");
};


// now you can use somthng like this
window.Greet = Hello;

//or

window.Greet = function(){ alert("say hello"); };


To use it you can call this function from any location, like

// calling the function
window.Greet();

Entity PrimaryKey using Metadata Service

Sometimes we need to get the Entity ID for the any custom entity, by default the entityid equals to +"id". So we can get the id for any dynamic entity as

Entity.Properties["entitylogicalname"+"id"];
But this is a snippet for achieving the same using metadata service.


// Get the Primary key from CRM Entity
public string GetEntityPrimaryKey(String EntityName)
{
// Metadata Service
Func myMetaService = () =>
{
// Create an authentication token.
CrmAuthenticationToken token = new CrmAuthenticationToken();
token.OrganizationName = "OrgName";
token.AuthenticationType = 0;

// Create the metadata Web service;
MetadataService metadataService = new MetadataService();
metadataService.Url = "http://:/MSCRMServices/2007/MetadataService.asmx";
metadataService.CrmAuthenticationTokenValue = token;
metadataService.Credentials = System.Net.CredentialCache.DefaultCredentials;
metadataService.PreAuthenticate = true;
return metadataService;
};

// Create the request
RetrieveEntityRequest entityRequest = new RetrieveEntityRequest();
entityRequest.RetrieveAsIfPublished = false;
entityRequest.LogicalName = EntityName;
entityRequest.EntityItems = EntityItems.EntityOnly;

// Execute the request
RetrieveEntityResponse entityResponse = (RetrieveEntityResponse)myMetaService().Execute(entityRequest);

// Access the retrieved entity
EntityMetadata retrievedEntityMetadata = entityResponse.EntityMetadata;
return retrievedEntityMetadata.PrimaryKey;
}

.Net Framework Interview Questions

1. What is mean by .Net Framework?

The .NET framework is a collection of all the tools and utilities required to execute the .NET managed applications on a particular platform.

 

2. What is mean by CLR?

Common Language Runtime is the core component of .Net framework. It is similar to the Java Virtual Machine or JVM in Java, which handles the execution of code and provides useful services for the implementation of the program. It provides a number of services, including the following

  • management (loading and execution)
  • Application memory isolation
  • Verification of type safety
  • Conversion of IL to native code
  • Access to metadata (enhanced type information)
  • Managing memory for managed objects
  • Enforcement of code access security
  • Exception handling, including cross-language exceptions
  • Interoperation between managed code, COM objects, and pre-existing DLLs (unmanaged code and data)
  • Automation of object layout
  • Support for developer services (profiling, debugging, and so on)

 

3. What is difference between managed and unmanaged code?

The managed code is always executed by a managed runtime execution environment like CLR for .Net. Metadata information of the code will be exchanged with runtime, so runtime environment can guarantee what the code is going to do and provide the necessary security checks before executing any piece of code

Code that is directly executed by the Operating System is known as un-managed code. Example applications written in VB 6.0, C++, C, etc are unmanaged code that typically targets the processor architecture and is always dependent on the computer architecture. In unmanaged code the memory allocation, type safety, security, etc needs to be taken care of by the developer.

 

4. What is mean by MSIL?

MSIL or IL stands for Microsoft Intermediate Language; if you compile managed code, the compiler translates your source code into Microsoft intermediate language. MSIL is platform independent language which can be converted to native code while installing software or at runtime by using Just-in compiler.

 

5. What is mean by CTS?

Common type system defines how types are declared, used, and managed in the runtime, and is also an important part of the runtime's support for cross-language integration. CTS is responsible for defining types that can be used across the .Net Languages. CTS Provides the data types, values, object types. This helps developers to develop applications in different languages.

For example, an integer variable in C# is written as int, whereas in VB.Net it is written as integer. Therefore in .Net Framework you have single class called System.Int32 to interpret these variables.

 

6. What is mean by CLS?

Common Language Specification is the subset of CTS; it is specification that defines the set rules and guidelines that all supporting language should follow. It integrate in such a way that programs written in any language can interoperate with one another.

 

7. What is mean by JIT?

Just In Time(JIT) compilers which compile the IL code to native executable code (.exe or .dll) for the specific machine and OS. JIT are slightly different from traditional compilers as they compile the IL to native code only when desired e.g., when a function is called, IL of function's body is converted to native code; just in time of need. If same function is called next time, the CLR uses the same copy of native code without re-compiling. As JIT are aware of processor and OS exactly at runtime, they can optimize the code extremely efficiently resulting in very robust applications.

 

8. What are different types of JIT?

Pre-JIT - Pre-JIT compiles complete source code into native code in a single compilation cycle. This is done at the time of deployment of the application.

Econo-JIT - Econo-JIT compiles only those functions that are called at runtime. However, these compiled functions are removed when they are not required.

Normal-JIT - Normal-JIT compiles only those functions that are called at runtime and they are stored in cache. If same function is called next time, the CLR uses the same copy of compiled code without re-compiling.

 

9. What is mean by Assembly?

  • Assemblies are self-describing installation units, consisting of one or more files.
  • Assemblies are the deployment units of .Net applications. .Net application consists of one or more assemblies.
  • An assembly may also contain references to other assemblies and it include metadata that describes all the types that are defined in the assembly with information about it members-methods, properties, events and fields.
  • One assembly could be a single Dll or exe that includes metadata, or it can be made of different files e.g resource files, modules and an exe.
  • Assembly manifests is a part of the metadata, it describes the assembly with all the information that's needed to reference it and lists all its dependencies.

 

10. What are the features of Assembly?

  • Assemblies are self-describing, it includes metadata that describes the assembly. It does not required to register key as like COM component.
  • Version dependencies are recorded inside an assembly manifest. The version of the referenced assembly that will be used can be configured by the developer and the system administrator.
  • Two different version of same assembly can be used inside single process.

 

11. What are different type's assemblies?

Private assembly- Private assembly is used within your application and it is installed at the same time as the application itself. It will be located in the same directory as the application or subdirectories thereof.

Shared assembly- Shared assemblies are used by several application. Shared assembly must have version number and unique name and it is usually installed in GAC (Global assembly catch). It reduces the need for disk space and memory space.

 

12. What are parts of assembly manifests?

  • Identity - Name, version, culture and public key
  • A list of files - Files belonging to the assembly, it can have one or more files.
  • Lists of referenced assemblies - all assemblies referenced by the assembly are documented inside the manifest.
  • Set of permission requests- these are the permission needed to run the assembly.
  • Exported types - It describes the structures, class with properties, method and events. It is used to create instance of the class.

 

13. What is mean by Namespace?

Namespace Logically group classes, it avoids name clashes between classes.

Example : most of the general purpose .net base classes are in a namespace called System. The base class Array is in this namespace is accessed with full name System.Array.

14. What is difference between Assembly and Namespace?
  • Assembly is physical grouping of classes. Namespace logically groups classes.
  • Single assembly can have different namespaces
  • Sample namespace can be used in different assembly. E.g the assembly mscorlib and system contain the namespace System.Threading

 

15. What is the difference between an executable assembly and a class library?

An executable assembly exists as the .exe file while a class library exists as the .dll file. Executable assembly represent executable applications having some entry (e.g., Main() method in C#). A class library, on the other hand, contains components and libraries to be used inside various applications. A Class library cannot be executed and thus it does not have any entry point.

 

16. What is ILDASM?

ILDASM(Intermediate Language DisAssembler ), this is inbuild tool to view content and manifest of the assembly. We can run the ILDASM by running following exe "C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools\ildasm.exe"

 

17. What is mean by Manifest?

Manifest is used to describe the information about the assembly, it contains following information.

  • Assembly name - Aids in versioning and visibility scope.
  • Version information - The version number is integrated into the assembly's identity.
  • Types - Boundaries and scopes of methods, classes, properties, events and attributes.
  • Locale - Information describing language/culture.
  • Reference - provides information for type references in an assembly and other referenced assemblies.
  • Cryptographic Hash - Public key encoded hash acting as version/security check.
  • Security Permissions - The permissions within the assembly determine the permissions that can be granted for all aspects of the assembly contents.

 

18. How will you created shared assembly?

Shared assembly can be created by signing the assembly. Sets to created shared assembly

  • Create new class library project using visual studio
  • Navigate to the property page of the class library
  • Select "Signing" tab
  • Select "Sign the assembly" check-box
  • Now select < New >... from "Choose a strong name key file" dropdown
  • Enter new Signing key file name and click Ok
  • Next the build the project. Now the shared assembly is ready to use in different project.

 

19. What is the use of Shared Assembly?

If you want to use the same assembly in different projects, we can create a shared assembly and placed inside the GAC(Global assembly Catch). So that assembly is access by all the application. Private assembly also be used in different projects, but we need to copy the private assembly files to different application folder. But if we are using Shared assembly, the assembly file remains in single location.

Shared assembly is highly secured, only administrator can uninstall the shared assembly.

20. What is GAC?

GAC(Global assembly catch) is used to store .Net assembly. It is located in "C:\Windows\assembly"

  • Assembly located in GAC is shared by multiple applications
  • Adding an Assembly to GAC

    "gacutil -i (assembly_name)", where (assembly_name) is the DLL name of the project.

 

21. What is mean by Delay signing?

During development process, usually private key will not be exposed to the developer due to security reason. In this kind of scenario, we will go with delay signing.Delay signing allows you to place a shared assembly in the GAC by signing the assembly with just the public key. This allows the assembly to be signed with the private key at a later stage, when the development process is complete and the component or assembly is ready to be deployed. This process enables developers to work with shared assemblies as if they were strongly named, and it secures the private key of the signature from being accessed at different stages of development.

E.g

VB.Net(Assemblyinfo.vb)

< Assembly: AssemblyKeyFileAttribute("myKey.snk") > 

< Assembly: AssemblyDelaySignAttribute(True) >

C#(Assemblyinfo.cs)

[assembly: AssemblyKeyFileAttribute("myKey.snk")]
[assembly: AssemblyDelaySignAttribute(true)]
 



      22. What is mean by Satellite assembly?


      When we write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies.

       

      23. What is portable executable (PE)?


      The file format defining the structure that all executable files (EXE) and Dynamic Link Libraries (DLL) must use to allow them to be loaded and executed by Windows. PE is derived from the Microsoft Common Object File Format (COFF). The EXE and DLL files created using the .NET Framework obey the PE/COFF formats and also add additional header and data sections to the files that are only used by the CLR.

       

      24. What is mean by Garbage collection?


      Garbage collection is a CLR features used to automatically manages memory. CLR automatically release the objects which are not longer used or referenced. Developer who forget to release the dispose the objects will be cleared by GC. But it is not known when GC will be called by CLR to clean the memory. So better we can dispose the objects once it is used.

       

      25. What are the different levels of GC is available?


      Generation 0 , Generation 1, Generation 2

       

      26. How Garbage collector will get memory from OS?


      When execution engine starts, GC will initialize segment of memory for its operation. GC reserves memory in segment, each segment is 16MB. When we run out of segments we reserve a new segment. If a segment of memory is not in use, it will be deleted.

       

      27. What is mean by LOH?


      LOH-(Large Object Heap). If size of the object are very high(>64KB) then it will be stored in different segment of memory called as LOH. GC will treat the large objects differently from small objects.

       

      28. What are situations GC will be called?



      1. If user forcefully calls System.GC.Collect
      2. System is in low memory situation
      3. Memory allocation exceeds the Generation0 threshold

       


      29. What is mean by value type and Reference type?


      Value type- Value type stores their value directly to memory address. Value type's values are allocated on the stack memory.

      Reference type - Reference type stores the reference to the value's memory address. Reference type values are allocated on head memory.

       

      30. What is mean by Boxing and Unboxing?


      Boxing - Converting value type variable to reference type is called as boxing

      UnBoxing - Converting reference type variable to value type is called as unboxing

                  int vType = 35;
      object rType;
      //Boxing process
      rType = vType;
      //Unboxing process
      vType =(int) rType;


      31. How will you decide when to use value type and reference type?


      All depends upon need.

       

      32. What is difference between System exception and Application exception?


      All exceptions are derived from the Exception base class. Where Exception class is derived from the Object class. Both System and Application exception are derived from exception class but it has difference between them. System exceptions are thrown by the CLR where as Application exceptions are thrown by Application.

      System Exception
      Application Exception

      System exceptions are thrown by CLR
      Application exceptions are thrown by Application

      E.g OutOfMemoryException, NullReferenceException,etc
      E.g User defined exception are created to throw application's exception and user defined exceptions are derived from ApplicationException


       


      33. What is Reflection?


      .Net compilers store metadata information(types defined) about the assemblies inside the assembly itself. Using this metadata we can load an assembly dynamically (at runtime), get information about its containing types, instantiate these types and call methods.

      "Reflection" is a mechanism using which we can load an assembly dynamically and call its method. The System.Reflection is the root namespace that contains classes to implement the reflection. The Assembly class is the one which is used to represent the assembly in .Net environment.

      Example:

      static void Main(string[] args)
      {
      // Load an assembly from file
      Assembly myAssembly = Assembly.LoadFrom("MyService.dll");
      // Get the types contained in the assembly and print their names
      Type[] types = myAssembly.GetTypes();
      foreach (Type type in types)
      {
      Console.WriteLine(type.FullName);
      //Get the members(methods) present inside each type
      foreach (MemberInfo member in type.GetMembers())
      {
      Console.WriteLine(" "+member.Name);
      }
      }
      Console.ReadLine();
      }

      OutPut:


       


      34. How will you decompile your assembly?


      Any assembly can be disassembled using ILDASM(Intermediate Language Disassembler), it is ships with the .Net framework SDK. Using third party tools like Reflector or Anakrino can also be easily decompile the assemblies.

       

      35. What is mean by Obfuscation?


      Obfuscation is a technique used to mangle symbols and rearrange code blocks to foil decompiling. Dotfuscator, is a popular obfuscation package ships with Visual Studio.

       

      36. If we have two different version of same assembly in GAC how do we make a choice?


      Let us consider the scenario where one of the applications uses the dll which is available in GAC. Now we are creating the second version of the same dll and placed inside the GAC. So GAC contains both version of the assembly, since application referring the dll from GAC, definitely it will take latest version of the dll. But we need old version of the assembly to be executed. How to achieve this requirement?

      Answer: using < bindingRedirect > tag in App.config file

      Example:

      Step 1: Create sample library class with MyVersion() method. This method will return current version of the assembly.

      namespace AssemblyVersionExample
      {
      public class Class1
      {

      public string MyVersion()
      {
      return "The old version: 1.0.0.10";
      }
      }
      }

      Step 2:Modify the "AssemblyVersion" attribute with the old version say ‘"1.0.0.10"

      // You can specify all the values or you can default the Build and Revision Numbers 
      // by using the '*' as shown below:
      // [assembly: AssemblyVersion("1.0.*")]
      [assembly: AssemblyVersion("1.0.0.10")]
      [assembly: AssemblyFileVersion("1.0.0.10")]

      Step 3:Compile the dll and register to assembly using "gacutil"

      Step 4:Create a public token key using following command [ sn -T "filepath"]. Now the public key for the assembly is created.


      Step 5:Repeat the step 2,3 with different version for same assembly

      	
      public string MyVersion()
      {
      return "The new version: 1.0.0.20";
      }

      // by using the '*' as shown below:
      // [assembly: AssemblyVersion("1.0.*")]
      [assembly: AssemblyVersion("1.0.0.20")]


      Step6: Now let's start creating the application, which refer the AssemblyVersionExample.dll Create a instance of the class and invoke the method. Output of the assembly will be new version.

      static void Main(string[] args)
      {
      AssemblyVersionExample.Class1 objClass = new AssemblyVersionExample.Class1();
      Console.WriteLine(objClass.MyVersion());
      Console.ReadLine();
      }

      Step 7: Since we need to use the old version of the assembly from GAC, we should make use of "bindingRedirect" tag in the application. In the below sample, you can find that new attribute is set with old version value (newVersion="1.0.0.10") and attribute is set with new version value (oldVersion="1.0.0.20"). When we execute the application, resultant output will be from old version of the dll.

      <configuration>

      <runtime>

      <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">

      <dependentAssembly>

      <assemblyIdentity name="AssemblyVersionExample"

      publicKeyToken="7c779e284ebe2e8c"

      culture="neutral" />

      <bindingRedirect oldVersion="1.0.0.20"

      newVersion="1.0.0.10"/>

      </dependentAssembly>

      </assemblyBinding>

      </runtime>

      </configuration>

      Output:


       

      37. What is mean by Dll Hell?


      DLL hell means deploying the same DLL in your application multiple times. In windows application dlls are shared across multiple application. Suppose when App1 is using MyAssembly.dll and it is working fine. Suppose I am installing new application App2 which also having assembly MyAssembly.dll, while installing App2 it will override the old assembly with new MyAssembly.dll. Now only App2 will function properly where as App1 which depends on MyAssembly.dll will fail. This is called as Dll hell. It can be solved by assembly versioning.

       

      38. How's the DLL Hell problem solved in .NET?


      Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly.

       

      39. What's the difference between the System.Array.CopyTo() and System.Array.Clone()?



      • System.Array.CopyTo() - Performs a deep copy of the array
      • System.Array.Clone()- Performs a shallow copy of the array

       


      40. What is difference between application running in Debug and Release mode?


      In a debug build mode the complete symbolic debug information is added to complile assembly to help while debugging applications and also the code optimization is not taken into account. While in release build the symbolic debug infrmation is not added to the compiled assembly and the code execution is optimized. Since debuging information is not added in a release build, the size of the final executable is lesser than a debug executable.

       

      41. What is the difference between traditional development and .NET development?


      In traditional programming languages, the source code of a program is compiled to a specific platform's assembly language and then machine language code. Later the library code required by the program is linked to it. Finally the operating system executes the program when desired by the user

      In the presence of dot net framework, a program is not compiled to the native machine executable code; rather it gets compiled to an intermediate language code called Microsoft Intermediate Language (MSIL) or Common Intermediate Language (CIL). The Dot Net Common Language Runtime (CLR) then converts this intermediate code at runtime to the machine executable code. The optimization is carried out at runtime

       

      41. How true it is that .NET and Java programs are quite in-efficient when compared to C++?


      In .Net and Java programming, initial execution of the program will be little bit slower than the C++ programming. Because .Net and Java involves the hosting of CLR into managed applcaiotn process in .Net and starting the JVM in a new process in case of Java. Since, the CLR and JVM optimizes the code more efficiently than the static C++ compilers, the execution speed of the program may actually be faster after sometime of the program startup when most of the code is translated. Hence, in the longer run, the .Net and Java based programs should not be in-efficient when compared to C++.

       

      42. How Finaliz() method will work in .net?


      .Net framework provides ahte Object.Finalize() method to clean up objects unmanaged resources. In general garbage collector keeps track of objects that have Finalize methods, using an internal structure called the finalization queue. Each time your application creates an object that has a Finalize method, the garbage collector places an entry in the finalization queue that points to that object. The finalization queue contains entries for all the objects in the managed heap that need to have their finalization code called before the garbage collector can free their memory.

      Finalize methods requires at least two garbage collections to free the resources. When the garbage collector performs a collection, it reclaims the memory for inaccessible objects without finalizers. At this time, it cannot collect the inaccessible objects that do have finalizers. Instead, it removes the entries for these objects from the finalization queue and places them in a list of objects marked as ready for finalization. Entries in this list point to the objects in the managed heap that are ready to have their finalization code called. The garbage collector calls the Finalize methods for the objects in this list and then removes the entries from the list. A future garbage collection will determine that the finalized objects are truly garbage because they are no longer pointed to by entries in the list of objects marked as ready for finalization. In this future garbage collection, the objects' memory is actually reclaimed.

      Logging JScript Errors to windows event log

      Writing Jscript for Dynamics CRM is a tough task, there were no errors is the data is in proper format, but somtimes i wish to log all those information & exception in some place to review/analyse. But since Jscript is not meant for this. Still there is something that you can do with Windows Event Logger. Here is a small script that uses activeXObject to write the log to eventviewer. Later you can view the log by running "eventvwer" in the cmd prompt.

      Here is the script



      // Creates a log object
      Log.prototype = {
      // adds functions to it
      Err:function(Error){
      var WshShell = new ActiveXObject("WScript.shell");
      WshShell.LogEvent(1,Error);
      },
      Success:function(Message){
      var WshShell = new ActiveXObject("WScript.shell");
      WshShell.LogEvent(0,Message);
      },
      Warn:function(Warning){
      var WshShell = new ActiveXObject("WScript.shell");
      WshShell.LogEvent(2,Message);
      },
      Info:function(Information){
      var WshShell = new ActiveXObject("WScript.shell");
      WshShell.LogEvent(4,Information);
      },
      AuditSuccess:function(Message){
      var WshShell = new ActiveXObject("WScript.shell");
      WshShell.LogEvent(8,Message);
      },
      AuditFailure:function(Message){
      var WshShell = new ActiveXObject("WScript.shell");
      WshShell.LogEvent(16,Message);
      }
      }

      // Calling the log to write error
      Log.Err("error in script");