How to Create a Simple Webpage Leveraging The CRM 2011 IOrganizationService Web Service


Recently I have received a lot of questions about how to get started in developing against CRM 2011. The SDK provides many different examples and helper classes which can be reused to save some time when developing applications. For someone new at developing for CRM, the robust SDK examples may be more than they want to start with.

Below I have provided steps to create a simple webpage that uses the IOrganizationService Web Service to create contacts in CRM. The late bound Entity class will be used for this walkthrough therefore the entity and attribute names must be known. This is a simplified solution that does not use any of the helper classes provided in the SDK and will only support AD authentication. The user that runs this webpage will need to be a CRM user in order for the example to work.

Scenario:

The CRM users need the ability to add contacts into the CRM system without using the main CRM application. They would like a simple data entry website with minimal fields. To accomplish this, we will develop an asp.net website that connects to the CRM 2011 platform using the IOrganizationService Web Service. The custom website will allow the user to specify the contact name, email address, and phone number. When the submit button is pressed on the page it will automatically create the contact record within CRM.

 

Requirements:

  • Visual Studio 2010
  • CRM 2011 SDK

 http://www.microsoft.com/downloads/en/details.aspx?FamilyID=420f0f05-c226-4194-b7e1-f23ceaa83b69 

Create a Custom Web Site

 Step by Step

1.        Create a new Web Site:

a.       Open Visual Studio 2010 to create a new web site.

b.       Click File | New | Web Site.

c.        Under Installed Templates, click Visual C# and choose ASP .NET Empty Web Site. Name the project "CRMContactDataEntry". Click OK.

d.       Click Website|Add New Item. This is the actual aspx page that we will develop on.

e.       Under Installed Templates, click Visual C# and choose Web Form. Click OK.

2.       Add a Title and Field Names to the Default.aspx page.

a.      Within Solution Explorer right click on the Default.aspx page and choose View Designer.

image

b.       Click in the box on the Default.aspx page and type the text “CONTACT ENTRY FORM” to give the page a title.


image

c.        Hit the Enter Key to create a new line below the title and type the text “First Name“.

d.       Add three more lines with the text “Last Name “, “Email Address ”, and “Phone Number ”.

image 

3.       Add four Textbox’s and a Button to the aspx page.

a.       Click View|Toolbox. When the toolbox window opens click the pin icon to keep the window open.  

image

b.       Find the TextBox control within the Toolbox window. Drag the TextBox control onto the Default.aspx page behind the text “First Name”. This creates a single Textbox on the page.

image

c.        Right click the TextBox control on the default.aspx page and choose Properties. The properties window will display on your right hand side.

image

d.       Find the ID property and change the value to txtFirstName.

image

e.       Repeat steps b-d to create three more TextBox’s with the following names.

·   txtLastName

·   txtEmailAddress

·   txtPhoneNumber                      

f.         Find the Button control within the Toolbox window. Drag the Button control onto the Default.aspx page Under the text “Phone Number”. This creates a single Button on the page.

image

g.       Right click the Button control on the default.aspx page and choose Properties. The properties window will display on your right hand side.

image

h.       Find the Text property and change the value to Submit.

image

4.       Add code to the Button’s Click Event.

a.       Double-Click the Button control on the Default.aspx page. This will take you to the Default.aspx.cs file where we can see the Button1_Click method.

image

b.        Add the following code within the Button1_Click code method.

NOTE: You will need to update the Organization URL to match your CRM Servername and OrgName. (i.e. “http://crmsrv:5555/org1/XRMServices/2011/Organization.svc”)

protected void Button1_Click(object sender, EventArgs e)

    {

        //Authenticate using credentials of the logged in user;       

        ClientCredentials Credentials = new ClientCredentials();

        Credentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;

        //This URL needs to be updated to match the servername and Organization for the environment.

        Uri OrganizationUri = new Uri("http://<SERVERURL>/<ORGNAME>/XRMServices/2011/Organization.svc");

        Uri HomeRealmUri = null;

 

        //OrganizationServiceProxy serviceProxy;       

        using (OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(OrganizationUri, HomeRealmUri, Credentials, null))

        {

            IOrganizationService service = (IOrganizationService)serviceProxy;

 

            //Instantiate the contact object and populate the attributes.

            Entity contact = new Entity("contact");

            contact["firstname"] = txtFirstName.Text.ToString();

            contact["lastname"] = txtLastName.Text.ToString();

            contact["emailaddress1"] = txtEmailAddress.Text.ToString();

            contact["telephone1"] = txtPhoneNumber.Text.ToString();

            Guid newContactId = service.Create(contact);

           

            //This code will clear the textboxes after the contact is created.

            txtFirstName.Text = "";

            txtLastName.Text = "";

            txtEmailAddress.Text = "";

            txtPhoneNumber.Text = "";

        }

    } 

5.       Add the Microsoft.Xrm.Sdk and Microsoft.crm.sdk.proxy assemblies as references.

a.       Locate the Solution Explorer, right-click the ProjectName and choose Add Reference.

image

b.       In the Add Reference browser window, click the Browse tab and browse to the location of this assembly reference (this is located in the Bin directory of the downloaded SDK).

c.        Choose Microsoft.Xrm.Sdk and Microsoft.crm.sdk.proxy, click OK.

image

d.       Add the following using statements at the top of the Default.aspx.cs file.

using System.ServiceModel.Description;

using Microsoft.Xrm.Sdk.Client;

using System.Net;

using Microsoft.Xrm.Sdk;

e.       The completed code should look similar to the following.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.ServiceModel.Description;

using Microsoft.Xrm.Sdk.Client;

using System.Net;

using Microsoft.Xrm.Sdk;

 

public partial class _Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

 

    }

    protected void Button1_Click(object sender, EventArgs e)

    {

        ClientCredentials Credentials = new ClientCredentials();

        Credentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;

        //This URL needs to be updated to match the servername and Organization for the environment.

        Uri OrganizationUri = new Uri("http://<ServerName>/<Orgname>/XRMServices/2011/Organization.svc");

        Uri HomeRealmUri = null;

 

        //OrganizationServiceProxy serviceProxy;       

        using (OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(OrganizationUri, HomeRealmUri, Credentials, null))

        {

            IOrganizationService service = (IOrganizationService)serviceProxy;

 

            //Instantiate the contact object and populate the attributes.

            Entity contact = new Entity("contact");

            contact["firstname"] = txtFirstName.Text.ToString();

            contact["lastname"] = txtLastName.Text.ToString();

            contact["emailaddress1"] = txtEmailAddress.Text.ToString();

            contact["telephone1"] = txtPhoneNumber.Text.ToString();

            Guid newContactId = service.Create(contact);

           

            //This code will clear the textboxes after the contact is created.

            txtFirstName.Text = "";

            txtLastName.Text = "";

            txtEmailAddress.Text = "";

            txtPhoneNumber.Text = "";

        }

    }

}

6.       Compile and Run the Custom Page.

a.       Click Build|Build Solution. If everything is correct you will see it say Build Succeeded at the bottom of the Visual Studio Window.

image

b.       Click Debug|Start Debugging. This will launch the website locally within Internet Explorer and allow for testing.

c.        Enter information into each of the text boxes and then click the Submit button. The textboxes will automatically clear out once the contact has been created.

Note: The user will need to be a CRM user for the contact to be created.

image

d.       Open the CRM Web Client to see the newly created Contact Record.

image

 

Comments (42)

  1. JD says:

    Looks great..

    It works for CRM 2011 online?

  2. JMorlock says:

    This sample uses AD authentication which will only work with CRM 2011 On-Premise. The authentication would be different to work correctly with CRM 2011 Online. The CRM 2011 Online authentication it is a little more complicated and would be best to use the Helper class provided with the CRM SDK. In the SDK documentation there is some sample code and pre-built applications. If you search the SDK for "Quick Start: A Simple Program" there is a console application using the helper class that will work with CRM Online. I plan on writing another blog entry with steps on using the Helper class.

  3. JD says:

    Thanks  alot.. I'm looking forward for your blog on Helper class.

    Hopefully on CRM online authentication 🙂

  4. ABZ says:

    I'm getting this error "The provided uri did not return any Service Endpoints!"

    at

    using (OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(OrganizationUri, HomeRealmUri, Credentials, null))

    Please help..

  5. Demail says:

    Hi,

    May need your advice — how to deploy it to the web using iis? I'm developing the customer form and gathering customer registration details from the web.

    The steps I did was —

    1. Publish the web project at visual studio 2010 (.net 4.0)

    2. Copy the files to inetpub

    3. Convert the folder to Application

    As result, I still not able to view the page..

    Anything wrong here?

  6. JMorlock says:

    ABZ,

    In the code make sure the following line of code is updated to match the url you access CRM with and that you can access this URL within IE. It should pull up a page with information about the endpoint.

         Uri OrganizationUri = new Uri("http://<SERVERURL>/<ORGNAME>/XRMServices/2011/Organization.svc&quot;);

    If the URL is correct it could also happen if you have more than one binding on the CRM website. Similar issues would be noticed if you tried to configure the CRM 2011 Email Router.

    support.microsoft.com/…/2501732

  7. Bilu says:

    Does this work for IFD ? I am getting the 'The user authentication failed' error, however if i hardcode the use name and password, it works fine.. Can you explain if any settings to be done in web.config

  8. JMorlock says:

    Bilu,

    This page was developed to use Windows authentication so it would be expected that you are logged in on a domain machine with a CRM user. You would need to change the authentication in the code to work with claims.

  9. Justin says:

    What would you have to do to change this app to update records instead of creating new ones?

    Thanks!

  10. Does creating aspx web pages and integrating with dynamics crm 2011 is supported by MS? In the SDK they are recommending to use web resources such as silverlight.

  11. Ashu says:

    Great tutorial.

    developer like me who is new to CRM build in one go. THANKS.

  12. JMorlock says:

    Justin- To update values you would just need to run the service.Update instead of service.Create. It would also require you to pass the contactid attribute in the object. Otherwise basically the same.

    Mukesh- If the page will be displayed in CRM then you'd want to develop in a way that can be used in a web resource. However if you are developing a page that will be outside of CRM this is one route that you can take. For example it could be a page on an intranet site to enter some sort of records into CRM.

  13. How to get attribute names from crm (customer has a possibility to add fields) in order to use them for late-binding?

  14. MF says:

    I am trying to write a similar solution using a console app, where I will read in a data file and add one CRM Contact for each record in the file. Although I have added Microsoft.Xrm.sdk as a Reference, the Imports statements for Microsoft.Xrm.Sdk.Client and Microsoft.Xrm.Sdk are not resolving. There is no error message and no suggested correction.

    Can you point me in the right direction?  Thanks.

  15. Nalini says:

    thanks,this was very useful to me,Now i want to update this fields in existing crm records…can anyone help me…

  16. Kulwant says:

    Can anyone suggest me?

    I have just signed up with MS Dynamic CRM 2011 Online, I want everything to start from scratch, To connect my website with the CRM about creating leads and Contacts. I am going to ask my website developer about re-designing the website by .NET and Visual Studio.

    Please suggest me any other better ways to develop the whole system for long run.

  17. Mert says:

    service.Update(contact);   how ll it work ?does anybody has sample code

  18. Hi, I'm new at developing for crm. Please assist me.

    I have a webpage that looks the same as the CRM 2011 window that shows the details of an account which I will use to create a new account. Everything works fine but for one thing. I don't know the id's of the fields on the form so I'm having problems with inserting some records.

    For instance; In the code: –> account["name"] = txtAccName.Text.ToString();

    "name" is fine because it is a correct id for the account name. Can you please provide me with id's for all the other controls on the form or tell me where I can find them.

    Thank you 🙂

  19. Ewerton Willams says:

    Hey, we have here the CRM 2011 On-Primise, but we need to build a simple webpage to make the clients (not CRM users) fill a form and submit tha data to the CRM, to be inserted in an entity. Is this possible with this code or I need the helper classes from sdk?

  20. Sudip Chakrovorty says:

    One of the best Step by Step instructions i have seen, you did a very good job…

    Keep it up like this. Instructions are so clear that anyone can implement this.

    Such a great post!

    I really appreciate your efforts.

  21. Karthik says:

    Hi Morlock,

    Do u have any idea about this error –  The authentication endpoint Username was not found on the configured Secure Token Service!

    I unable to create the record through service. Please help me

  22. Reham says:

    Hello, The code looks perfect,

    I have one question though, can you create one form (Like the one above) and add more sections to it (Like Accounts and Orders) that would actually auto populate the Account and the Orders form in CRM?

    Or, on the other hand, add like a "Next" buton that will take the user to another forms (Account info for example) that would populate the account form in CRM ?

    Thank you

  23. @Ewerton Willams – Yes you can do that however from a licensing perspective you'll want to make sure you have the external connector license for CRM. And you may also want to look at the portal accelerator within the CRM SDK as that will already have answers to many common hurdles for solutions as the one you're likely looking at building.

    @Karthik – if you're getting that error it is coming from your STS for ADFS (if you're using ADFS) since you're using IFD you'll need to reference the SDK documentation and alter your credential setup for IFD deployments and you should be fine.  

    @Reham, Yes, as you are leaving up to – one way would be to pre-create all the records with the information in CRM from the form.  If you wanted to, instead, pass the information to a CRM form using the URL Addressable forms you could also use the "ExtraQS" query string capabilities to pass in data.  My opinion, is if you're already using code behind you may as well create the information via the endpoint – but it really does depend on the scenario.  Thanks!

    Sean McNellis

    Premier Field Engineer

  24. Hi McNellis,

    I Created one ASP.net application for this ontact form and trying to update CRM contact form. I am doing this from my local windows 7 OS. I m getting the error "The authentication endpoint Username was not found on the configured Secure Token Service!". I m connecting online CRM and added 'DeviceId" class from helper code to my website. But still i am facing this problem. Please help me to resolve this error in windows 7.

    – Karthik

  25. @Karthik, check out the SDK documentation for connecting to Federation, most likely your online deployment is either federated with an on premise STS or you're in the new online environment which uses online federation I believe (different than the CTP environment).  Take a look at this article with sample code on how to connect to the new office365 based Dynamics CRM: msdn.microsoft.com/…/hh670628.aspx

  26. Works like a charm 🙂 thanks …

  27. Sekhar Pathakuntla says:

    Thank U .., this post help me a lot

  28. Manish Jain says:

    I am getting following error while running the web site

    The Security Support Provider Interface (SSPI) negotiation failed.

      at System.ServiceModel.Security.WindowsSspiNegotiation.GetOutgoingBlob(Byte[] incomingBlob, ChannelBinding channelbinding, ExtendedProtectionPolicy protectionPolicy)

      at System.ServiceModel.Security.SspiNegotiationTokenProvider.GetOutgoingBlobProxy.GetOutgoingBlob(ChannelBinding channelBinding)

      at System.ServiceModel.Security.RequestSecurityToken.GetBinaryNegotiation()

      at System.ServiceModel.Security.WSTrust.Driver.WriteRequestSecurityToken(RequestSecurityToken rst, XmlWriter xmlWriter)

      at System.ServiceModel.Security.RequestSecurityToken.OnWriteTo(XmlWriter writer)

      at System.ServiceModel.Security.RequestSecurityToken.WriteTo(XmlWriter writer)

      at System.ServiceModel.Security.RequestSecurityToken.OnWriteBodyContents(XmlDictionaryWriter writer)

      at System.ServiceModel.Channels.BodyWriterMessage.OnWriteBodyContents(XmlDictionaryWriter writer)

      at System.ServiceModel.Channels.Message.OnWriteMessage(XmlDictionaryWriter writer)

      at System.ServiceModel.Channels.BufferedMessageWriter.WriteMessage(Message message, BufferManager bufferManager, Int32 initialOffset, Int32 maxSizeQuota)

      at System.ServiceModel.Channels.TextMessageEncoderFactory.TextMessageEncoder.WriteMessage(Message message, Int32 maxMessageSize, BufferManager bufferManager, Int32 messageOffset)

      at System.ServiceModel.Channels.HttpOutput.SerializeBufferedMessage(Message message)

      at System.ServiceModel.Channels.HttpOutput.Send(TimeSpan timeout)

      at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.SendRequest(Message message, TimeSpan timeout)

      at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)

      at System.ServiceModel.Security.IssuanceTokenProviderBase`1.DoNegotiation(TimeSpan timeout)

  29. @Manish – at first glance that looks like a Kerberos failure be sure to check out this article on setting up load balanced environments: blogs.msdn.com/…/kerberos-in-load-balanced-environments.aspx

    If you're not load balanced, make sure you're not using an IP address, verify your machine is domain joined, and if you're on the domain also make sure your system clocks are all sync'd

  30. Arun kumar says:

    hi i am getting error "metadata contains a reference that cannot be resolved". i want to connect with CRM 2011 onpremise version which is IFD configured. but i am not able . Please anyone help me.

  31. Arun kumar says:

    hi i am getting error "metadata contains a reference that cannot be resolved". i want to connect with CRM 2011 onpremise version which is IFD configured. but i am not able . Please anyone help me.

  32. Pavan says:

    Hi When I am trying to execute I get this error,

    Value cannot be null.

    Parameter name: detail

     Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.ArgumentNullException: Value cannot be null.

    Parameter name: detail

    Any help?

  33. mnicks says:

    Very helpful!  Thanks!

  34. anu says:

    how to write update code for an entity. ? can somebody show the detailed code.

  35. Joeri says:

    i have a strange issue.

    my page works locally on my development pc, but when i deploy it on our server, it is not working anymore.

  36. KK says:

    Hi m getting error at line :

    using (OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(OrganizationUri, HomeRealmUri, Credentials, null))

    the error is  "InvalidOperationException was unhandled by the user code".Metadata contains a reference that cannot be resolved:

    plz suggest

  37. Try making sure you publish any outstanding customizations, also try an iisreset (just in case), finally i have gotten this when I'm trying to use a hostname that doesn't match what CRM expects (under the web address tab in deployment manager) or when you try to use http when CRM is configured to use SSL/HTTPS.

  38. I forgot to mention, if you're not using IFD then you may need to change that method to take in a username and password (or default credentials).

  39. nithin says:

    how to create login page using fetchxml code from crm ….in aspx web page

  40. KreenaP says:

    Hi,

    Thanks a lot!! It worked for me..

    Can you also share the code to create appointment ??

  41. Saranya says:

    Hi,

        I need to launch microsoft dynamics CRM for windows 8 app from my app. Please suggests the uri for the CRM from windows app

  42. akram khan says:

    Hello all,
    Is this code work for dynamic Crm 2016 on-promises.

Skip to main content