Latest Microsoft Dynamics 365 Blogs | CloudFronts - Page 34

Microsoft Dynamics CRM 2015 Web API

Posted On July 17, 2015 by Admin Posted in

Microsoft has released the Dynamics CRM Web API with the 2015 Spring Update. The purpose of this blog article is to demonstrate the use of the CRM Web API for performing different data operations. Before we begin using the Web API there are a few pre-requisites. Azure Subscription Dynamics CRM 2015 Update 1 Dynamics CRM user with System Administrator role Next we need to follow the steps given below to start using the Web API: Enable Web API Preview in CRM. Web API Preview can be enable in Dynamics CRM 2015 Update 1 from Settings> Administration > System Settings. Associate Azure Subscription to your Dynamics CRM Tenant. You can follow the steps given here to associate your Azure Subscription to your Dynamics CRM tenant. Register an App on Azure Active Directory. Log In to Azure and go to Active Directory -> <your directory> ->Applications -> Add Click on “Add an application my organization is developing”. Select “Native Client Application” and enter the name of the application. Enter the Redirect URI as http://localhost/<yourappname> and then click on Ok. Once completed you will be redirected to the application page. Click on “Configure Access to Web Apis in other applications” and then click on “Configure it now”. Click on Add Application and select Dynamics CRM Online and then click on Complete. Next, Under Delegated Permissions check “Access CRM Online as organization users” and click on Save. Also copy and save the ClientID and Redirect URI as we will require this is our code. Create a .Net App to start consuming the Web API Create a new Console Application project in Visual Studio. Right Click on the Project and click on Manage NuGet Packages. Enter “adal” in the search box and then install Active Directory Authentication Library. This will install the required .dlls to help us authenticate using Azure Active Directory. Add the below code in the Main() method of your program. string resource = “https://<yourdomain>.crm.dynamics.com/”; string clientID = “<your client id>”; string redirectUrl = “<your redirect uri>”; AuthenticationContext authContext = new AuthenticationContext(“https://login.windows.net/common”, false); AuthenticationResult result = authContext.AcquireToken(resource, clientID, new Uri(redirectUrl)); Run the code by pressing f5. You will be prompted to enter your user credentials. After entering the credentials the server returns an Authentication Token. The AccessToken and the AccessTokenType (“Bearer”) is what we need to include into every Authorization header of http request. Next into every requests we make to the CRM Web API we need to pass this authentication token. Below is a Sample Code which demonstrates use of CRM Web API for Create, Retrieve, Update and Delete Operations. using Microsoft.Crm.Sdk.Samples.HelperCode; using Microsoft.IdentityModel.Clients.ActiveDirectory; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using WebAPITest.Entities; namespace WebAPITest { class Program { static string resource = “https://destroyskynet.crm.dynamics.com/”; static string clientID = “<your client id>”; static string redirectUrl = “http://localhost/webapitest”; static void Main(string[] args) { AuthenticationContext authContext = new AuthenticationContext(“https://login.windows.net/common”, false); Task.WaitAll(Task.Run(async () => await DataOperations(authContext))); } private static async Task DataOperations(AuthenticationContext auth) { using (HttpClient httpClient = new HttpClient()) { httpClient.BaseAddress = new Uri(“https://destroyskynet.crm.dynamics.com”); httpClient.Timeout = new TimeSpan(0, 2, 0); //2 minutes httpClient.DefaultRequestHeaders.Add(“OData-MaxVersion”, “4.0”); httpClient.DefaultRequestHeaders.Add(“OData-Version”, “4.0”); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(“application/json”)); Account account = new Account(); account.name = “Cloudfronts TechnologiesNew”; account.telephone1 = “555-555”; string content = String.Empty; content = JsonConvert.SerializeObject(account, new JsonSerializerSettings() { DefaultValueHandling = DefaultValueHandling.Ignore }); httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(“Bearer”, auth.AcquireToken(resource, clientID, new Uri(redirectUrl)).AccessToken); //Create Entity HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, “api/data/accounts”); request.Content = new StringContent(content); request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(“application/json”); HttpResponseMessage response =await httpClient.SendAsync(request); if (response.IsSuccessStatusCode) Console.WriteLine(“Account ‘{0}’ created.”, account.name); else throw new Exception(String.Format(“Failed to create account ‘{0}’, reason is ‘{1}’.”, account.name, response.ReasonPhrase)); //Retreive Entity //The uri of the created entity is received in “OData-EntityId”. Use the account URI to update/delete account. string accountUri = response.Headers.GetValues(“OData-EntityId”).FirstOrDefault(); var retrieveResponse = await httpClient.GetAsync(accountUri + “?$select=name,telephone1”); Account retreivedAccount=null; if(retrieveResponse.IsSuccessStatusCode) { //Deserialize response into Account retreivedAccount = JsonConvert.DeserializeObject<Account>(await retrieveResponse.Content.ReadAsStringAsync()); Console.WriteLine(“Retreived Account Name : {0} Telephone : {1}”,retreivedAccount.name,retreivedAccount.telephone1); } else { throw new Exception(String.Format(“Failed to retreive account ‘{0}’, reason is ‘{1}’.”, account.name, response.ReasonPhrase)); } //Update Entity JObject accountToUpdate = new JObject(); accountToUpdate.Add(“name”, retreivedAccount.name + “Edited”); string updateContent = String.Empty; updateContent = accountToUpdate.ToString(); HttpRequestMessage updateRequest = new HttpRequestMessage(HttpMethod.Put, accountUri); updateRequest.Content = new StringContent(updateContent); updateRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(“application/json”); HttpResponseMessage updateResponse = await httpClient.SendAsync(updateRequest); if (response.IsSuccessStatusCode) Console.WriteLine(“Account ‘{0}’ updated.”, accountToUpdate[“name”]); else throw new Exception( String.Format(“Failed to update account ‘{0}’, reason is ‘{1}’.”, accountToUpdate[“name”], response.ReasonPhrase)); //Delete Account HttpResponseMessage deleteResponse = await httpClient.DeleteAsync(accountUri); if (response.IsSuccessStatusCode) Console.WriteLine(“Account deleted.”); else throw new Exception( String.Format(“Failed to delete account”)); } } } } Microsoft has also provided helper code to authenticate using credentials stored in the .config file. In my next article I will demonstrate how to use this helper code and authenticate users directly using the credentials stored in the .config file.

Share Story :

Powerful DAX CALCULATE() Function

Posted On June 24, 2015 by Admin Posted in Tagged in ,

The CALCULATE function in DAX is the magic key for many calculations we can do in PowerPivot. Below is the syntax: CALCULATE( <expression>, <filter1>, <filter2>… ) The expression that we put in the first parameter has to be evaluated to return the result (i.e. a value, not a table). For this reason, the expression is usually an aggregation function like SUM, MIN, MAX, COUNTROWS and so on. This expression is evaluated in a context that is modified by the filters. A key point is that these filters can both enlarge and restrict the current context of evaluation. Let’s try to understand what it means by considering a few examples. The following data model we have imported in PowerPivot named ‘Contract’ & ‘Project’ Scenario 1 Compare Contract & Project data model on YearMonth Column and take sum of multiple records of revenue column of Project data model into Contract data model Project data model has StartYM & StartRevenue Column as shown below And Contract data model has YM column, using Project data model StartYM, StartRevenue columns & Contract data model YM column, here we have derived StartR column with the help of Calculate() DAX function as shown below Formula is =calculate(sum(Project[StartRevenue]),filter(project,Project[StartYM]=Contract[YM])) Scenario 2 Calculate running total of ToDo column in ‘Contract-ToDo’ data model on basis of YearMonth column as shown below Formula is =calculate(sum(‘Contract-ToDo'[ToDo]),filter(‘Contract-ToDo’,’Contract-ToDo'[YearMonth]

Share Story :

UCC SAN SSL Certificate–GoDaddy/Azure

Introduction Adding sub-domain to UCC SSL 5 certificate and revoking existing SSL Certificate. Problem Statement: We have sub-domain called salesportal.mywebsite.com hosted on windows azure. Salesportal.mywebsite.com associated with SSL binding but that SSL is expired and we want to revoke that certificate and add it to UCC SSL 5 certificate from Go-daddy. => We have salesportal.mywesite.com hosted on windows azure. => SSL certificate purchase from Go-Daddy. In our case we want to remove standard certificate and add it to UCC 5 Certificate. Please follow below steps to revoke existing SSL and add it to New SSL certificate Installation To proceeds with SSL, first step is to download Open SSL. This is Open source software that will help us to create CSR request. Download Open SSL from following link: http://indy.fulgan.com/SSL/ Generate CSR Create CNF file for CSR For more detail visit following URL. http://azure.microsoft.com/en-in/documentation/articles/web-sites-configure-ssl-certificate/ Let’s understand how to apply SSL Certificate to multiple Domain. Download Sample code from http://azure.microsoft.com/en-in/documentation/articles/web-sites-configure-ssl-certificate/#bkmk_subjectaltname Example: # ————– BEGIN custom sancert.cnf —– HOME = . oid_section = new_oids [ new_oids ] [ req ] default_days = 730 distinguished_name = req_distinguished_name encrypt_key = no string_mask = nombstr req_extensions = v3_req # Extensions to add to certificate request [ req_distinguished_name ] countryName = Country Name (2 letter code) countryName_default = stateOrProvinceName = State or Province Name (full name) stateOrProvinceName_default = localityName = Locality Name (eg, city) localityName_default = organizationalUnitName = Organizational Unit Name (eg, section) organizationalUnitName_default = organization = Organization Name organization__default= commonName = Your common name (eg, domain name) commonName_default = www.mydomain.com commonName_max = 64 [ v3_req ] subjectAltName=DNS:payments. mydomain.com, DNS:blog.mydomain.com # ————– END custom sancert.cnf —– Note: => subjectAltName contains sub domain name. It can also contains main domain name as well. Example. www.crmonline.com File start with # ————– BEGIN custom sancert.cnf —– Above example can be tricky Problem statement 1: We have UCC SSL 5 certificate connected to payments.mywebsite.com and its running. We are adding salesportal.mywebsite.com domain to UCC SSL 5 certificate. In that case your Common Name will be payments.mywebsite.com and subjectAltName will be salesportal.mywebsite.com. Note: common name need to add from console window and subjectAltName in the cnf file. Example: # ————– BEGIN custom sancert.cnf —– HOME = . oid_section = new_oids [ new_oids ] [ req ] default_days = 730 distinguished_name = req_distinguished_name encrypt_key = no string_mask = nombstr req_extensions = v3_req # Extensions to add to certificate request [ req_distinguished_name ] countryName = Country Name (2 letter code) countryName_default = stateOrProvinceName = State or Province Name (full name) stateOrProvinceName_default = localityName = Locality Name (eg, city) localityName_default = organizationalUnitName = Organizational Unit Name (eg, section) organizationalUnitName_default = organization = Organization Name organization__default= commonName = Your common name (eg, domain name) commonName_default = www.mydomain.com commonName_max = 64 [ v3_req ] subjectAltName=DNS:salesportal.mywebsite.com, # ————– END custom sancert.cnf —– Problem Statement 2: We have UCC SSL 5 certificate connected to www.mywebsite.com and its running. We are adding salesportal.mywebsite.com domain to UCC SSL 5 certificate. In that case your Common Name will be www.mywebsite.com and subjectAltName will be salesportal.mywebsite.com. Please note: your common name you have to add from console window and subjectAltName in the cnf file. Example: # ————– BEGIN custom sancert.cnf —– HOME = . oid_section = new_oids [ new_oids ] [ req ] default_days = 730 distinguished_name = req_distinguished_name encrypt_key = no string_mask = nombstr req_extensions = v3_req # Extensions to add to certificate request [ req_distinguished_name ] countryName = Country Name (2 letter code) countryName_default = stateOrProvinceName = State or Province Name (full name) stateOrProvinceName_default = localityName = Locality Name (eg, city) localityName_default = organizationalUnitName = Organizational Unit Name (eg, section) organizationalUnitName_default = organization = Organization Name organization__default= commonName = Your common name (eg, domain name) commonName_default = www.mydomain.com commonName_max = 64 [ v3_req ] subjectAltName=DNS:salesportal.mywebsite.com, # ————– END custom sancert.cnf —– CSR Generation Write following command in Open SSL Console window. req -new -nodes -keyout myserver.key -out server.csr -newkey rsa:2048 -config sancert.cnf Note: sancert.cnf is above sample. myserver.key file is used to generate .pfx file. Steps 1: => Please fill basic information like Country name, State etc. => I have entered common name like payments.mywebsite.com because first time UCC SSL certificate is associate with payments.mywebsite.com. => If you are first time creating csr request then common name will be www.mywebsite.com If you want to check your CSR request then open CSR file in notepad and copy all code paste in following website. https://www.sslshopper.com/csr-decoder.html Revoke Expired SSL Certificate (GoDaddy) Always it’s better to revoke SSL certificate after it is expired. Please refer following URL for more support. https://support.godaddy.com/help/article/4747/revoking-an-ssl-certificate?countrysite=in Login to GoDaddy account: 1. Click on SSL Certificate: 2. Click on manage You can see we have one sub-domain Standard SSL is expired and another sub-domain has standard UCC SSL 5 certificate. We are going to add expired sub domain to standard UCC SSL certificate. 3. Click view status of expired domain. 4. Click on conform after that following window will appeared. 5. Wait for few minutes and refresh page. Certificate is expired successfully. 6. Following is status of certificate Add Domain to UCC 5 Certificate Click on domain which has UCC 5 certificate. If you have just purchase UUC 5 certificate then open that certificate and paste csr request. (Which also include # ————– BEGIN custom sancert.cnf —–# and # ————– END custom sancert.cnf —–#). Then click on manage. To add domain to UCC 5 Certificate, first we need re key that certificate Copy and paste your CSR in a text box Then Click on submit changes that will submit your New CSR request to GoDaddy Verification window will appeared. Refresh this page, you can see new Domain is successfully added to this certificate. Install certificate to Azure Download certificate from GoDaddy => Select Server type IIS and download zip file. => Important file is .crt extension and Ignore other files contain in zip => Open OpenSSl and click run as administrator(Run as administrator is IMP) Type following command in command line pkcs12 -export -out salesportal.pfx -inkey myserver.key -in 889d0fa6641ee566.crt myserver.key is … Continue reading UCC SAN SSL Certificate–GoDaddy/Azure

Share Story :

SEARCH BLOGS:

FOLLOW CLOUDFRONTS BLOG :


Secured By miniOrange