My Photo

Microsoft Dynamics 365

Official Blog for Microsoft Dynamics Functional and Technical Solutions....

Dynamics CRM V9 / D365 Connection through Console without Prompt

There are 2 major steps involved in the process.
  • Register the application with your Azure subscription
  • Build the Console Application
Register the application with your Azure subscription

Build the Console Application 

You need to change only the below authentication method in step 3 rest remains same

Pass user credentials with service URL and client id in Authentication Context


string authority = "https://login.microsoftonline.com/68e86d2-65ed-4666-8ee-f8ce245d20de/oauth2/authorize";
AuthenticationContext authContext = new AuthenticationContext(authority, false);
var credentials = new UserCredential("shashank@s.onmicrosoft.com", "pas@wrd1");
//without prompt
AuthenticationResult authResult = authContext.AcquireToken(serviceUrl, clientId, credentials);
authHeader = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
You can have a look at my code here :Sample Code

Happy Coding and CRMing 😊


SOURCE : mscrm.com

Host free asp.net website on free server and domain (Host asp.net website on windows server for free No credit card required)

If you wanna test you website on public domain without purchasing an website hosting , you can register on below website : Click Here  (On Azure we get 30 days trail and it require credit card )


once registered Login and find you FTP details , you can also map you custom domain to the hosting.


You will get an free domain to view your asp.net website. Hope this was helpful. thanks

SOURCE : mscrm.com

Dynamics 365 V9 : New feature lookupObjects (Xrm.Utility.lookupObjects)

Opens a lookup control to select one or more items.
Microsoft dynamics 365 V9.0 has enhanced many existing features in CRM online and has also introduced new features. Xrm.Utility namespace has also been enhanced with new feature like
and LookupObjects.

Lets take an example creating new field in account "new_lookupfilter"  when write js on change of this field (if we enter 'admin' it will open an lookup dialog of contact entity and we can modify it i.e multi-select E.T.C )



Now  selected record can be set to any other field.

------------------------------------------------------------------------

function lookUpobjectTest() {
    // Set properties here
    var lookupOptions = {
        defaultEntityType: "contact",
        defaultViewId: "{608861bc-50a4-4c5f-a02c-21fe1943e2cf}", // GUID of the View
        viewIds: ["{00000000-0000-0000-0000-000000000000}",
                        "{00000000-0000-0000-0000-000000000000}",
                        "{00000000-0000-0000-0000-000000000000}"], // GUID of the View
        entityTypes: ["contact", "incident"],
        allowMultiSelect: true
    };
    Xrm.Utility.lookupObjects(lookupOptions);
}

-------------------------------------------------------------------------
Hope this was Helpful. Thanks

SOURCE : https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/clientapi/reference/xrm-utility/lookupobjects

Show Progress Indicator (Out of the box) Microsoft Dynamics 365 CRM V9

Yesterday used a nice feature progress indicator, before we use to write custom JS to show loading progress image but now we can use new JavaScript function of the Xrm.Utility namespace : showProgressIndicator.


  • showProgressIndicator
  • closeProgressIndicator

show progress indicator (loading image)

------------------------------------------------------------------------------------------------------

function setFaxNumber() {
    Xrm.Utility.showProgressIndicator("Loading contact Info..");
    setTimeout(setFaxNumberafterdelay, 3000);
}
function setFaxNumberAfterDelay() {
    var phoneNumber = Xrm.Page.getAttribute("telephone1").getValue();
    if (phoneNumber != null) {
        Xrm.Page.getAttribute("description").setValue(phoneNumber);
    }
    Xrm.Utility.closeProgressIndicator();

}

---------------------------------------------------------------------------------


Update and delete entities using the Web API Dynamics 365 V9

Follow link to "Retrieve multiple entity record using Web API " above step is required to understand the how to connect with Dynamics 365 using Web API.

for update we can use SendAsync

----------------------------------------------------------------------------------

JObject content= new JObject();
                    content.Add("statuscode", "100000000");
                    content.Add("statecode", "0");

                    content.Add("new_name","name");

 HttpRequestMessage updateRequest2 = new HttpRequestMessage(new HttpMethod("PATCH"),  "[Organization URL]api/data/v9.0/new_test(00000000-0000-0000-0000-000000000001)?$select=new_testid,statuscode,statecode,sab_name"  );
                        updateRequest2.Content = new StringContent(Content.ToString(),Encoding.UTF8, "application/json");
                        HttpResponseMessage updateResponse1 = httpClient.SendAsync(updateRequest2).Result;
                        if (updateResponse1.IsSuccessStatusCode)
                        {
                            //Get the response content  and parse it.
                           JObject body = new JObject();
                            body.Add("success", "true");
                            return body;
                        }
                        else
                        {
                            throw new Exception("error");

                        }

--------------------------------------------------------------------------------------

Hope this helped. thanks

SOURCE : mscrm.com

Retrieve multiple Entity record in Console/aspx website from Microsoft dynamics 365 V9 using Web API

Use link for "Connection to  Dynamics CRM / D365 WebApi v9 from Console Application C#"  . This step is needed to get Client ID after registering app in Azure.




Once connection is made you can use GetAsync to retrieve entities records using webapi query strings example : "[Organization URI] api/data/v9.0/new_test?$select=new_testid,new_amount,new_caseid,new_email&$filter=new_test eq '12'"

Find the sample code  below (Register app in azure and get clientId E.t.c Click Here )

---------------------------------------------------------------------------------
  public partial class test: System.Web.UI.Page
    {
        //TODO: Uncomment then substitute your correct Dynamics 365 organization service
        // address for either CRM Online or on-premise (end with a forward-slash).
        private static string serviceUrl = "https://sableadx.crm.dynamics.com/";;
        // CRM Online
        //private static string serviceUrl = "https://<organization name>.<domain name>/";   // CRM IFD
        //private static string serviceUrl = "http://myserver/myorg/";;        // CRM on-premises
        //TODO: For an on-premises deployment, set your organization credentials here. (If
        // online or IFD, you can you can disregard or set to null.)
        private static string userAccount = null;//"shashank@sablecafex.onmicrosoft.com";  //CRM user account
        private static string domain = null;//"crm8.dynamics.com";  //CRM server domain
        //TODO: For CRM Online or IFD deployments, substitute your app registration values 
        // here. (If on-premise, you can disregard or set to null.)
        //private static string clientId = "74b31987-2602-4e05-87d0-77339ac53096";//"992101fe-6c37-4fb2-b461-2f16505438f6";    //e.g. "e5cf0024-a66a-4f16-85ce-99ba97a24bb2"
        private static string clientId = "d933d1a6-5624-4f4f-b135-2a60d059c195";    //e.g. "74b31987-2602-4e05-87d0-77339ac53096";//"992101fe-6c37-4fb2-b461-2f16505438f6";
        private static string redirectUrl = "http://localhost"; //e.g. "http://localhost/SdkSample";

public static httpClient()
        {
            //One message handler for OAuth authentication, and the other for Windows integrated
            // authentication.  (Assumes that HTTPS protocol only used for CRM Online.)
            HttpMessageHandler messageHandler;
            if (serviceUrl.StartsWith("https://";))
            {
                messageHandler = new OAuthMessageHandler(serviceUrl, clientId, redirectUrl,
                         new HttpClientHandler());
            }
            else
            {
                //Prompt for user account password required for on-premise credentials.  (Better
                // approach is to use the SecureString class here.)
                Console.Write("Please enter the password for account {0}: ", userAccount);
                string password = Console.ReadLine().Trim();
                NetworkCredential credentials = new NetworkCredential(userAccount, password, domain);
                messageHandler = new HttpClientHandler() { Credentials = credentials };
            }
            try
            {
                //Create an HTTP client to send a request message to the CRM Web service.
                using (HttpClient httpClient = new HttpClient(messageHandler))
                {
                    //Specify the Web API address of the service and the period of time each request
                    // has to execute.
                    httpClient.BaseAddress = new Uri(serviceUrl);
                    httpClient.Timeout = new TimeSpan(0, 10, 0);  //2 minutes
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
                    //Send the WhoAmI request to the Web API using a GET request.
                   
                        var response = httpClient.GetAsync("[Organization URI] api/data/v9.0/new_test?$select=new_testid,new_amount,new_caseid,new_email&$filter=new_test eq '12'",
                            HttpCompletionOption.ResponseHeadersRead).Result;
                       
                        if (response.IsSuccessStatusCode)
                        {
                            //Body will contain JSON result
                            JObject body = JObject.Parse(response.Content.ReadAsStringAsync().Result);                           
                           
                        }
                        else
                        {
                            throw new Exception("error");
                        }
                                   
                }
            }
            catch (Exception ex)
            {
                DisplayException(ex);
                throw;
            }
          
        }
        /// <summary> Displays exception information to the console. </summary>
        /// <param name="ex">The exception to output</param>
        private static void DisplayException(Exception ex)
        {
           
            while (ex.InnerException != null)
            {
                throw new exception("\t* {0}", ex.InnerException.Message);
                ex = ex.InnerException;
            }
        }
    }
    /// <summary>
    ///Custom HTTP message handler that uses OAuth authentication thru ADAL.
    /// </summary>
    class OAuthMessageHandler : DelegatingHandler
    {
        private AuthenticationHeaderValue authHeader;
        public OAuthMessageHandler(string serviceUrl, string clientId, string redirectUrl,
                HttpMessageHandler innerHandler)
            : base(innerHandler)
        {
            // Obtain the Azure Active Directory Authentication Library (ADAL) authentication context.
            // AuthenticationParameters ap = AuthenticationParameters.CreateFromResourceUrlAsync(
            //new Uri(serviceUrl + "api/data/")).Result;
            //AuthenticationContext authContext = new AuthenticationContext(ap.Authority, false);
            //
            AuthenticationContext authContext = new AuthenticationContext(authority, false);
            //Note that an Azure AD access token has finite lifetime, default expiration is 60 minutes.
            // without prompt
            var credentials = new UserCredential("admin@org.onmicrosoft.com", "assword");
            AuthenticationResult authResult = authContext.AcquireToken(serviceUrl, clientId, credentials);
            //// with prompt
            //AuthenticationResult authResult = authContext.AcquireToken(serviceUrl, clientId, new Uri(redirectUrl), PromptBehavior.Always);
            //getting authority hedders from token
            authHeader = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
        }
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            request.Headers.Authorization = authHeader;
            return base.SendAsync(request, cancellationToken);
        }

}
--------------------------------------------
Hope this was helpfull. thanks

SOURCE : mscrm.com