Dynamics 365 SDK


Getting started with CRM SDK has been this simple. CRM now offers you variety of options to connect with. You can choose between XRM Tooling Connector, Standard Core assemblies, or simply use OAuth with Web API. This article will talk about CRM SDK using late binding approach.

  

Postman is the most popular tool today to troubleshoot and write sample code for testing. Postman offers variety of programming options as well. I love to use variables option which is easy to then show the data.

  

WebAPI is now part of Dynamics 365 since a long time. I will try to present some scenarios through the series including Jscript and C#. Today I will be covering an example to code using WebAPI (with Jscript) and troubleshoot at the same time. Read more..

  

I’ve added this post to showcase the CRUD operations in C# through WebAPI endpoint. You must have working experience in below areas: –

  • Program using C#
  • Dynamics 356 Online.
  • Visual Studio
  • Conceptual knowledge of ODATA Operations.
  • Using ADAL + OAuth

All the operations below require access token to be passed as a header hence it’s important to know how to use ADAL (Active Directory Azure Authentication Library).

  

Hello Everyone

  

OAuth applications can be developed using Dynamics 365 Online and OnPremise versions. Let’s see these in more details:

  

Hey Everyone

  

Hey Guys,

  

Hey Folks,

  

Hey Guys,

I went back a little got this sample out from my source directory. Today I'm expanding a bit on existing sample for building an SSO based application to integrate with Dynamics CRM. I have collated few samples and concepts from below articles:

It's really important for you to understand on how WAUTH is used. The blog article above really helps you to understand this from the expert level point of view. To go more in depth about the SAML Based Authentication Context, you can see the below table at: Supported SAML Authentication Context Classes and Strengths

Authentication Method Authentication Context Class URI
User Name and Password urn:oasis:names:tc:SAML:2.0:ac:classes:Password
Password Protected Transport urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport
Transport Layer Security (TLS) Client urn:oasis:names:tc:SAML:2.0:ac:classes:TLSClient
X.509 Certificate urn:oasis:names:tc:SAML:2.0:ac:classes:X509
Integrated Windows Authentication urn:federation:authentication:windows
Kerberos urn:oasis:names:tc:SAML:2.0:ac:classes:Kerberos

Now, I'll go ahead and walk you through the steps required to build your application:

    • Create a new Project "ASP.NET" Web Application in Visual Studio
    • You can choose to write the below sample to display the post login information as below:
    • Now go ahead and Publish your website in IIS / or Host your site.
    • While the hosting is done and mapped to your local path. I'd choose a custom header for my website to look like below
    • I chose https://custom.domain.com:82/Welcome.aspx. Be sure to select your "Wild Card certificate". I'm using the same as I have for ADFS STS (With onebox setup)
    • Go ahead and download the WIF SDK
    • Go to Programs, and Select "Windows Identity Federation Utility Wizard" (FedUtil.exe) - Please ensure to open this with "Run as Administrator" option.
    • While you keep running this tool with Next option, you'll be providing below information
    •    - Custom Web Url: https://custom.domain.com:82/Welcome.aspx
                     - STS Url: https://sts.domain.com/FederationMetadata/2007-06/FederationMetadata.xml
    • I've added few screen shots below



  • These steps will be helpful for you to create your application.

Happy CRM Integration :)

Cheers,
Apurv

  

Hey Guys,

Today I'm going to talk about an exciting new feature of CRM 2013/2015 environment "Business Process Flows". You can read more about the features here

While you can do this job from UI, but the idea is to automate the creation of next steps automatically. This article talks about the a plugin code using CRM SDK to achieve this.


Some Prerequisites before you start:

  1. Hands on CRM 2013 - Business process flow
  2. Hands on CRM SDK 2013
  3. Plugin Registration for CRM 2013
  4. .NET Framework 4.0 / Visual Studio 2012 or higher

Consider the scenario below:

  • Opportunity Entity
  • Custom Entity new_customflow

Please make sure you've enabled "Business Process Flows" in the entity customization for "new_customflow" entity, see below image:

  • Now go ahead and create a business flow with a custom entity

This will look like as shown below:

You're all set with designing the business Flows via CRM customizations.

  • Now when you create opportunity, it should automatically create a record for Custom Flows and link it to existing opportunity.

You'll need to write the code as below

  • This code will be registered as Plugin

For Plugins (Config):
a. Message: Create
b. Entity: Opportunity
c. Operation: Post
d. Execution mode: Sync

Note: The workflow Id and Stage Id has to be correctly mentioned. In this sample, I've used hardcoded values which can be replaced by just doing a simple retrieve using SDK. Or you can use Early bound classes to use "WorkflowSet".

You're now all set for automating your business process flows. As you hit "next" you can see the opportunity is now listed as connected flow. In the below screenshot, notice "108".

Stages preview:


I'd like to thank Kaustubh Giri who helped me with all the testing and innovating the business processes.



Happy customizing! :)

Thanks,
Apurv

  

Hey guys,

Today I'm going to talk about an interesting sample on Windows store apps which will go connect with CRM using Oauth.

You'll need a working knowledge on the following

  1. ADAL (Active Directory Authentication Library) - Available on Nuget
  2. ADFS 3.0
  3. Window Store Apps
  4. A bit of Fiddler (Optional)

I'm trying to walk you through the entire steps which includes the configuration of ADFS, then we'll go ahead and build the sample.

Register your application with ADFS Environment for development / Token issue

  1. Create a GUID using Guid Generator using Visual Studio
  2. Make a note of it for registration
  3. At this point, I've not provided Redirect Url

Adfs script:

Add-AdfsClient -ClientId C8E3F34A-E1A6-455C-A6DB-A1B82E6A6BE0 -Name WindowsAppsStore -Description "OAuth for CRM connecting Clients from Windows Store"

Windows Store Application demo

Note: This app is using Mobile SDK Please read the instructions to compile and generate the Assembly for app reference

  1. Create a new project using Visual Studio 2013
  2. Choose, Project for Store (Blank should be okay)
  3. Add Reference to "Microsoft.Crm.Sdk.Mobile"
  4. Add CrmHelper.cs file form the Mobile SDK Download to reuse the code.
  5. I have written and attached below

Few Global Variables

ADAL Based Sample:

It's important that you run the code for the first time with all the correct parameters/variables set and obtain the redirect URL from below code:
public static string redirectUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString();

Once you've see the value, it will look something like this
ms-app://s-1-15-2-23142
Now go back to ADFS and use the below command:

Set-AdfsClient -ClientId C8E3F34A-E1A6-455C-A6DB-A1B82E6A6BE0 -Name WindowsAppsStore -Description "OAuth for CRM connecting Clients from Windows Store" -RedirectUri ms-app://s-1-15-2-23142

Once you execute and deploy your application. You can see the token value in fiddler as below:

        HTTP/1.1 200 OK
        Cache-Control: no-store
        Pragma: no-cache
        Content-Length: 1115
        Content-Type: application/json;charset=UTF-8
        Server: Microsoft-HTTPAPI/2.0
        client-request-id: 43224044-4a95-41cc-9716-fe9387529c49
        Date: Tue, 06 Jan 2015 18:52:44 GMT
        {"access_token":"token value encrypted>":491520}

My special credits to Kenichiro Nakamura for inspiring and providing technical insights to use Mobile SDK for CRM.

Cheers,
Apurv

MainPage.xaml.zip

  

Hello Folks, Finally I was able to spend some time out to work on shorter code for CRM connection using late bound approach. More than the helper concept the idea is about a universal application which can help you troubleshoot/isolate the issues with CRM authentication.

  

Hello Folks,

I have been always writing some basic sort of examples on CRM scripting / SDK. This time I have brought down this to .NET core feature called “Entity Framework” versus “CRM SDK”.
This article is useful is people who are quite familiar with LINQ but are new to CRM entity classes.

Let’s take a look at the code comparisons below:


.NET Entity Framework Example:
SQL Table: Student

id int
name varchar(300)
marks int

Now when we generate the .NET Entity Model using .edmx file. We will see the classes have been regenerated with relevant properties as below

public int id {  get;  set ;}
public string name {  get;  set ;}
public int marks {  get;  set ;}

When we start to use this in LINQ implementation, we would generally use Students object and receive the data.

var context = new EntityFrameWorkEntities();
var query = (from o in context.Students select o );

This will result into complete rows of Student Table. Now let’s have a look at the way we would write CRM classes using LINQ. First and foremost we would need to generate classes using CrmSvcUtil.exe.

Below is the screen shot of CrmSvcUtil Screen shot:

Consider a sample entity called “new_Student” with similar fields like we took in above example.

Here’s what it would look like:

CRM SQL table: new_student

new_id int
new_name nvarchar(300)
new_marks int

Here’s the LINQ implementation:

IOrganizationService service = ReturnCrmService();
using (var context = new CrmContext(service))
{
var query = (from o in context.AccountSet select new{ o.Name }.Name);
foreach (string name in query)
{
Console.WriteLine(string.Format("Account Name: {0}", name));
}
Console.ReadKey();
}

By default all CRM entities are post pended with the word “Set”. This is how you can identify the entity names. I have attached the working CRM Project for your quick reference.

Hope this information was helpful.

Cheers,
Apurv

Program.zip

  

Hello Guys,

I’m back with exciting new topic which could be helpful when you want to understand on how to use early bound classes in CRM Plugin.

Let’s take a look at the hand-on pre-requisites

  • Visual Studio 2010 or higher
  • .NET Framework 4.0
  • LINQ
  • CRM SDK - Consuming Services
  • CRM SDK - Plugin Development

I wouldn’t touch a lot of CRM SDK basics here. I’d like to start with code generation tool directly commonly known as CrmSvcUtil. The below walkthrough will use a sample to update a contact on Post operation.

Let’s go with step-by-step approach

  • Create a new Class Library project in Visual Studio
  • Reference the below CRM SDK assemblies

  • Add the below code
namespace Apurv.CRMSdk.Samples
{
     public class UpdatePlugin : IPlugin
     {
        public void Execute(IServiceProvider serviceProvider)
        {
         // create organization service
         var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
         var factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
         var Service = factory.CreateOrganizationService(context.UserId);
         using (var crm = new XrmServiceContext(Service))
         {
          //Use this variable to fetch the current target
          var target = (Entity)context.InputParameters["Target"];
          //Use this variable convert the target in current entity object
          var entity = target.ToEntity();           //Retrieving the Id value from the entity object.
          Guid id = entity.Id.Value;           //Use the XRM contact object to pass in the Early-bound context.           contact contactEntity = new contact           { contactEntity = id, contactEntity.lastname = "Last Name value" };
          //In case you want check if the entity is attached or not. The below code can be used.
          if (!crm.IsAttached(contactEntity))
          crm.Attach(contactEntity); crm.UpdateObject(contactEntity);
          crm.SaveChanges();
          }
         }
     }
}
  • Compile your code and you're assembly is ready for deployment.

Here is this example we’re getting the contact Id Guid from the Input Parameters which will help us to update the record in question. Once we save this record, the plugin will update the lastname to “developer specified value”. This example could be ideal scenario to create some auto-generated number via etc..,

Hope this was helpful.

Cheers,
Apurv

  

Today I’m kicking off the posts on plugins. I dedicate today’s post to CRM developers who are planning for plugin development. I have collected and provided all the information that you would need to understand before you start architecting your plugin.

Before we get started, please check the prerequisites that you should be aware of:

  • CRM SDK 2011
  • Microsoft Visual Studio 2010 or higher

Plug-ins are normal classes which are built using Class library project. They implement the IPlugin interface. All cases exposed in CRM 2011 are .NET Framework 4 CLR-compliant. You will need to add Microsoft.Xrm.Sdk.dll and Microsoft.Crm.Sdk.Proxy.dll assembly references to your project in order to compile plug-in code. All these assemblies can be found in the SDKBin folder of the SDK download. Refer to http://msdn.microsoft.com/en-us/library/gg594416 to see the sample code for plugin.

Designing a plugin When you start thinking about the plugin make sure you have gone through the Event Execution pipeline described here http://msdn.microsoft.com/en-us/library/gg327941

Handling Exceptions Here’s is the sample to catch your exceptions: http://msdn.microsoft.com/en-us/library/gg327884. This sample contains the code applicable for Console Application. You can choose to write this into a file on a server. This is a business logic to be decided on the fly.

Developing CRM Online Plugins vs. CRM OnPremise Plugins When you start working on CRM online you might want to take care of not using IOrganizationService directly like you would do in custom SDK applications. You will land-up in Security Exception, the reason being sandboxed environment. Microsoft on cloud restricts the environment with unauthorized usage.

The sandbox environment is limited to access Registry settings, event logs etc. This is due to partial trust on assemblies. You might want to go through the definition of Sandbox environment http://en.wikipedia.org/wiki/Sandbox_%28computer_security%29.

For more details on CRM Plugin Trusts, please read http://msdn.microsoft.com/en-us/library/gg334752

Coming back to CRM OnPremise, You can allow your sandbox environments to make only web requests. This ideally means when you explicitly write connection to access CRM Web requests it will allow that. For this you will need to make registry changes.
Registry Key: HKEY_LOCAL_MACHINESOFTWAREMicrosoftMSCRMSandboxWorkerOutboundUriPattern
Value:
^http[s]?://(?!((localhost[:/])|([.*])|([0-9]+[:/])|(0x[0-9a-f]+[:/])|(((([0-9]+)|(0x[0-9A-F]+)).){3}(([0-9]+)|(0x[0-9A-F]+))[:/]))).+
Extract from: http://msdn.microsoft.com/en-us/library/gg334752 Here’s the sample for Web Access in plugin: http://msdn.microsoft.com/en-us/library/gg509030

Debugging the plugin When debugging an OnPremise plugin, please make sure you’ve read http://msdn.microsoft.com/en-us/library/gg328574.aspx to check the name of processes which would be required to attach at the time of debug.

When debugging CRM Online Plugin you can make use of Plugin Profiler which is a part of Plugin registration tool. Here are the steps http://msdn.microsoft.com/en-us/library/hh372952.aspx

Registering Plugin Please check out a walkthrough available at MSDN: http://msdn.microsoft.com/en-us/library/gg309580

Custom SDK application vs. Plug-ins When you start writing SDK application the first step that you would start with is with writing IOrganizationService to execute the functions like Create, delete and execute etc..,. When you start writing a plugin the service is already made available to you within in the context of it. Here’s is the implementation /or sample of it http://msdn.microsoft.com/en-us/library/gg309673.aspx#bkmk_access.

Other topics that might interest you

Cheers,
Apurv

  

Hello Developers,
This article is most interesting and life saver for who are in trouble with authenticating to CRM Online organizations. Microsoft recently announced about moving organization to integrated O365 environment. Looks awesome!! Does this mean you’ll need to revisit your code?? Yes you will need to :)
I’ve framed couple of questions which may cross your mind.

What has changed?
The CRM SDK has been revised with newer functions like “Authenticate()” to make our life easier. This returns security token response that is used in the service proxy constructor. We now use IServiceManagement Generic Interface to pass through authentication. For more details, please check http://msdn.microsoft.com/en-us/library/hh670628.aspx.

What error do I see when using older code against O365 based authentication?
The error is pretty generic and restricted to authentication failure in WCF layer. The typical error message is below

Do we have a sample?
Yes we do have a sample code available http://msdn.microsoft.com/en-us/library/hh675404 with helper class http://msdn.microsoft.com/en-us/library/gg309393 which is revised to embed this part. You might want to look at http://blogs.msdn.com/b/apurvghai/archive/2012/07/29/authenticate-office-365-users-with-microsoft-dynamics-crm-online.aspx. I have simplified the approach for smooth usage.

Is there any other thing I need to look at?
Yes you need to be aware of discovery URL changes. We now use https://disco.crm.dynamics.com/XRMServices/2011/Organization.svc Please refer this article http://msdn.microsoft.com/en-us/library/gg309401.aspx to choose correct endpoints.

I also noticed a blog post available from Microsoft talking about ongoing issues with CRM Online organizations. Check out for more insights https://community.dynamics.com/product/crm/crmtechnical/b/crmonlineservice/default.aspx

Hope this helps!! Let me know if you have something I can add here :)

Cheers,
Apurv

  

Here’s what I have for you guys a simple technique to connect to your CRM office 365 based organizations. I have created a sample to add a new contact. This will help you use the Create function of CRM Service

  • Create an empty solution in VS 2010
  • Right click, to add new class library project
  • Choose the Target Framework as .NET 4.0
  • Name the project as “<<your preferred name>>”
  • Add the required references to your project
  • Add the following code:
Note: The example is based out from MSDN article. For complete details on how to create a helperclass, please refer to http://msdn.microsoft.com/en-us/library/gg309393.aspx.

Walkthrough

  • Create an empty solution in VS 2010
  • Right click, to add new console
  • Choose the Target Framework as .NET 4.0
  • Name the project as “CrmProxy”
  • Create a class called
  • Add the required references to your project
  • Add the following code:

public class Program

    {

        //Define global variables

        private String discoveryServiceAddress = "https://disco.crm5.dynamics.com/XRMServices/2011/Discovery.svc"; //Use this discovery URL

        private String organizationUniqueName = "UniqueName"; //Provide the unique name of the organization

        private String userName = "user@yourname.onmicrosoft.com"; //Use your office 365 user Id

        private String password = "*******"; //Provide your password here

        private String domain = "domainName";

 

        static void Main(string[] args)

        {

            Program programObject = new Program();

            programObject.ReturnCRMServiceInstance();

        }

 

        /// <summary>

        /// This function returns the instance for CRM Service using OrganizationServiceProxy

        /// </summary>

        /// <returns></returns>

        public OrganizationServiceProxy ReturnCRMServiceInstance()

        {

            String organizationUri = "https://<yourorgName>.api.crm5.dynamics.com/XRMServices/2011/Organization.svc";

            IServiceManagement<IOrganizationService> OrganizationServiceManagement = ServiceConfigurationFactory.CreateManagement<IOrganizationService>(new Uri(organizationUri));

            AuthenticationProviderType OrgAuthType = OrganizationServiceManagement.AuthenticationType;

            AuthenticationCredentials authCredentials = GetCredentials(OrgAuthType);

            AuthenticationCredentials tokenCredentials = OrganizationServiceManagement.Authenticate(authCredentials);

            OrganizationServiceProxy organizationProxy;

            SecurityTokenResponse responseToken = tokenCredentials.SecurityTokenResponse;

 

            using (organizationProxy = new OrganizationServiceProxy(OrganizationServiceManagement, responseToken))

            {

                organizationProxy.EnableProxyTypes();

            }

 

            return organizationProxy;

        }

 

        /// <summary>

        /// Use this function for creating

        /// </summary>

        /// <param name="lastName"></param>

        /// <returns></returns>

        public Guid createContact(string lastName)

        {

            OrganizationServiceProxy organizationProxy = this.ReturnCRMServiceInstance();

            Entity contactEntity = new Entity("contact");

            contactEntity.Attributes["lastname"] = lastName;

            return organizationProxy.Create(contactEntity);

        }

 

        //Note: Please use your own authentication mechanism. Refer to this link for more types: http://msdn.microsoft.com/en-us/library/gg309393.aspx

        /// <summary>

        /// This function retuns the authentication instance for different type of modes.

        /// </summary>

        /// <param name="endpointType"></param>

        /// <returns></returns>

        private AuthenticationCredentials GetCredentials(AuthenticationProviderType endpointType)

        {

            AuthenticationCredentials authCredentials = new AuthenticationCredentials();

            switch (endpointType)

            {

 

                case AuthenticationProviderType.ActiveDirectory:

                    authCredentials.ClientCredentials.Windows.ClientCredential =

                        new System.Net.NetworkCredential(userName, password, domain);

                    break;

                case AuthenticationProviderType.LiveId:

                    authCredentials.ClientCredentials.UserName.UserName = userName;

                    authCredentials.ClientCredentials.UserName.Password = password;

                    authCredentials.SupportingCredentials = new AuthenticationCredentials();

                    authCredentials.SupportingCredentials.ClientCredentials =

                        Microsoft.Crm.Services.Utility.DeviceIdManager.LoadOrRegisterDevice();

                    break;

                default: // For Federated and OnlineFederated environments.                   

                    authCredentials.ClientCredentials.UserName.UserName = userName;

                    authCredentials.ClientCredentials.UserName.Password = password;

                    // For OnlineFederated single-sign on, you could just use current UserPrincipalName instead of passing user name and password.

                    // authCredentials.UserPrincipalName = UserPrincipal.Current.UserPrincipalName;  //Windows/Kerberos

                    break;

 

            }

            return authCredentials;

        }

    }

 

  • Now, we’re all set.
  • Build the complete solution and now you have your assembly ready.
  • You can use this in any of your projects.

Happy Integration with Office 365!

Cheers,
Apurv

Program.zip

  

This article deals with integrating SSIS 2008 and CRM 2011. You might have faced a lot of issues doing this part. As we know that SSIS 2008 still doesn’t support .NET 4.0 Framework so adding .NET 4 compiled assemblies is not a possible task/solution. What’s next? We can do this with backward compatibility using CRM v4 SDK. But with this approach we lose on CRM 2011 newer functions. After doing a lot of research I was finally able to write some code over it using .NET Framework 3.5

Before we get started, please refer the requirements:

  • Visual Studio 2010
  • WCF concepts
  • Hands on CRM SDK 2011

Note: I will not cover the SSIS Project creation, for more details you can see http://msdn.microsoft.com/en-us/library/ms137823.aspx.

Walkthrough

  • Create an empty solution in VS 2010
  • Right click, to add new Class Library Project
  • Choose the Target Framework as .NET 3.5
  • Name the project as “CrmProxy”
  • Create a class called “CrmHelper.cs”
  • Add service reference to Organization.svc and name it as “Crm”
  • Add the following code:

  

Hello Guys, I have come up with an interesting article on enabling/disabling the out of box ribbon items in CRM 2011. This article demonstrates the order entity where I would be disabling the “Create invoice button” based on a condition in jscript. The script returns “false” or “true” value.

Before we get started, here’s the list of requirements with which you need to be familiar:

  • Microsoft Visual Studio 2010 / Notepad ++ (or XML editor)
  • MS CRM SDK 2011
  • Jscript

Walk-through

  • Go to settings > customizations > solutions
  • Click “new” add new solution
  • Provide a valid name, publisher and your version number
  • Save the solution
  • Add the existing “Order” entity.
  • Save & close the dialog
  • Export the solution
  • Unzip the archive and open the customization.xml file
  • Search for “RibbonDiffXML” tag under the order entity
  • Add the following code

  • Save and close the file
  • Zip all the three files Customization.xml, [Content_Types].xml and solution.xml
  • Go to CRM application
  • Go to settings > customizations > customize the system > web resources
  • Click to add “new” web resource, provide a name “new_CustomRule.js”
  • Add the following code

function HideExisting()
{
return false;
}

  • Import the customizations
  • Publish the customizations
  • You can see the changes reflected

You can download the solution below.

Additional Information:

Cheers,
Apurv

Export_Order_1_0_Final.zip

  

Hello people, I dedicate this post to our newest developers using jscript in CRM. I have added steps on how you can debug your scripts with events like OnLoad, OnSave and OnChange. The process of using IE developer doesn’t change but I have customized it to CRM level.

Requirements

  1. Internet Explorer (7.0 or above)
  2. CRM 2011 SDK
  3. Jscript basics

Scenario

I want to display an alert on account form when I save the form.

Walkthrough Steps:

    • Open the existing record
    • Press F12 on your keyboard, you will see below screen appearing
    • Before even we start debugging, we need to identify the script which is already attached to this form. Click on the down arrow to look for your script/web resource. Below screen shot displays a list
    • Finally I have searched my library which I want to debug, I click Start Debugging and you will see following screen. Select the line you want to debug
    • Hit Save button to execute the script
    • You will see the debugger on your breakpoint line

For general article on using IE developer Tool, please read this http://msdn.microsoft.com/en-us/library/ie/dd565625%28v=vs.85%29.aspx

Cheers,
Apurv

  

Hello All, I’m back with exciting new sample code to develop your own SDK application with offline capability. The application uses Cassini server URL. This article provides you step by step information how and what to write. I have also mentioned some environment step that you can keep handy.

Requirements

  1. CRM for Outlook (Offline Capability)
  2. Visual Studio 2010
  3. .NET Framework 4.0
  4. CRM 2011 SDK

Walkthrough Steps:

  1. Create a Windows application using Visual Studio
  2. Add appropriate references and declare the following namespace

using System.ServiceModel;
using System.ServiceModel.Description;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Client.Services;
using Microsoft.Xrm.Client.Configuration;

  1. Add the following source code

//Organization URL
Uri OrganizationUri = new Uri(String.Format("http://{0}/XRMServices/2011/Organization.svc","localhost:2525"));
//Discovery URL
Uri HomeRealmUri = new Uri(String.Format("http://{0}/XRMServices/2011/Discovery.svc", "localhost:2525"));
//Domain Credentials
ClientCredentials localCredentials = new ClientCredentials();
//Live Credentials - Used in CRM Online. I have just created instance, but I don't fill values.
ClientCredentials deviceCredentials = new ClientCredentials();
localCredentials.UserName.UserName = "XXXXXXXX";
localCredentials.UserName.Password = "XXXXXXXX";
using (serviceProxy = new OrganizationServiceProxy(OrganizationUri, HomeRealmUri, localCredentials, deviceCredentials))
{
    serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
     IOrganizationService service = (IOrganizationService)serviceProxy;
     Entity account = new Entity("account");
     accountId = serviceProxy.Create(account);
     MessageBox.Show("Account with name " + textBox1.Text + " is created successfully.");
}

This code is similar to what I have described in my first blog about creating web service here except I'm using cassini here instead of online URL.

You will also notice I have used "localhost:2525" which is the default port for cassini server. You can always change the default port. I have complied couple of articles related to this topic.

  1. FAQ’s on Cassini Server: http://support.microsoft.com/kb/893391
  2. Sample : Use Outlook Methods: http://msdn.microsoft.com/en-us/library/gg309513.aspx

  

This article talks about a parent look view which is never visible after the “Display search box in lookup diaglog” is checked while customizing Opportunity Product Entity in CRM 2011. There is an easy workaround to get back to old view. I have mentioned the ways you see this happening and a tweak in customization which will revert this back.

How can I see a different view?

  1. Go to Settings > Customizations > Customize the system > Entities > Opportunity Product > Forms > Main Form > Existing Product
  2. Select "Change Properties"
  3. Go to General Tab and scroll down until you find “Display this is search box”
  4. Check that setting and save the entity following to publish it.
  5. Now go to, opportunities entity
  6. Add a price list and continue adding an existing product
  7. A screen will appear to choose existing product.
  8. The moment you click lookup icon, you will see that the name of view has changed to “Product Lookup View”

How do I revert to old view?

If you’re thinking that you can just go and uncheck. No then that’s not a solution. We will need to revert through a customization tweak. The reason for this and by now CRM has reset the view id. Hence it shows a different view.
The following are steps to achieve that
  1. Go to Settings > Solutions
  2. Add new Solution and provide a valid name to it.
  3. Save the solution.
  4. Now add existing entity, “Opportunity Product”
  5. Export the solution as unmanaged
  6. Open the unmanaged solution in notepad and locate the following:
  7. Replace {8BA625B2-6A2A-4735-BAB2-0C74AE8442A4} with {BCC509EE-1444-4A95-AED2-128EFD85FFD5}
  8. Save the changes
  9. Zip the files and import the solution back to your environment
  10. Publish the customizations
  11. Refresh the CRM in your browser
  12. You will see the correct view.
You can always check the correct GUID values in the database.

Happy customizing :)

Cheers,
Apurv

  

I have tried to outline couple of examples that you could use in CRM. These examples are based on Xrm patterns which tells you how you can utilize the resources available in better way. These are newly introduced in CRM 2011. The whole idea is to put together a set of common functions as an library which can be used across the forms. You just need to register them under one common place called web resources and keep attaching them to forms where you need to use these. I will also demonstrate how you can achieve that. Let's get to the list and see what we have in store for today :)

  • Server URL.
Xrm.Page.context.getServerUrl()
  • Get the string value of a text field
function GetMainPhone() {
   var MainPhone = Xrm.Page.data.entity.attributes
     .get("telephone1").getValue();
}
  • Set the value of a string field
function SetMainPhone() {
  Xrm.Page.data.entity.attributes
     .get("telephone1").setValue();
}
  • Adding value to option set
var optionsetbox = Xrm.Page.getControl("customertypecode")
optionsetbox.text= "Apurv";
optionsetbox.value= "10";
Xrm.Page.ui.controls.get("customertypecode").addOption(optionsetbox,12);
  • Removing a value from option set on fly
Xrm.Page.getControl("customertypecode").removeOption(4);

I'm still working on more user friendly examples. Please do wait for more. Keep surfing and visiting.

Cheers,
Apurv

  

This post talks about formatting phone number is US style. The code already available in CRM v4 SDK Guide, however I have re-written the same thing in CRM v2011 model.

It only part of code which is different here in the usage of context class available in XRM pattern.

function validatePhone()


var phone = Xrm.Page.data.entity.attributes.get("telephone1");
var sTmp = phone.getValue().replace(/[^0-9]/g, "");
phoneRegex = /^d{10}$/; 

if(!sTmp.match(phoneRegex))
{
alert("Phone must contain 10 numbers.") ;
}
else
{
switch(sTmp.length)
{
case "4105551212".length:
phone.setValue( "(" + sTmp.substr(0, 3) + ") " + sTmp.substr(3, 3) + "-" + sTmp.substr(6, 4));
break;

case "5551212".length:
phone.setValue= sTmp.substr(0, 3) + "-" + sTmp.substr(3, 4);
break;

}

}


References
  1. Formatting Phone Numbers in CRM v4

  

  

I hope this article can help you understand when you need to create a middleware between CRM system and a Legacy system/or custom application.The below example talks about the “contact” entity where the web service accepts the “lastname” attribute of it and inserts the same into CRM system. The end result is the guid which is retrieved and confirms the successful execution of the operation.

Before we get started, here’s the list of requirements

  1. Microsoft Visual Studio 2010
  2. MS .NET Framework 4.0
  3. MS CRM SDK 2011

Walkthrough Steps: Web Service

  • Open Visual Studio 2010
  • Select your project, ASP.NET Empty Web Application
  • Select a suitable name of your project
  • On Successful Creation of Project
  • Go to Solution Explorer
  • Add New Item: Web Service


        
 

  • Provide a suitable name
  • Click on Add to create
  • You will see the C# content in “CustomWebService.asmx.cs”
  • Add reference to CRM Assemblies

     

  • Adding another .NET assemblies

 
      

  • Adding Live ID Code File available in CrmSdk (SDKsamplecodecshelpercode)
  • Declare the namespace

        

  • Write the code for CRM

/// <summary>
/// This function accepts the lastname and creates a contact with that in CRM
/// </summary>
/// <param name="lname"></param>
/// <returns></returns>
public string CreateContact(string lname)
{
     string message = string.Empty;
     try
     {
     OrganizationServiceProxy serviceProxy;
     ClientCredentials deviceCredentials = null;
     ClientCredentials clientCredentials = null;
     Guid contactId = Guid.Empty;
    
     //Organization URL
     Uri OrganizationUri = new Uri(String.Format("https://{0}.api.crm.dynamics.com/XRMServices/2011/Organization.svc","<<Organization>>"));
     //Discovery URL
     Uri HomeRealmUri = new Uri(String.Format("https://dev.{0}/XRMServices/2011/Discovery.svc", "crm.dynamics.com"));
     //Setting Client Credentials
     clientCredentials = this.GetCredentials("<<Live Id>>", "<<Live Password>>");
     //Get the Device Id and Password
     deviceCredentials = this.GetDeviceCredentials();
     //Using Organization Service Proxy to instantiate the CRM Web Service
     using (serviceProxy = new OrganizationServiceProxy(OrganizationUri, HomeRealmUri, clientCredentials, deviceCredentials))
     {
          // This statement is required to enable early-bound type support.
          serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
          IOrganizationService service = (IOrganizationService)serviceProxy;
          //Define Entity Object
           Entity contact = new Entity("contact");
          //Specify the attributes
          contact.Attributes["lastname"] = lname;
          //Execute the service
          contactId = service.Create(contact);
          //Confirmation Message
           message = "Contact Created with LastName:- " + lname + " Guid is" + contactId.ToString();

      }
     }
     catch (Exception ex)
     {
           message = ex.Message;
     }
     //returns the message
     return message;
}

  • Write the other functions used in the code above

        protected virtual ClientCredentials GetCredentials(string username, string password)
        {
            ClientCredentials credentials = new ClientCredentials();
            credentials.UserName.UserName = username;
            credentials.UserName.Password = password;
            return credentials;
        }

        protected virtual ClientCredentials GetDeviceCredentials()
        {           
          return Microsoft.Crm.Services.Utility.DeviceIdManager.LoadOrRegisterDevice();
        }

  • Complie your code
  • You've successfully completed the walkthrough.

Useful links

  1. How to use retrieve method