Saturday, November 28, 2020

MSCRM Email Plugins C# with and Without CRM Reference

 // Create a new activity party linked to a contact

Entity party1 = new Entity("activityparty"); party1["addressused"] = "some@email.com"; party1["partyid"] = new EntityReference("contact", contactId); // Create a new unresolved activity party Entity party2 = new Entity("activityparty"); party2["addressused"] = "unresolved@email.com"; // Create a new EntityCollection and add the 2 parties EntityCollection to = new EntityCollection(); to.Entities.Add(party1); to.Entities.Add(party2); // Create an email with the EntityCollection Entity email = new Entity("email"); email["subject"] = "Test Party Lists"; email["to"] = to; Guid _emailid = service.Create(email);

    if (_emailid != Guid.Empty)
    {
        SendEmailRequest sendEmailreq = new SendEmailRequest
        {
            EmailId = _emailid,
            TrackingToken = "",
            IssueSend = true
        };

        SendEmailResponse sendEmailresp = (SendEmailResponse)service.Execute(sendEmailreq);
    }

Monday, November 2, 2020

Mscrm Attachment with Seperate Folder

 string root = @"D:\Business";

                    // If directory does not exist, create it. 

                    if (!Directory.Exists(root))

                    {

                        Directory.CreateDirectory(root);

                    }


string FilePath = @"D:\Business\" + loopFetchIndApplications.Attributes["new_businessapplicationid"].ToString();

                                    // Create a sub directory

                                    if (!Directory.Exists(FilePath))

                                    {

                                        Directory.CreateDirectory(FilePath);

                                    }

                                    string getAttachments = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>

   <entity name='annotation'>

                                                     <attribute name='subject' />

                                                    <attribute name='notetext' />

                                                    <attribute name='filename' />

                                                    <attribute name='documentbody' />

                                                    <attribute name='mimetype' />

                                                    <attribute name='annotationid' />

    <order attribute='subject' descending='false' />

  </entity>

</fetch>";



                                    getAttachments = getAttachments.Replace("{replaceID}", loopfetchgetIndDocuments.Id.ToString());


                                    EntityCollection fetchAnnotations = service.RetrieveMultiple(new FetchExpression(getAttachments));


                                    foreach (var loopfetchAnnotations in fetchAnnotations.Entities)

                                    {

                                        if (loopfetchAnnotations.Attributes.Contains("documentbody"))

                                        {

                                            //Also check here, if file with the same name already exists, if not create one

                                            if (!String.IsNullOrWhiteSpace(loopfetchAnnotations.Attributes["documentbody"].ToString()) && !File.Exists(FilePath + "\\" + loopfetchAnnotations.Attributes["filename"].ToString()))

                                            {

                                                byte[] data = Convert.FromBase64String(loopfetchAnnotations.Attributes["documentbody"].ToString());

                                                File.WriteAllBytes(FilePath + "\\" + loopfetchAnnotations.Attributes["filename"].ToString(), data);

                                            }

                                        }

                                    }


                                }

Friday, October 16, 2020

Salesforce OAuth Connection without Username and Password using JWT and C#

Hi All,

Please find the code to Convert JWT to PCKS

keytool -importkeystore -srckeystore LocalfolderPath\FileName.jks -destkeystore LocalfolderPath\FileName.cer -srcstoretype JKS -deststoretype PKCS12 -deststorepass password


keytool -importkeystore -srckeystore LocalfolderPath\FileName.jks -destkeystore LocalfolderPath\FileName.p12 -srcstoretype JKS -deststoretype PKCS12 -srcstorepass password -deststorepass gridserve -srcalias Randomname2020 -destalias 1 -srckeypass password-destkeypass password–noprompt


LocalfolderPath\FileName.jks - JKS File
LocalfolderPath\FileName.cer - PKCS File(Certificate)
password - Password for JKS



static string ToBase64UrlString(byte[] input)
        {
            return Convert.ToBase64String(input).TrimEnd('=').Replace('+', '-').Replace('/', '_');
        }

        //Create Lead
        public static GetLeadResults createLead(string access_token)
        {
            var clientSend = new RestClient("https://orgName.salesforce.com/services/data/v49.0/sobjects/Lead");
            var requestSend = new RestRequest(Method.POST);
            requestSend.AddHeader("postman-token", "93331841-f3d2-de3e-dbcf-309a32fa1a7c");
            requestSend.AddHeader("cache-control", "no-cache");
            requestSend.AddHeader("content-type", "application/json");
            requestSend.AddHeader("authorization", "Bearer " + access_token);
            requestSend.AddParameter("application/json", "{ "FirstName": "Raghu"} ", ParameterType.RequestBody);
            IRestResponse responseSend = clientSend.Execute(requestSend);
            GetLeadResults getCreatedResults = JsonConvert.DeserializeObject<GetLeadResults>(responseSend.Content);
            return getCreatedResults;
        }

        public static GenerateToken GetAccessToken()
        {
            // certificate
            //X509Certificate2 certificate = new X509Certificate2(@"localpath\filename.pfx", "password", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);

            // header
            var header = new { alg = "RS256" };

            var claimset = new
            {
                iss = "client_id",
                sub = "Email",
                aud = "https://test.salesforce.com",
                exp = expiryDate,
            };
            var ser = new JavaScriptSerializer();

            // encoded header
            var headerSerialized = ser.Serialize(header);
            var headerBytes = Encoding.UTF8.GetBytes(headerSerialized);
            var headerEncoded = ToBase64UrlString(headerBytes);

            // encoded claimset
            var claimsetSerialized = ser.Serialize(claimset);
            var claimsetBytes = Encoding.UTF8.GetBytes(claimsetSerialized);
            var claimsetEncoded = ToBase64UrlString(claimsetBytes);

            // input
            var input = headerEncoded + "." + claimsetEncoded;
            var inputBytes = Encoding.UTF8.GetBytes(input);

            // signiture
            var rsa = certificate.PrivateKey as RSACryptoServiceProvider;
            var signingCredentials = new X509SigningCredentials(certificate, "RS256");
            var signature = JwtTokenUtilities.CreateEncodedSignature(input, signingCredentials);

            // jwt
            var jwt = headerEncoded + "." + claimsetEncoded + "." + signature;

            var client = new WebClient();
            client.Encoding = Encoding.UTF8;

            var content = new NameValueCollection();

            var clients = new RestClient("https://org.salesforce.com/services/oauth2/token");
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            var request = new RestRequest(Method.POST);
            request.AddHeader("cache-control", "no-cache");
            request.AddHeader("content-type", "application/x-www-form-urlencoded");
            //request.AddHeader("authorization", "client_id:3MVG9uAc45HBYUriJoqjtxJLD.1f.Vptl72m7pFWVLcdgslPKKdE8K31RrUqiqDS5y2bTvu99B.OcdhSaK9c9, " +
            //    "client_secret:79A8DC7B0586433932A6EB846C76C8920145DFE7AE0BE0B28ED076C5397F9ADC");
            request.AddHeader("authorization", "client_id:clientid,client_secret:clientSecret");
            request.AddParameter("application/x-www-form-urlencoded", "assertion=" + jwt +
                "&grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer", ParameterType.RequestBody);
            IRestResponse response = clients.Execute(request);

            GenerateToken customerDto = JsonConvert.DeserializeObject<GenerateToken>(response.Content);

            return customerDto;
        }

        public class GenerateToken
        {
            public string access_token { get; set; }
            public string scope { get; set; }
            public string instance_url { get; set; }
            public string token_type { get; set; }
            public string id { get; set; }
        }

        private static int GetExpiryDate()
        {
            var utc0 = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            var currentUtcTime = DateTime.UtcNow;

            var exp = (int)currentUtcTime.AddMinutes(4).Subtract(utc0).TotalSeconds;

            return exp;
        }

        public class GetLeadResults
        {
            public string id { get; set; }
            public string success { get; set; }
            public string[] errors { get; set; }
        }

Tuesday, September 29, 2020

MSCRM+ on premise plugin error + could not find default endpoint element that references contract

 Hi All,


If you get error with could not find default endpoint element that references contract


while trying in Plugins or Workflow Activity

Please use below code in your code


BasicHttpBinding myBinding = new BasicHttpBinding();

                myBinding.Name = "BasicHttpBinding_Service";

                myBinding.Security.Mode = BasicHttpSecurityMode.None;

                myBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;

                myBinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;

                myBinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;


                // Endpoint Address defining the asmx Service to be called.

                EndpointAddress endPointAddress = new EndpointAddress(@"http://yourwebservice.com/sms_ws/Service.asmx");


                // Call to the Web Service using the Binding and End Point Address.

                SendSMS.ServiceSoapClient myClient = new SendSMS.ServiceSoapClient(myBinding, endPointAddress);

Monday, September 21, 2020

HttpClient + GUID Create Record Mscrm C#

 HttpClient httpClient = GetHttp().Result;

            //var appSettings = ConfigurationManager.AppSettings;

            String apiUrl = "https://ORG.crm4.dynamics.com/api/data/v9.1/";

            JObject idea = new JObject();

  idea.Add("admin_BusinessPoint@odata.bind","/systemusers("+ getUserGuid.Result.ToString().Replace("}","").Replace("{","") + ")");


PASS CRM FIELD INSTED LOGICAL NAME

response.Content.ReadAsStringAsync().Result - retrieve values

Convert 


var retrievedcontact1 = response.Content.ReadAsStringAsync().Result;

                dynamic data = JObject.Parse(retrievedcontact1);

                RootObject objects = JsonConvert.DeserializeObject<RootObject>(response.Content.ReadAsStringAsync().Result);


public class Value

        {

            [JsonProperty("@odata.etag")]

            public string etag { get; set; }

            public string systemuserid { get; set; }

            public string ownerid { get; set; }

        }


        public class RootObject

        {

            [JsonProperty("@odata.context")]

            public string context { get; set; }

            public List<Value> value { get; set; }

        } 

Thursday, September 10, 2020

Trigger Workflow MSCRM c#

var executeWorkflowRequest = new ExecuteWorkflowRequest()  

{  

  WorkflowId = Guid.Parse(""), // Guid of workflow  

  EntityId = Guid.Parse("") // Guid of record  

};              

var executeWorkflowResponse =(ExecuteWorkflowResponse)orgService.Execute(executeWorkflowRequest); 

Day 11 - Customizing Option Sets Dropdown Fields with JavaScript

  In this Blog, we will see how to Customizing Option Sets Dropdown Fields with JavaScript label1 = formContext.getAttribute( "bosch_op...