The Microsoft Dynamics CRM Blog
News and views from the Microsoft Dynamics CRM Team

Creating and Publishing a Web Portal to an Azure Cloud Service

Creating and Publishing a Web Portal to an Azure Cloud Service

  • Comments 5

Hello all:

At Convergence a few weeks ago I presented some CRM demos and this article will be the first in detailing how those demos were created and how you can mirror the functionality in your CRM Online deployment.

This first article will cover the creation and publishing of a Web Portal published to an Azure Cloud Service that can be used to capture simple lead information and subsequently create Leads in Microsoft Dynamics CRM Online. The creation of the portal involves just a few steps:

  1. Creating an Azure Account
  2. Creating an Azure Web Site
  3. Developing your web portal in Visual Studio using C#
  4. Publishing your web portal to the Azure web site

Note that it does not matter if you decide to create the site first and then create the Azure portal or vice versa, in this article we will first create the Azure account and web site, and then the web site. So let’s get started!

First, sign up for a free trial on Azure and fill out the necessary fields to create a new Azure account. Note that if you or your company has an MSDN subscription you can also access Azure via MSDN subscription benefits. Once on the page shown below (direct URL: http://www.windowsazure.com/en-us/pricing/free-trial/) click the “Try it Free’ button and complete the sign up process.

The next step is to create the Azure web site which will host your new portal.  From the Azure main page, click the link for the “Management Portal.”

Once you reach the management portal page, on the left-hand navigation bar click “Web Sites” and then click “New”.


 

A new page will appear with some information that needs to be filled out to create a new web site.

  1. Click “Quick Create”
  2. Enter a name for your new web site, the new URL will be <yoursitename>.azurewebsites.net. I am using crmblogportal for this example.
  3. Click “Create Web Site”

When Azure finishes creating the site, you’ll see a page like this one showing the site(s) you have created. Click the link for the site you just created.

We need to get the publishing profile for our new site so we can upload our portal from Visual Studio, so on this page, in the middle section with the title “Publish your App”, click the link “Download the publish profile” and when prompted save the file to your desktop (or anywhere on your hard drive as long as you remember where!). The file will be named <yoursitename>.azurewebsites.net.PublishSettings.

And that’s it. Your new Azure web site is set up and ready for you to upload whatever you create to it. The next steps involve creating the portal site itself in Visual Studio.

For the next steps we need to build a web site in Visual Studio so if you have Visual Studio installed, fire it up. If not and you have a personal or corporate MSDN subscription, you can download it there, or you can download and install Visual Studio Express from http://www.microsoft.com/visualstudio/eng/products/visual-studio-express-products.

Lastly, we’ll need the CRM SDK, so download and install the SDK from http://www.microsoft.com/en-us/download/details.aspx?id=24004.

For the Convergence demo we needed a site that allowed a user to register on a web form, and then that web form created a new lead in CRM. I will use this site in this example, but note you can create any site in Visual Studio that you wish.

When Visual Studio Starts, select File->New Project->and then on the left under “Templates” click “Visual C#” and then click “Web” and then select the “ASP.NET Web Forms Application” template.

This template generates a web site with a lot of the portal functionality already there, so saves a lot of work if it meets your needs. In the Solution Explorer view, expand the “Account” folder and double-click the “Register.aspx” file to open it in the editor. Note that this page is generated by Visual Studio and uses a control called the “CreateUserWizard” which has some great built-in functionality, but is also somewhere difficult to modify. For this reason I created a new page for the Convergence demo, so right-click on the “Account” folder, and in the Context Menu that appears select “Add->New Item”. On the left-hand panel be sure that “Web” is selected under “Visual C#”, and in the list in the middle, select “Web Form using Master Page”. Name the new page “NewUser.aspx”, click “Add” and then on the confirmation dialog, select “Site.Master”.

Right-click on “NewUser.aspx”, select “Set as Start page”, and then press F5 to run the site, and you’ll see we have a very simple page but that the style of the site is applied so we have a good starting point.

The first step is to change the image that says “Your Logo here” to a logo of your choosing, I’ll use the Dynamics CRM logo.

Close the browser window, and then in Visual Studio on the right-side in Solution Explorer, right-click the Images folder and select “Add->Existing Item”, and then in the file browser window browse to your logo image file, and double-click on the file to add it to the Images folder of your project. Now, because we are working with a Master site page template, we cannot edit the log on the NewUser.aspx page, we have to make the change on the Site.Master page, so in Solution Explorer double-click Site.Master to open it in the editor. Click the “Source” button in the editor window, and then in the code find the line that says

<a runat="server" href="~/">your logo here</a>

it should be at line 43 or thereabouts. Change this line to:

<a runat="server" href="http://www.microsoft.com/en-us/dynamics/crm.aspx"><img src=" ../Images/crm_logo.PNG" border="0"/></a>

Where “crm_logo.png” is whatever image file you used, and of course you can change the URL too! Note that Visual Studio might add

id="A1"

to the line, if so, delete that.

Save the project and press F5 to run it, and you should see the changed logo. Click on it and the Dynamics CRM site will open.

Close the browser.

We are now ready for the next step, which is to add the controls we need to build the New User input form. We’ll keep it very simple and just use 2 fields. In “Solution Explorer”, double-click “NewUser.aspx” to open the form in the editor, and insert the code pasted below in between these lines (should be lines 6 and 7):

 <asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
  <PASTE CODE HERE>
</asp:Content>

Paste this code:

<ContentTemplate>
<p class="validation-summary-errors">
  <asp:Literal runat="server" ID="ErrorMessage" />
</p>
<fieldset>
  <legend>Registration Form</legend>
  <ol>
    <li>
    <asp:Label ID="Label3" runat="server" AssociatedControlID="FullName">Full  Name</asp:Label>
    <asp:TextBox runat="server" ID="FullName" />
    <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="FullName"
    CssClass="field-validation-error" ErrorMessage="The Full Name field is required." />
  </li>
  <li>
  <asp:Label ID="Label4" runat="server" AssociatedControlID="MobilePhone">Mobile Phone</asp:Label>
  <asp:TextBox runat="server" ID="MobilePhone" />
  <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="MobilePhone"
  CssClass="field-validation-error" Display="Dynamic" ErrorMessage="The Mobile Phone field is required." />
</li>
</ol>
<asp:Button ID="Button1" runat="server" Text="Register" OnClick="Button1_Click" />
</fieldset>
</ContentTemplate>

We now need to add the Event handler for the Register Button click event, so save the project, then click the “Design” button and double-click the button “Register” to add the event handler. Note that we’ll add the code later to create the lead in CRM, for now just adding the event handler is all we need to do. Save the project, press F5 to run the page, and you should see a page similar to this:

 

Our page is shaping up, but it still doesn’t do anything to create a lead in CRM. We’ll wire up that functionality in a bit, but right now we need to create a “Thank you” page to display to the user when registration is complete. As we did with the NewUser.aspx page, right-click on the Account folder, and select “Add->New Item”, and then on the left-hand panel be sure that “Web” is selected under “Visual C#”, and in the list, be sure “Web Form using Master Page” is selected. Name the new page “Thankyou.aspx”, click “Add” and then on the confirmation dialog, select “Site.Master”. Double click on “Thankyou.aspx” to open it in the editor, and then in between the 3rd content tags:

<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
</asp:Content>

Paste the following code:

<ContentTemplate>
  <fieldset>
    <legend>Thank you!!</legend>
  </fieldset>
  <p>
    <h1>Thank you for registering!!</h1>
  </p>
</ContentTemplate>

Save the project.

Now we’ll write the code that does the work of creating the new lead in CRM. First, we need to add a few references from the Microsoft Dynamics CRM SDK, so in the Solution Explorer view, right-click “References” and select “Add Reference”.  Click “Browse” on the dialog that appears, and then browse to the folder where you installed the CRM SDK, and then browse to the “sdk\bin folder”. Hold the <ctrl> key, select the following files to add, and click “Add”.

  • Microsoft.xrm.sdk.dll
  • Microsoft.xrm.portal.dll
  • Microsoft.xrm.client.dll
  • Microsoft.crm.sdk.proxy.dll

You also need to add a reference to Microsoft.IdentityModel.dll which is not part of the SDK download, but is likely on your PC already (do a search for it). If not, you can download it here: Download Microsoft.IdentityModel dll

Add the reference the same way you added the SDK references.

We next need to add a reference to several Assemblies from the .NET Framework, so in the Reference Manager window select “Assemblies” from the left-hand navigation, and then select:

  • System.DirectoryServices
  • System.DirectoryServices.AccountManagement
  • System.Runtime.Serialization
  • System.Security
  • System.ServiceModel

Click OK and all the references will be added.

Next, we need to add some of the helper classes that come with the SDK to enable authentication to CRM Online. Right-click on the Account folder, and select “Add->Existing Item”. Browse to the folder where you installed the SDK, and browse to “\sdk\samplecode\cs\helpercode” and add the following files:

  • Crmservicehelper.cs
  • Deviceidmanager.cs
  • Myorganizationcrmsdktypes.cs

 Next we need to add a line to the web.config (not the Web.config file in the Account folder, but the one under the Project itself) file for our connection string, so double-click web.config to open it. In the <connectionStrings> section, add the following lines:

<!-- Online using Office 365 -->
<add name="Server=CRM Online, organization=your org, user=user name" connectionString="Url=https://yourorg.crm.dynamics.com; Username=username; Password=password;"/>

Where:
your org = your organization name
user = the user name for your org
UserName = full user name
password = the user password

So for example, the org I used for Convergence Demos was called Convergence1 and the username was admin, so my connection string was (with <password> replaced by the actual password for my user account):

<add name="Server=CRM Online, organization=convergence1, user=admin"
connectionString="Url=https://convergence1.crm.dynamics.com;
Username=admin@convergence1.onmicrosoft.com; Password=<password>;"/>

Next we need to add the code to the NewUser.aspx.cs file, so right-click on NewUser.aspx and select “View Code”.  Add the following using statements:

using Microsoft.AspNet.Membership.OpenAuth;

using System.Configuration;
using System.ServiceModel;

// These namespaces are found in the Microsoft.Crm.Sdk.Proxy.dll assembly
// located in the SDK\bin folder of the SDK download.
using Microsoft.Crm.Sdk.Messages;

// These namespaces are found in the Microsoft.Xrm.Sdk.dll assembly
// located in the SDK\bin folder of the SDK download.
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;

// These namespaces are found in the Microsoft.Xrm.Client.dll assembly
// located in the SDK\bin folder of the SDK download.
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Client.Services;

Then, just below the lines:

public partial class NewUser : System.Web.UI.Page
{

add these lines:

#region Class Level Members
private Guid _leadId;
private OrganizationService _orgService;
public String connectionString;
#endregion Class Level Members

So at this point, the entire NewUser.aspx.cs file should look like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Microsoft.AspNet.Membership.OpenAuth;

using System.Configuration;
using System.ServiceModel;

// These namespaces are found in the Microsoft.Crm.Sdk.Proxy.dll assembly
// located in the SDK\bin folder of the SDK download.
using Microsoft.Crm.Sdk.Messages;

// These namespaces are found in the Microsoft.Xrm.Sdk.dll assembly
// located in the SDK\bin folder of the SDK download.
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;

// These namespaces are found in the Microsoft.Xrm.Client.dll assembly
// located in the SDK\bin folder of the SDK download.
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Client.Services;

namespace CrmBlogPortal.Account
{
  public partial class NewUser : System.Web.UI.Page
  {
   #region Class Level Members
    private Guid _leadId;
    private OrganizationService _orgService;
    public String connectionString;
    #endregion Class Level Members

    protected void Page_Load(object sender, EventArgs e)
    {

     }

     protected void Button1_Click(object sender, EventArgs e)
    {

     }
  }
}

Save and build the project to be sure there are no errors. We also need to add some methods from the SDK for processing authentications. Just after the Button1_Click method, paste the following code.  So where this method appears in the file:

protected void Button1_Click(object sender, EventArgs e)
{
}

// Paste the code here!!

Code:

    #region Private Methods
    /// <summary>
    /// Gets web service connection information from the app.config file.
    /// If there is more than one available, the user is prompted to select
    /// the desired connection configuration by name.
    /// </summary>
    /// <returns>A string containing web service connection configuration information.</returns>
    private static String GetServiceConfiguration()
    {
      // Get available connection strings from app.config.
      int count = ConfigurationManager.ConnectionStrings.Count;

      // Create a filter list of connection strings so that we have a list of valid
      // connection strings for Microsoft Dynamics CRM only.
      List<KeyValuePair<String, String>> filteredConnectionStrings =
          new List<KeyValuePair<String, String>>();

      for (int a = 0; a < count; a++)
      {
        if (isValidConnectionString(ConfigurationManager.ConnectionStrings[a].ConnectionString))
          filteredConnectionStrings.Add
              (new KeyValuePair<string, string>
                  (ConfigurationManager.ConnectionStrings[a].Name,
                  ConfigurationManager.ConnectionStrings[a].ConnectionString));
      }

       // No valid connections strings found. Write out and error message.
      if (filteredConnectionStrings.Count == 0)
      {
        Console.WriteLine("An app.config file containing at least one valid Microsoft Dynamics CRM " +
            "connection string configuration must exist in the run-time folder.");
        Console.WriteLine("\nThere are several commented out example connection strings in " +
            "the provided app.config file. Uncomment one of them and modify the string according" +
            "to your Microsoft Dynamics CRM installation. Then re-run the sample.");
        return null;
      }

       // If one valid connection string is found, use that.
      if (filteredConnectionStrings.Count == 1)
      {
        return filteredConnectionStrings[0].Value;
      }

      // If more than one valid connection string is found, let the user decide which to use.
      if (filteredConnectionStrings.Count > 1)
      {
        Console.WriteLine("The following connections are available:");
        Console.WriteLine("------------------------------------------------");

        for (int i = 0; i < filteredConnectionStrings.Count; i++)
        {
          Console.Write("\n({0}) {1}\t",
          i + 1, filteredConnectionStrings[i].Key);
        }

         Console.WriteLine();

        Console.Write("\nType the number of the connection to use (1-{0}) [{0}] : ",
            filteredConnectionStrings.Count);
        String input = Console.ReadLine();
        int configNumber;
        if (input == String.Empty) input = filteredConnectionStrings.Count.ToString();
        if (!Int32.TryParse(input, out configNumber) || configNumber > count ||
            configNumber == 0)
        {
          Console.WriteLine("Option not valid.");
          return null;
        }

         return filteredConnectionStrings[configNumber - 1].Value;

       }
      return null;

     }

     /// <summary>
    /// Verifies if a connection string is valid for Microsoft Dynamics CRM.
    /// </summary>
    /// <returns>True for a valid string, otherwise False.</returns>
    private static Boolean isValidConnectionString(String connectionString)
    {
      // At a minimum, a connection string must contain one of these arguments.
      if (connectionString.Contains("Url=") ||
          connectionString.Contains("Server=") ||
          connectionString.Contains("ServiceUri="))
        return true;
      return false;
    }
    #endregion Private Methods

Save and build the project.

We’re almost there! The next step is to add the code to the Button1_Click method that actually creates the new Lead in CRM from the information entered on the web form. Replace the method:

protected void Button1_Click(object sender, EventArgs e)
{
}

With this:

    protected void Button1_Click(object sender, EventArgs e)
    {
      try
      {
        // Obtain connection configuration information for the Microsoft Dynamics
        // CRM organization web service.
        connectionString = GetServiceConfiguration();

        // Establish a connection to the organization web service using CrmConnection.
        Microsoft.Xrm.Client.CrmConnection connection = CrmConnection.Parse(connectionString);

        // Obtain an organization service proxy.
        // The using statement assures that the service proxy will be properly disposed.
        using (_orgService = new OrganizationService(connection))
        {
          // Obtain information about the logged on user from the web service.
          Guid userid = ((WhoAmIResponse)_orgService.Execute(new WhoAmIRequest())).UserId;
          SystemUser systemUser = (SystemUser)_orgService.Retrieve("systemuser", userid,
              new ColumnSet(new string[] { "firstname", "lastname" }));

          // Retrieve the version of Microsoft Dynamics CRM.
          RetrieveVersionRequest versionRequest = new RetrieveVersionRequest();
          RetrieveVersionResponse versionResponse =
              (RetrieveVersionResponse)_orgService.Execute(versionRequest);

          //This code grabs the data entered in the Full Name text field,
          //and splits it into first name and
          //last name. The input is expected in format <FirstName> <LastName>
          string strFullName = FullName.Text;
          string delimStr = " ";
          char[] delimiter2 = delimStr.ToCharArray();
          string[] nameSplit = null;
          nameSplit = strFullName.Split(delimiter2);

           //This is the Code that creates the new lead
          Lead newLead = new Lead
          {
            Subject = "New lead from Convergence",
            LastName = nameSplit[1].ToString(),
            FirstName = nameSplit[0].ToString(),
            MobilePhone = MobilePhone.Text.ToString()
          };

           _leadId = _orgService.Create(newLead);

         // Change this line to point at your web site
        Response.Redirect(http://<yourwebsite>.azurewebsites.net/Account/Thankyou.aspx);

          }
       }

         // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
      catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
      {
        // You can handle an exception here or pass it back to the calling method.
        throw;
      }
    }

Note, in the Response.Redirect line, be sure to change the URL to point at your web site.

That should complete our web site and we can test it locally by saving, and then pressing F5 to run the site. Enter values for the Name (be sure to enter a First Name and a Last Name separated by a space) and the mobile phone, and then click “Register”.  The “Thank you” page will display.

And then if we go to our CRM instance we can see the new lead created by the web page.

 

And opening the Lead shows that the information from the web form was populated in the Lead:

 

The last step before we publish the web site is to change the “Register” link on the home page to point at our new Newuser.aspx page. Double-click Site.Master to open it, and then find this line:

<li><a id="registerLink" runat="server" href="~/Account/Register">Register</a></li>

Change this line to this:

<li><a id="registerLink" runat="server" href="~/Account/NewUser.aspx">Register</a></li>

Save the project and the last step is to publish our new site to the Azure web portal. In Visual Studio right-click the project, and then select Publish.

 

When the dialog shown below appears, click “Import” and browse to the location where you saved the publish settings file, it is named:

<yoursite>.azurewebsites.net.PublishSettings

And select the file, then click Next.

 

Click Next on this screen:

 

And click Next again:

 

And then click Publish.

 

When the publishing process completes, Visual Studio will display Success messages as shown here:

 

And then your newly published site will open in a browser, click the “Register” link to open your NewUser.aspx page.

 

When the NewUser.aspx page opens, fill in some data and then click the “Register” button.

 

And the “Thank you” page should display.

 

To confirm our page works, open up your CRM instance and confirm your new lead is there:

 

This example, while simple, has demonstrated:

  • Setting up an Azure account
  • Setting up Azure web sites
  • Creating web site projects in Visual Studio
  • Connecting web forms to Dynamics CRM Online
  • Publishing web projects to Azure web sites

Now that you have the basics in place you can modify the web project whatever way you need to in order to meet your business objectives.

The full Visual Studio project code can be downloaded at CrmBlogPortal Source.

John Straumann
Senior Technical Product Manager
Dynamics CRM Product Marketing Group

  • Excellent!!

  • Truly Excellent !!!

  • Nice post. I've learned a lot from it. thanks.

  • Excellent !!!

    Thanks for post. Helped a lot.

  • Excellent. I found this blog useful for understanding the way of publishing your website on azure cloud service. But My question is, what will be advantage of this, if i have CRM onpremise version available?

Page 1 of 1 (5 items)
Leave a Comment
  • Please add 7 and 3 and type the answer here:
  • Post