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");

      Formatting international phone numbers

      The CRM SDK contains a sample to format US phone numbers and it works pretty well. However, there are customers outside the US and the sample doesn't work with international phone numbers. An easy formatting rule is replacing any occurrence of '(', ')' or a space with a dash. People can then enter the phone number in their preferred way, but get the same output.


      var originalPhoneNumber = "+49 (89) 12345678";
      var formattedPhoneNumber = originalPhoneNumber.replace(/[^0-9,+]/g, "-");
      formattedPhoneNumber = formattedPhoneNumber.replace(/-+/g, "-");
      alert(formattedPhoneNumber);


      The first call to the replace method changes every character in the input string that is not a digit and not the plus sign (which is used for international
      numbers) to the dash symbol. However, the output is +49--89--12345678, so the second call replaces all occurrences of multiple dashes with a single
      one, giving a final result of +49-89-12345678.

      Retrieving all fields inside a CRM form

      If you want to loop over all fields (input fields) on a CRM form, you can use the following script



      //CRM 4 Jscript



      for (var index in crmForm.all) {
      var control = crmForm.all[index];

      if (control.req && (control.Disabled != null)) {
      //control is a CRM form field
      }
      }


      The conditions mean that a control must have the "req" attribute and the "Disabled" method. This seems a good indicator for a CRM form field.

      Complete Installation guide for CRM 4.0

      Complete Installation guide for CRM 4.0 / Step by Step guide to install CRM 4.0

              Last week I installed Microsoft Dynamic 4.0 on my virtual machine and I found that it will be helpful for beginner like me, if there is a step by step installation guide. Lets start with OS selection.

      1. You can use Windows Server 2003 or later server version. I had Windows Server 2003 R2.

      2. Install latest service pack for OS you installed.

      3. Install Internet Information Service.

      4. Install Active Directory.

      5. Configure DNS Server.

      6. Create new user for domain and make him member of Administrators group.

      7. Install SQL Server 2005 with Reporting Service and Analysis service.

      8. Configure new account as service account for Report Server and Analysis server.

      9. Install Visual Studio 2008.

      10. Start installation of CRM 4.0

      11. Enter display name for your Organization.

      clip_image001

      12. Next step is to select installation path, you can leave this as it is or select specific folder,

      clip_image002

      13. Next select website for CRM, I choose new website with different port address in my case it was 5555 as shown in image below,

      clip_image003

      14. Next you need to enter URL for Reporting server.

      15. Next you have to select Organization Unit. Click on Browse button and select the root node of your domain in my case it is chirag.

      clip_image004

      16. On next step you need to specify security account, choose the one you created in step 6. Enter the password in password textbox and click next.

      17. Select your local machine as Email Router setting or select specific machine on domain which you are using at email server. I chose my local machine so localhost.

      18. Once you click next you will see System Requirements screen. If Domain user, SQL Server Reporting Service and ASP.NET are installed properly you will receive no error or warning else you will receive error message. I received following errors,

      clip_image005

      19. If you receive error message for SQL Server or SQL Server Reporting Service don’t be afraid. Open Services from Start – All Programs – Administrative Tools – Services. Check whether SQL Server Agent is running. If not right click on service and select property. Select Startup Type as Automatic and click on start button.

      20. Another common error is for Indexing service. Follow the steps mention in point 19 to start Indexing Service.

      21. You can see a warning mentioning Verify Domain User account SPN for the Microsoft Dynamics CRM ASP.NET Application Pool account. This will usually shows when you add specific domain account for security account in step 16.

      22. If System Requirements screen show no error or warning on next step installation will be started.

      23. Finally you will see following screen, this means your CRM is installed.

      clip_image006

      Removing a navigation bar entry at runtime

      To remove a navigation bar entry dynamically, you can use the following code:

      var navigationBarEntry = document.getElementById("navProds");

      if (navigationBarEntry != null) {
      var lbArea = navigationBarEntry.parentNode;
      if (lbArea != null) {
      lbArea.removeChild(navigationBarEntry);
      }
      }

      If you haven't already done it, download and install the Internet Explorer Developer Toolbar to find the name of the navigation bar entry.

      Retrieving the current user information

      The new solution uses the Microsoft CRM web services to retrieve the user id, business unit id, organization id and the first, last and full name of the currently logged on user. I have attached a simple test form with the following OnLoad event:


      var xml = "" +
      "" +
      "" +
      GenerateAuthenticationHeader() +
      " " +
      " " +
      " " +
      " systemuser" +
      " " +
      " " +
      " businessunitid" +
      " firstname" +
      " fullname" +
      " lastname" +
      " organizationid" +
      " systemuserid" +
      "
      " +
      "
      " +
      " false" +
      " " +
      " And" +
      " " +
      " " +
      " systemuserid" +
      " EqualUserId" +
      "
      " +
      "
      " +
      "
      " +
      "
      " +
      "
      " +
      "
      " +
      "
      " +
      "";

      var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");

      xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
      xmlHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple");
      xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
      xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
      xmlHttpRequest.send(xml);

      var resultXml = xmlHttpRequest.responseXML;
      var entityNode = resultXml.selectSingleNode("//RetrieveMultipleResult/BusinessEntities/BusinessEntity");

      var firstNameNode = entityNode.selectSingleNode("q1:firstname");
      var lastNameNode = entityNode.selectSingleNode("q1:lastname");
      var fullNameNode = entityNode.selectSingleNode("q1:fullname");
      var systemUserIdNode = entityNode.selectSingleNode("q1:systemuserid");
      var businessUnitIdNode = entityNode.selectSingleNode("q1:businessunitid");
      var organizationIdNode = entityNode.selectSingleNode("q1:organizationid");

      crmForm.all.sw_firstname.DataValue = (firstNameNode == null) ? null : firstNameNode.text;
      crmForm.all.sw_lastname.DataValue = (lastNameNode == null) ? null : lastNameNode.text;
      crmForm.all.sw_name.DataValue = (fullNameNode == null) ? null : fullNameNode.text;
      crmForm.all.sw_systemuserid.DataValue = (systemUserIdNode == null) ? null : systemUserIdNode.text;
      crmForm.all.sw_businessunitid.DataValue = (businessUnitIdNode == null) ? null : businessUnitIdNode.text;
      crmForm.all.sw_organizationid.DataValue = (organizationIdNode == null) ? null : organizationIdNode.text;

      Web Service Interview Questions

      1. What is Web service?

      Web Services are applications that provide services on the internet. Web services allow for programmatic access of business logic over the Web. Web services typically rely on XML-based protocols, messages, and interface descriptions for communication and access. SOAP over HTTP is the most commonly used protocol for invoking Web services. SOAP defines a standardized format in XML which can be exchanged between two entities over standard protocols such as HTTP.

      Example: Google search engine's web service, e.g., allows other applications to delegate the task of searching over the internet to Google web service and use the result produced by it in their own applications.

      2. What is UDDI?

      UDDI - Universal Description, Discovery and Integration. It is an XML-based standard for describing, publishing, and finding Web services. It is platform independent, open framework and specification for a distributed registry of Web services

      3. What is DISCO?

      DISCO is the abbreviated form of Discovery. It is basically used to club or group common services together on a server and provides links to the schema documents of the services it describes may require.

      4. What is the use of Disco.exe?

      The Web Services Discovery tool discovers the URLs of XML Web services located on a Web server and saves documents related to each XML Web service on a local disk.

      5. What are the uses of Web service?
      • Application integration Web services within an intranet are commonly used to integrate business applications running on different platforms.

        For example, a .NET client running on Windows 2000 can easily invoke a Java Web service running on a mainframe or Unix machine to retrieve data from a legacy application.

      • Business integration Web services allow trading partners to engage in e-business allowing them to leverage the existing Internet infrastructure. Organizations can send electronic purchase orders to suppliers and receive electronic invoices. Doing e-business with Web services means a low barrier to entry because Web services can be added to existing applications running on any platform without changing legacy code.
      • Commercial Web services focus on selling content and business services to clients over the Internet similar to familiar Web pages. Unlike Web pages, commercial Web services target applications as their direct users.
      6. What is WSDL?

      The Web Services Description Language (WSDL) is a particular form of an XML Schema, developed by Microsoft and IBM for the purpose of defining the XML message, operation, and protocol mapping of a web service accessed using SOAP or other XML protocol.

      WSDL describes the details such as

      • Where we can find the Web Service (its URI)?
      • What are the methods and properties that service supports?
      • Data type support.
      • Supported protocols
      7. How to create a web service?

      This sample explains about the creation of sample web service and consuming it.

      Step 1: Create a new web service by clicking File->New->WebSite and select "ASP.Net Web Service"

      Step 2:

      Create a class and methods which is need to be exposed as service. Decorate the class with "WebService" and methods with "WebMethod" attribute.

      [WebService(Namespace = "http://tempuri.org/")]
      [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
      // To allow this Web Service to be called from script,
      //using ASP.NET AJAX, uncomment the following line.
      // [System.Web.Script.Services.ScriptService]

      public class Service : System.Web.Services.WebService
      {
      public Service () {

      //Uncomment the following line if using designed components
      //InitializeComponent();
      }

      [WebMethod]
      public string HelloWorld() {
      return "Hello World";
      }

      [WebMethod ]
      public string SayHello(string name) {
      return "Hello " + name;
      }

      }


      Step 3:

      Run the web service


      Step 4: Create the client application to consume the service by clicking File->New->Project and select the Console Application.

      Step 5: Right click the project file and select "Add Service Reference"


      Step 6:

      Create a new instance for proxy class and call the web method "SayHello"

      class Program
      {
      static void Main(string[] args)
      {
      ServiceReference1.ServiceSoapClient proxy = new
      ServiceReference1.ServiceSoapClient();
      Console.WriteLine(proxy.SayHello("Ram"));
      Console.ReadLine();
      }
      }


      Step 7:

      Output window are shown


      8. What is difference between Add Reference and Add Service reference?

      Add Reference is used to add the .Net assemblies and COM components to the project files, where as Add Service Reference is used to create a proxy for the web service.

      9. What is the transport protocol you use to call a Web service?

      SOAP (Simple Object Access Protocol) is the preferred protocol.

      10. Where on the Internet would you look for Web services?

      http://www.uddi.org

      11. To test a Web Service you must create a windows application or web application to consume this service? It is True/False?

      Every web service by default generates a test page, we need not create or consume the Web service in order to test it.

      12. When would you use .NET Remoting and when Web services?

      When both service and client are .Net platform, .Net remoting will be more efficient where are if both server and client are different platform use web service for communication

      13. A Web service can only be written in .NET True or False?

      False

      14. How to implement security to the web service?

      WS-Security (Web Services Security) is a communications protocol providing a means for applying security to Web services.

      The protocol contains specifications on how integrity and confidentiality can be enforced on Web services messaging. The WSS protocol includes details on the use of SAML and Kerberos, and certificate formats such as X.509

      WS-Security describes how to attach signatures and encryption headers to SOAP messages. In addition, it describes how to attach security tokens, including binary security tokens such as X.509 certificates and Kerberos tickets, to messages.

      WS-Security incorporates security features in the header of a SOAP message, working in the application layer. Thus it ensures end-to-end security.

      Comment your code

      Following are 13 tips on how to comment your source code so that it is easier to understand and maintain over time.

      1. Comment each level

      Comment each code block, using a uniform approach for each level.  For example:

      • For each class, include a brief description, author and date of last modification
      • For each method, include a description of its purpose, functions, parameters and results

      Adopting comment standards is important when working with a team.  Of course, it is acceptable and even advisable to use comment conventions and tools (such as XML in C# or Javadoc for Java) to facilitate this task.

      2. Use paragraph comments

      Break code blocks into multiple “paragraphs” that each perform a single task, then add a comment at the beginning of each block to instruct the reader on what is about to happen.

      // Check that all data records
      // are correct
      foreach (Record record in records)
      {
          if (rec.checkStatus()==Status.OK)
          {
              . . .
          }
      }
      // Now we begin to perform
      // transactions
      Context ctx = new ApplicationContext();
      ctx.BeginTransaction();
      . . .
      3. Align comments in consecutive lines

      For multiple lines of code with trailing comments, align the comments so they will be easy to read.

      const MAX_ITEMS = 10; // maximum number of packets
      const MASK = 0x1F;    // mask bit TCP

      Some developers use tabs to align comments, while others use spaces.  Because tab stops can vary among editors and IDEs, the best approach is to use spaces.

      4. Don’t insult the reader’s intelligence

      Avoid obvious comments such as:

      if (a == 5)      // if a equals 5
          counter = 0; // set the counter to zero

      This wastes your time writing needless comments and distracts the reader with details that can be easily deduced from the code.

      5. Be polite

      Avoid rude comments like, “Notice the stupid user has entered a negative number,” or “This fixes the side effect produced by the pathetically inept implementation of the initial developer.”  Such comments do not reflect well upon their author, and you never know who may read these comments in the future: your boss, a customer, or the pathetically inept developer you just insulted.

      6. Get to the point

      Don’t write more in comments than is needed to convey the idea.  Avoid ASCII art, jokes, poetry and hyperverbosity.  In short, keep the comments simple and direct.

      7. Use a consistent style

      Some people believe that comments should be written so that non-programmers can understand them.  Others believe that comments should be directed at developers only.  In any event, as stated in Successful Strategies for Commenting Code, what matters is that comments are consistent and always targeted to the same audience.  Personally, I doubt many non-developers will be reading code, so comments should target other developers.

      8. Use special tags for internal use

      When working on code as a team, adopt a consistent set of tags to communicate among programmers.  For example, many teams use a “TODO:” tag to indicate a section of code that requires additional work:

      C# Code for Sending Email to Unresolved Recipients

      This code will send email to unresolved recipient.
      private void SendEmailToUnresolvedRecent(IOrganizationService prmCrmService, string 
                   prmToRecipientEmailAddress, Guid prmSenderUserId, string prmSubject, string prmMessageBody)
              {
      
                  // Email record id
                  Guid wod_EmailId = Guid.Empty;
      
                  // Creating Email 'to' recipient activity party entity object
                  Entity wod_EmailToReciepent = new Entity("activityparty");
      
                  // Creating Email 'from' recipient activity party entity object
                  Entity wod_EmailFromReciepent = new Entity("activityparty");
      
                  // Assigning receiver email address to activity party addressused attribute
                  //wod_EmailToReciepent["participationtypemask"] = new OptionSetValue(0);
                  wod_EmailToReciepent["addressused"] = prmToRecipientEmailAddress;
      
                  // Setting from user account
                  wod_EmailFromReciepent["partyid"] = new EntityReference("systemuser", prmSenderUserId);
      
                  // Creating Email entity object
                  Entity wod_EmailEntity = new Entity("email");
      
                  // Setting email entity 'to' attribute value
                  wod_EmailEntity["to"] = new Entity[] { wod_EmailToReciepent };
      
                  // Setting email entity 'from' attribute value
                  wod_EmailEntity["from"] = new Entity[] { wod_EmailFromReciepent };
      
                  // Setting email subject and description
                  wod_EmailEntity["subject"] = prmSubject;
      
                  wod_EmailEntity["description"] = prmMessageBody;
      
                  // Creating email record
                  wod_EmailId = prmCrmService.Create(wod_EmailEntity);
      
                  // Creating SendEmailRequest object for sending email
                  SendEmailRequest wod_SendEmailRequest = new SendEmailRequest();
      
                  // Creating Email tracking token request object
                  GetTrackingTokenEmailRequest wod_GetTrackingTokenEmailRequest = new GetTrackingTokenEmailRequest();
      
                  // Creating Email tracking token response object to get tracking token value
                  GetTrackingTokenEmailResponse wod_GetTrackingTokenEmailResponse = null;
      
                  // Setting email record if for sending email
                  wod_SendEmailRequest.EmailId = wod_EmailId;
      
                  wod_SendEmailRequest.IssueSend = true;
      
                  // Getting tracking token value
                  wod_GetTrackingTokenEmailResponse = (GetTrackingTokenEmailResponse)
                                                       prmCrmService.Execute (wod_GetTrackingTokenEmailRequest);
      
                  // Setting tracking token value
                  wod_SendEmailRequest.TrackingToken = wod_GetTrackingTokenEmailResponse.TrackingToken;
      
                  // Sending email
                  prmCrmService.Execute(wod_SendEmailRequest);
      
              }
      

      Create a button on the CRM 4.0

      I'll show you the example of Appeal (Case-incident) how to create a button on the form and hang on click function.

      ms-crm-create-button-alert

      button on the CRM-form

      Add to the essence of the new Case attribute named new_button, submit it to a form, the properties of the field new_button remove the check mark Display label on the form, save and publish.

      Open the OnLoad event of form and paste the following script:

       
      /* Jscript */



      / / The button
      crmForm.all.new_button.DataValue = «Button»;
      crmForm.all.new_button.style.textAlign = "center";
      crmForm.all.new_button.vAlign = "Middle";
      / / styles
      crmForm.all.new_button.style.cursor = "Hand";
      crmForm.all.new_button.style . backgroundColor = "# CADFFC";
      crmForm.all.new_button.style.color = "# 000000";
      crmForm.all.new_button.style.borderColor = "# 330066";
      crmForm.all.new_button.style.fontWeight = "bold ";
      crmForm.all.new_button.contentEditable = false;
      / / change color when the mouse



      changeC1 function () {
      crmForm.all.new_button.style.color = "000099";
      }
      changeC2 function () {
      crmForm.all.new_button.style.color = "000000";
      }
      changeC3 function () {
      crmForm.all.new_button.style.backgroundColor = "# 6699FF";
      }
      changeC4 function () {
      crmForm.all.new_button.style.backgroundColor = "CADFFC";
      }
      / / when you click on the button call the TestTheButton
      crmForm.all.new_button.attachEvent ("onclick", TestTheButton);
      function TestTheButton ()
      {Alert (":)");
      }

      Follow a lead from creation through closure

      A lead record in Microsoft Dynamics CRM Online represents a potential customer who must be qualified or disqualified as a sales opportunity. You can use leads to manage potential sales from the point at which you become aware of a customer's interest through the successful sale.

      The following diagram illustrates the ways that you can create a lead and convert it to several different record types.

      Lead diagram

      There are several ways that you can create a lead in Microsoft Dynamics CRM Online:

      After you create the lead, you can convert it into any of the following three record types:

      • Account
      • Contact
      • Opportunity

      When you convert the lead to an opportunity, you can also choose to link the new opportunity to the new accounts or contacts you may have created, or to an existing account or contact in your Microsoft Dynamics CRM Online database.

      Follow an opportunity from creation through closure

      An opportunity is a potential sale or possible revenue from an account or contact.

      The following diagram illustrates the ways that you can create an opportunity and close it when the potential customer decides whether to move forward with the sale.

      Opportunity diagram

      There are several ways that you can create an opportunity in Microsoft Dynamics CRM:

      When you know whether or not the customer is going to move forward with the sale, you can close the opportunity with a status of either Won or Lost.

      Walkthrough: Using the Discovery Service with Active Directory Authentication

      [Applies to: Microsoft Dynamics CRM 4.0]

      This walkthrough demonstrates how to use the Discovery Web service to find the correct CrmService Web service endpoint for your organization. This is for an on-premise installation of Microsoft Dynamics CRM. For more information on the Discovery Web service, see Web Services: CrmDiscoveryService.

      During this walkthrough you will learn how to do the following:

      • Use Microsoft Visual Studio 2005 to create a console application that uses the Microsoft Dynamics CRM Web services.
      • Use Active Directory authentication for interacting with the Microsoft Dynamics CRM Web services.

      This walkthrough utilizes Microsoft Visual C# sample code only. However, a Microsoft Visual Basic .NET version of the code can be found at SDK\Walkthroughs\Authentication\VB\ActiveDirectory.

      Prerequisites

      In order to complete this walkthrough, you will need the following:

      • Access to a Microsoft Dynamics CRM 4.0 server.
      • A Microsoft Dynamics CRM system account.
      • Visual Studio 2005.

      Creating a Visual Studio 2005 Solution

      You will use a Visual Studio 2005 solution to build your project code.

      To create a Visual Studio 2005 solution

      1. In Microsoft Visual Studio 2005, on the File menu, point to New, and then click Project to open the New Project dialog box.

      2. In the Project types pane, select Visual C#.

      3. In the Templates pane, click Console Application.

      4. Type a name for your project and then click OK.

      While this walkthrough only shows the Visual C# code for the project, a VB.NET version of the code can be found in the SDK\Walkthroughs\Authentication\VB\ActiveDirectory folder.

      Adding Web References

      You need to add Web references to the required Microsoft Dynamics CRM Web services. By adding these Web references, you are making the Web service proxy namespaces accessible to your project.

      To add the CrmDiscoveryService Web service reference

      1. In the Solution Explorer window, right-click your project name and choose Add Web Reference.

      2. In the Add Web Reference wizard, type the URL for the CrmDiscoveryService Web service in the URL box, using the name and port number for your Microsoft Dynamics CRM server, and then click Go. For example:

      3. http://<servername:port>/mscrmservices/2007/AD/CrmDiscoveryService.asmx

      4. When the CrmDiscoveryService Web service is found, change the text in the Web reference name box to CrmSdk.Discovery and then click Add Reference.

      To add the CrmService Web service reference

      1. In the Solution Explorer window, right-click your project name and choose Add Web Reference.

      2. In the Add Web Reference wizard, type the URL for the CrmService Web service in the URL box, using the name and port number for your Microsoft Dynamics CRM server, and then click Go. For example:

      3. http://<servername:port>/mscrmservices/2007/CrmServiceWsdl.aspx

      4. When the CrmService Web service is found, change the text in the Web reference name box to CrmSdk and then click Add Reference.

      Note that you can name the Web references any name that you like, but for this example they have been named CrmSdk and CrmSdk.Discovery.

      Accessing Microsoft Dynamics CRM Web Services

      To access the Microsoft Dynamics CRM Web services and work with business entities, your code typically includes these kinds of program statements:

      • Using statements, which provide access to the required namespaces.
      • Code that instantiates the CrmDiscoveryService and CrmService Web service proxies.
      • Instantiation of Microsoft Dynamics types.
      • Invocation of Web service methods.

      To include the required .NET namespaces

      Add the following lines of code above the namespace statement in your project:

      [C#]

       using System.Web.Services.Protocols;
      using System.Xml;

      To include the required Microsoft Dynamics CRM Web service namespaces

      Add the following lines of code after the namespace statement and before the class statement:

      // Import the Microsoft Dynamics CRM namespaces.
      using CrmSdk;
      using CrmSdk.Discovery;
      // This class is found in Microsoft.Crm.Sdk.dll. You can add a reference
      // to the DLL and remove this class definition if you like.
      public sealed class AuthenticationType
      {
      public const int AD = 0;
      public const int Passport = 1;
      public const int Spla = 2;
      }

      This code also adds an AuthenticationType class that is used later in the sample code.

      To add configuration information to your solution

      Add the following code after the class statement and before the Main method. This code sets up the necessary variables such as organization name. Be sure to fill in the correct values for the server name, TCP port, and organization of your Microsoft Dynamics CRM installation.

      [C#]



      // The following configuration data is site specific.
      // TODO: Set the name and TCP port of the server hosting Microsoft Dynamics CRM.
      static private string _hostname = "localhost";
      static private string _port = "80";

      // TODO: Set the target organization.
      static private string _organization = "AdventureWorksCycle";

      #endregion Configuration data

      // Expired authentication ticket error code. The error codes can be found in the
      // SDK documentation at Server Programming Guide\Programming Reference\Error Codes.
      static private string ExpiredAuthTicket = "8004A101";





      To add error handling to your solution

      Add the following code within the Main method. This code will provide some console output you can use to verify that your program is working.

      [C#]




      try
      {
      Run();
      Console.WriteLine("Authentication was successfull.");
      }
      catch (System.Exception ex)
      {
      Console.WriteLine("The application terminated with an error.");
      Console.WriteLine(ex.Message);

      // Display the details of the inner exception.
      if (ex.InnerException != null)
      {
      Console.WriteLine(ex.InnerException.Message);

      SoapException se = ex.InnerException as SoapException;
      if (se != null)
      Console.WriteLine(se.Detail.InnerText);
      }
      }
      finally
      {
      Console.WriteLine("Press to exit.");
      Console.ReadLine();
      }




      Your program will not build because the Run method does not exist. You will create this next.

      To add the Run method

      This method contains all the code needed to use the Discovery service to obtain the correct URL of the CrmService Web service for your organization. The code then sends a WhoAmI request to the service to verify that the user has been successfully authenticated.

      Add the following code after the Main method.

      [C#]



      public static bool Run()
      {
      try
      {
      // STEP 1: Instantiate and configure the CrmDiscoveryService Web service.
      CrmDiscoveryService discoveryService = new CrmDiscoveryService();
      discoveryService.UseDefaultCredentials = true;
      discoveryService.Url = String.Format(
      "http://{0}:{1}/MSCRMServices/2007/{2}/CrmDiscoveryService.asmx",
      _hostname, _port, "AD");

      // STEP 2: Retrieve the organization name and endpoint Url from the
      // CrmDiscoveryService Web service.
      RetrieveOrganizationsRequest orgRequest =
      new RetrieveOrganizationsRequest();
      RetrieveOrganizationsResponse orgResponse =
      (RetrieveOrganizationsResponse)discoveryService.Execute(orgRequest);

      OrganizationDetail orgInfo = null;

      foreach (OrganizationDetail orgDetail in orgResponse.OrganizationDetails)
      {
      if (orgDetail.OrganizationName.Equals(_organization))
      {
      orgInfo = orgDetail;
      break;
      }
      }

      if (orgInfo == null)
      throw new Exception("The organization name is invalid.");

      // STEP 3: Create and configure an instance of the CrmService Web service.
      CrmAuthenticationToken token = new CrmAuthenticationToken();
      token.AuthenticationType = AuthenticationType.AD;
      token.OrganizationName = orgInfo.OrganizationName;

      CrmService crmService = new CrmService();
      crmService.Url = orgInfo.CrmServiceUrl;
      crmService.CrmAuthenticationTokenValue = token;
      crmService.Credentials = System.Net.CredentialCache.DefaultCredentials;

      // STEP 4: Invoke CrmService Web service methods.
      WhoAmIRequest whoRequest = new WhoAmIRequest();
      WhoAmIResponse whoResponse = (WhoAmIResponse)crmService.Execute(whoRequest);

      return true;
      }

      // Handle any Web service exceptions that might be thrown.
      catch (SoapException ex)
      {
      throw new Exception("An error occurred while attempting to authenticate.", ex);
      }
      }





      To add the GetErrorCode method

      Add the following code, after the Run method, for the GetErrorCode method that extracts a numeric error code from a SoapException stored in anXmlNode or returns an empty string if no error exists.

      [C#]



      private static string GetErrorCode(XmlNode errorInfo)
      {
      XmlNode code = errorInfo.SelectSingleNode("//code");

      if (code != null)
      return code.InnerText;
      else
      return "";
      }




      Now build and run your solution by pressing F5. If you get any compile errors, you can find the complete code sample in the SDK\Walkthroughs\Authentication\CS|VB\ActiveDirectory folder.

        
      

      RetrievePrincipalAccess Message

      Retrieves the access that the security principal (user) has for the specified entity instance.


      //# The following code example shows how to use the RetrievePrincipalAccess message.

      // Set up the CRM service.
      CrmAuthenticationToken token = new CrmAuthenticationToken();
      // You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
      token.AuthenticationType = 0;
      token.OrganizationName = "AdventureWorksCycle";

      CrmService service = new CrmService();
      service.Url = "http://:/mscrmservices/2007/crmservice.asmx";
      service.CrmAuthenticationTokenValue = token;
      service.Credentials = System.Net.CredentialCache.DefaultCredentials;

      // Create the SecurityPrincipal object.
      // This references the user whose access is being checked.
      SecurityPrincipal principal = new SecurityPrincipal();

      // Set the properties of th SecurityPrincipal object.
      // Type is the typecode of the principalid.
      principal.Type = SecurityPrincipalType.User;
      // PrincipalId is the GUID of the user whose access is being checked.
      principal.PrincipalId = new Guid("F111F0B1-70CE-44B4-8BF2-2E6C7EADA111");

      // Create the target for the request.
      TargetOwnedAccount owner = new TargetOwnedAccount();

      // EntityId is the GUID of the account to which access is being checked.
      owner.EntityId = new Guid("2B951FBC-1C56-4430-B23B-20A1349068F3");

      // Create the request object.
      RetrievePrincipalAccessRequest access = new RetrievePrincipalAccessRequest();

      // Set the properties of the request object.
      access.Principal = principal;
      access.Target = owner;

      // Execute the request.
      RetrievePrincipalAccessResponse accessResponse = (RetrievePrincipalAccessResponse)service.Execute(access);




      CRM 2011 Processes

      Processes - Introduction


      Processes - Dialogs


      Processes - Workflow


      Processes - Performance & Versioning

      LoseOpportunity Message

      Sets the state of an opportunity to Lost.



      //# The following code example shows how to use the LoseOpportunity message.
      // Set up the CRM service.
      CrmAuthenticationToken token = new CrmAuthenticationToken();
      // You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
      token.AuthenticationType = 0;
      token.OrganizationName = "AdventureWorksCycle";

      CrmService service = new CrmService();
      service.Url = "http://:/mscrmservices/2007/crmservice.asmx";
      service.CrmAuthenticationTokenValue = token;
      service.Credentials = System.Net.CredentialCache.DefaultCredentials;

      //Set up the data required for this sample.

      // Create an account for the opportunity's potential customer.
      account potentialCustomer = new account();
      potentialCustomer.name = "Adventure Works Cycle";

      Guid createdAccountId = service.Create(potentialCustomer);

      // Build a query for US Dollar currency.
      QueryByAttribute dollarQuery = new QueryByAttribute();
      dollarQuery.EntityName = EntityName.transactioncurrency.ToString();
      dollarQuery.Attributes = new string[] { "currencyname" };
      dollarQuery.Values = new string[] { "US Dollar" };
      // Be aware that using AllColumns may adversely affect
      // performance and cause unwanted cascading in subsequent
      // updates. A best practice is to retrieve the least amount of
      // data required.
      dollarQuery.ColumnSet = new AllColumns();

      // Create the US currency request.
      RetrieveMultipleRequest dollarRequest = new RetrieveMultipleRequest();
      dollarRequest.Query = dollarQuery;

      // Get US currency to use in the opportunity.
      RetrieveMultipleResponse dollarResponse = (RetrieveMultipleResponse)service.Execute(dollarRequest);
      transactioncurrency usCurrency = (transactioncurrency)dollarResponse.BusinessEntityCollection.BusinessEntities[0];

      // Create an opportunity.
      opportunity loseOpportunity = new opportunity();
      loseOpportunity.customerid = new Customer();
      loseOpportunity.customerid.type = EntityName.account.ToString();
      loseOpportunity.customerid.Value = createdAccountId;
      loseOpportunity.name = "SDK Sample for LoseOpportunity Message";
      loseOpportunity.transactioncurrencyid = new Lookup();
      loseOpportunity.transactioncurrencyid.type = EntityName.transactioncurrency.ToString();
      loseOpportunity.transactioncurrencyid.Value = usCurrency.transactioncurrencyid.Value;

      Guid loseOpportunityId = service.Create(loseOpportunity);

      // Create an opportunityclose object.
      opportunityclose oppClose = new opportunityclose();

      // Set the opportunityclose properties.
      oppClose.subject = "SDK Sample for LoseOpportunity Message";

      // Set the opportunityid to an existing opportunity.
      oppClose.opportunityid = new Lookup();
      oppClose.opportunityid.type = EntityName.opportunity.ToString();
      oppClose.opportunityid.Value = loseOpportunityId;

      // Create the request.
      LoseOpportunityRequest loseOppReq = new LoseOpportunityRequest();
      loseOppReq.OpportunityClose = oppClose;

      // A status of -1 will have the platform set the status to the appropriate value.
      loseOppReq.Status = -1;

      // Execute the request.
      service.Execute(loseOppReq);




      ImportCompressedAllXml Message

      Import all customizations from an XML file that has been compressed using the WinZip format.



      This request requires an ImportExportXml file for import. This example exports this file from CRM and then imports it back into Microsoft Dynamics CRM.
      [C#]
      // Set up the CRM service.
      CrmAuthenticationToken token = new CrmAuthenticationToken();
      // You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
      token.AuthenticationType = 0;
      token.OrganizationName = "AdventureWorksCycle";

      CrmService service = new CrmService();
      service.Url = "http://:/mscrmservices/2007/crmservice.asmx";
      service.CrmAuthenticationTokenValue = token;
      service.Credentials = System.Net.CredentialCache.DefaultCredentials;

      // Create the request.
      ExportCompressedAllXmlRequest requestExport = new ExportCompressedAllXmlRequest();
      requestExport.EmbeddedFileName = "customizations.xml";

      // Execute the request.
      ExportCompressedAllXmlResponse responseExport = (ExportCompressedAllXmlResponse)service.Execute(requestExport);

      // Get the compressed data
      byte[] compressedXML = responseExport.ExportCompressedXml;

      // Create the request.
      ImportCompressedAllXmlRequest request = new ImportCompressedAllXmlRequest();

      // Assign the compressed data
      request.CompressedCustomizationXml = compressedXML;

      // Execute the request.
      ImportCompressedAllXmlResponse response = (ImportCompressedAllXmlResponse)service.Execute(request);




      ImportAllXml Message

      Import all customizations from an XML file.

       
      //# This request requires an ImportExportXml file for import. This example exports this file from CRM and then imports it back into Microsoft Dynamics CRM.

      // Set up the CRM service.
      CrmAuthenticationToken token = new CrmAuthenticationToken();
      // You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
      token.AuthenticationType = 0;
      token.OrganizationName = "AdventureWorksCycle";

      CrmService service = new CrmService();
      service.Url = "http://:/mscrmservices/2007/crmservice.asmx";
      service.CrmAuthenticationTokenValue = token;
      service.Credentials = System.Net.CredentialCache.DefaultCredentials;

      // This is a potentially long running operation. The default 90-second
      // time-out might be too short. Set the time-out to be 5 minutes.
      // This property takes milliseconds.
      service.Timeout = 300 * 1000;

      // Create the request.
      ExportAllXmlRequest request = new ExportAllXmlRequest();

      // Execute the request.
      ExportAllXmlResponse exportResponse = (ExportAllXmlResponse)service.Execute((Request)request);

      // Create the request.
      ImportAllXmlRequest importRequest = new ImportAllXmlRequest();

      // Tell the request where the temporary XML file is located.
      importRequest.CustomizationXml = exportResponse.ExportXml;

      // Execute the import.
      ImportAllXmlResponse importResponse = (ImportAllXmlResponse)service.Execute(importRequest);




      Understanding Hierarchical Entity Relationships

       

      Hierarchical entity relationships require that one of the records have a field to store a unique identifier that references another record. The record that stores the reference to another record is called the child record ( A record in a hierarchical relationship with a parent record where a reference to the parent record is stored in the record. One parent record can be related to many child records. Child records have lookup fields in the form to allow them to be related to a parent record. ) . The record referenced by the unique identifier in the child record is called the parent record ( A record that is in a hierarchical relationship with a child record, where a reference to the record is stored in the child record. One parent record can be related to many child records. ) .

      A hierarchical relationship allows each child record ( A record in a hierarchical relationship with a parent record where a reference to the parent record is stored in the record. One parent record can be related to many child records. Child records have lookup fields in the form to allow them to be related to a parent record. ) to store a reference to one parent record ( A record that is in a hierarchical relationship with a child record, where a reference to the record is stored in the child record. One parent record can be related to many child records. ) . A parent record can be referenced by an unlimited number of child records. The parent record can display all the child records in an associated view ( The view of an entity that is displayed in the forms of other entities. The associated view is different from the views that are visible for the entity in its own area of the user interface. For example, in an account record, under Details, you can click Contacts to view and open a contact form. That is the Contacts associated view. There can be only one associated view of each entity. ) .

      Issues related to Hierarchical relationships include:

      · Defining Relationships

      · Data Integrity

      · Relationship Behavior

      · Limitations for Hierarchical Relationships

      · Mapping

      Defining Relationships

      Relationships are defined between entities. The entity that will represent the child records is called the related entity ( An entity that is associated with a primary entity (record type) through a unique reference defined by using a lookup control on the related entity form. For example, an account has a unique reference to a primary contact. ) . A relationship attribute ( An attribute that exists in a related entity when a hierarchical relationship exists. When added to the form of the related entity, a lookup control is displayed to allow the record to be related to another record as defined in the relationship. ) , also known as a lookup attribute ( An attribute used to create a reference to a related record. Also known as a relationship attribute. ) , is created on the related entity to allow records to store a reference to a parent record. The entity that will represent the parent records is called the primary entity ( The entity that a related entity is associated to. Sometimes called a parent entity. ) in the relationship.

      When you create or edit a relationship between entities in Microsoft Dynamics CRM you must start from one of the entities. Which entity is not important because only one relationship will be created and only one relationship needs to be edited. The terminology used depends on whether you start from the primary entity ( The entity that a related entity is associated to. Sometimes called a parent entity. ) or the related entity ( An entity that is associated with a primary entity (record type) through a unique reference defined by using a lookup control on the related entity form. For example, an account has a unique reference to a primary contact. ) .

      o A 1:N Relationship is a hierarchical relationship created or viewed from the primary entity. Any one record from the primary entity can be referenced by many records from the related entity.

      o A N:1 Relationship is a hierarchical relationship created or viewed from the related entity. Many records from the related entity can reference any one record from the primary entity.

      Note: It is important to remember that the same relationship can be viewed from either of the two entities that participate in the relationship.

       

      Data Integrity

      A hierarchical relationship introduces the opportunity to define rules for data integrity. For example, an opportunity ( A potential revenue-generating event or sale to an account that needs to be tracked through a sales process to completion. ) record has no meaning if it isn't associated with a customer record. Microsoft Dynamics CRM requires that an opportunity record be related to a customer record. However, a task activity ( An action to be performed, such as a task, or a communication item that is sent or received, for example, e-mail, phone calls, and appointments. The status of activities is tracked and the activity history is stored in the system, so users can view the open and closed activities. ) can be meaningful whether it is associated to another record or not. Relating a task activity to another record is optional.

      When you create a relationship, you must choose whether to enforce rules for data integrity. If you make the relationship attribute on the related entity a required field by setting a requirement level ( A setting that determines whether users must enter data. For example, when the requirement level of a field is set to Business Required, users will be unable to save the record without entering data in that field. The field will also appear in the Quick Create form. ) of Business Required, you can guarantee that each of the related entity records created through the Microsoft Dynamics CRM application will be related to a record of the parent entity.

      Note: Field level constraints only apply to the Microsoft Dynamics CRM application. Records created programmatically through the Microsoft Dynamics CRM Web services are not required to respect field level constraints.

       

      Relationship Behavior

      Once you create a hierarchical relationship you can control how the relationship behaves to support both data integrity and business rules for your organization. The relationship can control how actions performed on a parent record will cascade down to child records.

      You can configure the relationship behavior for the following actions performed on the record of the primary entity:

      · Assign ( The related records will be assigned to the same user. )

      · Share ( The related entity records will also be shared with the same user or team. )

      · Unshare ( The related entity records will no longer be shared with the same user or team. )

      · Reparent ( If the owner of the primary entity record changes because the primary entity record was reparented, the owner of any related records will be set to the same owner as the primary entity record. )

      · Delete ( The related records can be deleted, unlinked from the primary entity record, or the delete action can be canceled. )

      · Merge ( The related records associated with the subordinate record will be reparented to the master record. )

      You can choose from three pre-defined and commonly used types of behavior, or you can choose to configure the appropriate cascading action for each action performed on the record of the primary entity.

      The three predefined types of behavior are:

      · Parental
      In a Parental type of behavior, all actions cascade down to the related records. For example, if a parent record is deleted, all child records will also be deleted. If a parent record is reassigned, all the child records are reassigned to the same user.

      · Referential
      In a Referential type of behavior, none of the actions will cascade down to child records. For example, when a parent record is deleted, the data linking that record in any child records is removed.

      · Referential, Restrict Delete
      The Referential, Restrict Delete type of behavior is the same as Referential except that the deletion action is not allowed if there are any related records.

      You can also choose to define specific cascading behavior for each of the actions by choosing the Configurable Cascading type of behavior. For most actions, your choices are:

      · Cascade All
      This is the behavior of the Parental type of behavior. All actions will cascade to all child records, including inactive records.

      · Cascade Active
      Actions will only cascade down to active child records.

      · Cascade User-Owned
      Actions will only cascade down to child records assigned to the same user as the owner of the parent record.

      · Cascade None
      This is the behavior of the Referential type of behavior. No actions will cascade.

      Data integrity must be preserved when data in records changes or when the status of records change. For example, deleting a parent record breaks the data integrity of any child records if the relationship is required. There are three ways to address this:

      · Use the Referential, Restrict Delete type of behavior to prevent the deletion of any records that have dependent child records.

      · Use the Parental type of behavior to delete any dependent child records for any parent records that are deleted.

      · Use the Configurable Cascading type of behavior and set the Delete action to either Cascade All or Restrict.

      If the relationship is not required, it is sufficient to remove the data that establishes the link to the deleted parent record.

      In addition to data integrity, your business may have rules that should be applied when data in records changes or when the status of records changes. For example, some organizations may want to reassign all child records when the a parent record is reassigned. The Relationship behavior can cascade this action so it does not need to be done manually.

       

      Limitations for Hierarchical Relationships

      · Parental Relationships
      Each entity can participate in only one parental ( A relationship between entities in which any action taken on a record of the parent entity is also taken on any child entity records that are related to the parent entity record. For example, if you delete a record in the parent entity, the related child entity records are also deleted; or if you share a parent entity record, the related records from the child entity are also shared. ) relationship. Most Microsoft Dynamics CRM  system entities ( Entities that are included in Microsoft Dynamics CRM by default, such as Account. )   already participate in a parental relationship and this relationship cannot be changed.

      · Number of Relationships
      Enities can have referential relationships with any entity, including system entities. You can create multiple relationships between two entities. Entities can even have referential relationships with themselves - allowing linked records of the same type. However, a record cannot be linked to itself.

      · Relationships with Customer Records
      Customers in Microsoft Dynamics CRM may be Accounts or Contacts. These two entities together represent a composite Customer ( The account or contact with which a business unit conducts a business transaction. ) entity. Some Microsoft Dynamics CRM system entities, such as Opportunity and Case must be related to a Customer. However, you cannot create this type of relationship with custom entities.

       

      Mapping

      New child records can be created by users in the associated view ( The view of an entity that is displayed in the forms of other entities. The associated view is different from the views that are visible for the entity in its own area of the user interface. For example, in an account record, under Details, you can click Contacts to view and open a contact form. That is the Contacts associated view. There can be only one associated view of each entity. ) if they click the New button. When this happens, data from the parent record is copied into the form for the new child record. By default, a reference to the parent record is always copied to the relationship lookup field in the child record. You can choose whether data from other fields should be copied at the same time.

      Clone Message

      Copies an existing contract and its line items.



      //# The following code example demonstrates how to clone a contract.
      // Set up the CRM Service.
      CrmAuthenticationToken token = new CrmAuthenticationToken();
      // You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
      token.AuthenticationType = 0;
      token.OrganizationName = "AdventureWorksCycle";

      CrmService service = new CrmService();
      service.Url = "http://:/mscrmservices/2007/crmservice.asmx";
      service.CrmAuthenticationTokenValue = token;
      service.Credentials = System.Net.CredentialCache.DefaultCredentials;

      // Create the request object.
      CloneContractRequest clone = new CloneContractRequest();

      // Set the properties of the request object.
      clone.ContractId = new Guid("C15AF217-C17E-DA11-B90F-000874DE7397");
      clone.IncludeCanceledLines = false;
      clone.ReturnDynamicEntities = false;

      // Execute the request.
      CloneContractResponse cloned = (CloneContractResponse) service.Execute(clone);




      RevokeAccess Message

      Revokes access rights to the entity instance for the specified security principal (user or team).

      Remarks

      To use this message, pass an instance of the RevokeccessRequest class as the request parameter in the Execute method.

      This method also applies to all child instances of the target instance. For all child instances, if the caller does not have share privileges for those entity types or share rights to the instances, access to the child instances is not revoked. As a result, the owner of the instance or a user who shares the instance with share rights automatically has share rights to all child instances of the target instance. In this case, only the lack of privileges to a particular entity type prevents access to the child instances from being revoked.

      For a description of how actions on a parent instance affect child instances, see Cascading Rules.

      To perform this action, the caller must have access rights on the entity instance specified in the request class. For a list of required privileges, see RevokeAccess Privileges.

       
      //#The following code example shows how to use the RevokeAccess message.

      // Set up the CRM service.
      CrmAuthenticationToken token = new CrmAuthenticationToken();
      // You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
      token.AuthenticationType = 0;
      token.OrganizationName = "AdventureWorksCycle";

      CrmService service = new CrmService();
      service.Url = "http://:/mscrmservices/2007/crmservice.asmx";
      service.CrmAuthenticationTokenValue = token;
      service.Credentials = System.Net.CredentialCache.DefaultCredentials;

      // Create the SecurityPrincipal.
      SecurityPrincipal principal = new SecurityPrincipal();
      principal.Type = SecurityPrincipalType.User;

      // PrincipalId is the GUID of the user whose access is being revoked.
      principal.PrincipalId = new Guid("7B222F98-F48A-4AED-9D09-77A19CB6EE82");

      // Create the target for the request.
      TargetOwnedAccount target = new TargetOwnedAccount();

      // EntityId is the GUID of the account to which access is being revoked.
      target.EntityId = new Guid("2B951FBC-1C56-4430-B23B-20A1349068F3");

      // Create the request object.
      RevokeAccessRequest revoke = new RevokeAccessRequest();

      // Set the properties of the request object.
      revoke.Revokee = principal;
      revoke.Target = target;

      // Execute the request.
      RevokeAccessResponse revoked = (RevokeAccessResponse)service.Execute(revoke);





      Send a Custom E-mail for a Campaign Activity

      The following sample shows how to send an e-mail for a campaign activity.



      [C#]
      public void SendEmail(Guid campaignActivityID)
      {
      CrmService service = new CrmService();
      service.Credentials =
      System.Net.CredentialCache.DefaultCredentials;

      service.CallerIdValue = new CallerId();
      // Replace the GUID with the GUID of your Microsoft Dynamics CRM
      // Administrator.
      service.CallerIdValue.CallerGuid =
      new Guid("FD80F8E8-C852-DA11-B1FB-0007E94D105B");

      SendEmailRequest req = new SendEmailRequest();
      req.EmailId = campaignActivityID;
      req.TrackingToken = "";
      req.IssueSend = true;

      try
      {
      SendEmailResponse res =
      (SendEmailResponse)service.Execute(req);
      }
      catch (System.Web.Services.Protocols.SoapException er)
      {
      //Process any error messages here.
      }
      }




      Cancel Message

      Cancels a contract or salesorder

          //#Cancels a Contract
      // Set up the CRM Service.
      CrmAuthenticationToken token = new CrmAuthenticationToken();
      // You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
      token.AuthenticationType = 0;
      token.OrganizationName = "AdventureWorksCycle";

      CrmService service = new CrmService();
      service.Url = "http://:/mscrmservices/2007/crmservice.asmx";
      service.CrmAuthenticationTokenValue = token;
      service.Credentials = System.Net.CredentialCache.DefaultCredentials;

      // Create the cancel request for a previously created contract
      CancelContractRequest contactCancelationRequest = new CancelContractRequest();

      // Set the properties for the request
      contactCancelationRequest.ContractId = new Guid("C15AF217-C17E-DA11-B90F-000874DE7397");
      contactCancelationRequest.CancelDate = new CrmDateTime();
      contactCancelationRequest.CancelDate.Value = DateTime.Now.ToString();
      contactCancelationRequest.Status = 5;

      // Execute the request
      service.Execute(contactCancelationRequest);




      The following code example demonstrates how to cancel a sales order.

       
      //# cancel a sales order.
      // Set up the CRM Service.
      CrmAuthenticationToken token = new CrmAuthenticationToken();
      // You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
      token.AuthenticationType = 0;
      token.OrganizationName = "AdventureWorksCycle";

      CrmService service = new CrmService();
      service.Url = "http://:/mscrmservices/2007/crmservice.asmx";
      service.CrmAuthenticationTokenValue = token;
      service.Credentials = System.Net.CredentialCache.DefaultCredentials;

      // Create the order close activity object.
      orderclose close = new orderclose();

      // Set the properties of the order close object.
      close.subject = "orderclose";

      // Create a Lookup for the sales order being canceled.
      close.salesorderid = new Lookup();
      close.salesorderid.type = EntityName.salesorder.ToString();
      close.salesorderid.Value = created.id;

      // Create the request object.
      CancelSalesOrderRequest cancel = new CancelSalesOrderRequest();

      // Set the properties of the request object.
      cancel.OrderClose = close;
      cancel.Status = -1;

      // Execute the request.
      CancelSalesOrderResponse canceled = (CancelSalesOrderResponse) service.Execute(cancel);