17.04.2013, 23:11 | #1 |
Участник
|
Microsoft Dynamics CRM Team Blog: Creating and Publishing a Web Portal to an Azure Cloud Service
Источник: http://blogs.msdn.com/b/crm/archive/...d-service.aspx
============== 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:
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.
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 .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/visualstudi...press-products. Lastly, we’ll need the CRM SDK, so download and install the SDK from http://www.microsoft.com/en-us/downl....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 your logo here it should be at line 43 or thereabouts. Change this line to: 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): Paste this code: Registration Form
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: Paste the following code: Thank you!! Thank you for registering!! 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 key, select the following files to add, and click “Add”.
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:
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:
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 section, add the following lines: 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 replaced by the actual password for my user account): 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 /// /// 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. /// /// A string containing web service connection configuration information. 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 filteredConnectionStrings = new List(); for (int a = 0; a < count; a++) { if (isValidConnectionString(ConfigurationManager.ConnectionStrings[a].ConnectionString)) filteredConnectionStrings.Add (new KeyValuePair (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; } /// /// Verifies if a connection string is valid for Microsoft Dynamics CRM. /// /// True for a valid string, otherwise False. 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 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://.azurewebsites.net/Account/Thankyou.aspx); } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException) { // 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: Register Change this line to this: Register 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: .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:
The full Visual Studio project code can be downloaded at CrmBlogPortal Source. John Straumann Senior Technical Product Manager Dynamics CRM Product Marketing Group Источник: http://blogs.msdn.com/b/crm/archive/...d-service.aspx
__________________
Расскажите о новых и интересных блогах по Microsoft Dynamics, напишите личное сообщение администратору. |
|
|
|