示例#1
0
        public async Task Test()
        {
            using (var auth = new AuthenticationClient())
            {
                await auth.UsernamePasswordAsync("3MVG96_7YM2sI9wQEuGYr2dV41ANxFem_XLDBd5Dn8ixAvm8AslaHNoNMUFJI218vqYQDMdCAMFUg_zzFWQJE",
                                                 "7D4690EC731EF30143F64D3469AA907011256023ADC41241178B87CF899F02F4",
                                                 "*****@*****.**",
                                                 "!HalaMadrid@2019stfEr80kdHLR4Nu21RlXtECl");



                using (var forceClient = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion))
                {
                    var result = await forceClient.QueryAsync <PurchaseOrder>("SELECT Name FROM Purchase_Order__c");

                    var uploadResult = await forceClient.CreateAsync("Purchase_Order__c", new PurchaseOrder
                    {
                        Id   = "a062p00001rJSBLAA4",
                        Name = "UpsertTest"
                    });

                    var uploadBatchResult = await forceClient.CreateAsync("Purchase_Order__c", new CreateRequest
                    {
                        Records = new List <IAttributedObject> {
                            new PurchaseOrder
                            {
                                Name = DateTime.Now.Ticks.ToString()
                            },
                            new PurchaseOrder
                            {
                                Name = DateTime.Now.AddTicks(1).Ticks.ToString()
                            }
                        }
                    });


                    //{
                    //    new PurchaseOrder
                    //    {
                    //        Name = DateTime.Now.Ticks.ToString()
                    //    },
                    //    new PurchaseOrder
                    //    {
                    //        Name = DateTime.Now.AddTicks(1).Ticks.ToString()
                    //    }
                    //});
                }
            }
        }
示例#2
0
        public static void AddLinkToSalesforce(ForceClient forceClient, SharepointFile fileInfo, string url)
        {
            ImageLink__c linkToAdd = new ImageLink__c()
            {
                Name = fileInfo.FileName, Contact__c = fileInfo.ParentId, File_Name__c = fileInfo.FileName, URL__c = url
            };

            // Wait synchronously for the result
            // TODO: maybe offer async option in an overload
            Task <SuccessResponse> response = forceClient.CreateAsync("ImageLink__c", linkToAdd);

            response.Wait();
            SuccessResponse result = response.Result;

            if (result.Success)
            {
                Log("uploaded link successfully to salesforce:\n ID: " + result.Id + " \n filename: " + fileInfo.FileName + " \n ContactID: " + fileInfo.ParentId);
            }
            else
            {
                log.Error("Error inserting link: " + fileInfo.FileName + " for: " + fileInfo.ParentId);
                log.Error(result.Errors.ToString());
                //TODO maybe throw exception
            }
        }
示例#3
0
        public Class1()
        {
            var auth = new AuthenticationClient("v44.0");

            var account = new Account()
            {
                Name = "New Name", Description = "New Description"
            };

            var instanceUrl = auth.InstanceUrl;
            var accessToken = auth.AccessToken;
            var apiVersion  = auth.ApiVersion;

            var client     = new ForceClient(instanceUrl, accessToken, apiVersion);
            var bulkClient = new BulkForceClient(instanceUrl, accessToken, apiVersion);

            var id = await client.CreateAsync("Account", account);

            var accounts = await client.QueryAsync <Account>("SELECT id, name, description FROM Account");

            foreach (var account in accounts.records)
            {
                Console.WriteLine(account.Name);
            }
        }
示例#4
0
        /// <summary>
        /// Demonstrates creating an Apex class in a client's Salesforce instance.
        /// </summary>
        private async Task CreateWebhookClassAsync(WebhookModel webhookModel, ForceClient client)
        {
            // First check if a class with this name already exists
            var existingWebhookClass = await client.QueryAsync <ApexClass>("SELECT Id FROM ApexClass WHERE Name = 'ActionRelayWebhook'");

            // If the class does not exist
            if (!existingWebhookClass.Records.Any())
            {
                var classBody = GetApexCode("SalesforceIntegration.ApexTemplates.WebhookTemplate.txt");

                var apexClass = new ApexClass
                {
                    ApiVersion = _apiVersion.TrimStart('v'),
                    Body       = classBody,
                    Name       = "ActionRelayWebhook"
                };

                var success = await client.CreateAsync("ApexClass", apexClass);

                if (!success.Success)
                {
                    throw new HttpException((int)HttpStatusCode.InternalServerError, "Create Failed!");
                }
            }
        }
示例#5
0
        public async Task <string> InsertComment(string caseRecordId, string comment)
        {
            ForceClient client = await GetClient();

            dynamic caseComment = new ExpandoObject();

            caseComment.ParentId    = caseRecordId;
            caseComment.CommentBody = comment;
            return(await client.CreateAsync("CaseComment", caseComment));
        }
        /// <summary>
        /// Adding new opportunity details
        /// </summary>
        /// <param name="client">Force client instance</param>
        /// <param name="opportunity">Opportunity Details</param>
        /// <returns></returns>
        public async Task <SalesForceResponse> CreateOpportunity(ForceClient client, Opportunity opportunity)
        {
            var result = await client.CreateAsync(Constants.Opportunity, opportunity);

            return(new SalesForceResponse
            {
                IsSuccess = result.Success,
                Details = result.Success ? Constants.MsgOpportunityAddSuccess : Constants.MsgOpportunityAddFailed
            });
        }
        public async Task CreateLotsOfAccounts(ForceClient forceClient)
        {
            var account = new Account { Name = "Test Account", Description = "New Account Description" };

            for (var i = 0; i < 1000; i++)
            {
                account.Name = "Test Account (" + i + ")";
                await forceClient.CreateAsync("Account", account);
            }
        }
        public async Task <SalesForceModels.SalesForceResponseModel> CreateOpportunity(ForceClient client, SalesForceModels.OpportunityModel opportunity)
        {
            var result = await client.CreateAsync("Opportunity", opportunity);

            return(new SalesForceModels.SalesForceResponseModel
            {
                IsSuccess = result.Success,
                Details = result.Success ? "Opportunity successfully created." : "Problem while creating opportunity into SFDC.Please refresh the page and try again."
            });
        }
        protected async void booking_btn_Click(object sender, EventArgs e)
        {
            try
            {
                Random rnd = new Random();
                var userName = "******";
                var password = "******";
                var passwordSecurityToken = "<passwordSecurityToken>";
                var consumerKey = "consumerKey";
                var consumerSecret = "<consumerSecret>";
                var auth = new AuthenticationClient();

                await auth.UsernamePasswordAsync(consumerKey, consumerSecret, userName, password + passwordSecurityToken);

                var forceClient = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);
                
                Wallet wc = new Wallet { Bank__c = bankName.Value, Card_Type__c = cardType.Value, Credit_Card_Number__c = CardNo.Value };
                string x = await forceClient.CreateAsync("Wallet__c", wc);
                
                Rider__c rc = new Rider__c { Email_id__c = email.Value, Name__c = name.Value, Phone_number__c = contact.Value, Wallet__c = x };
                string x2 = await forceClient.CreateAsync("Rider__c", rc);
                
                Salesforce.Common.Models.QueryResult<Location__c> d1 = await forceClient.QueryAsync<Location__c>("SELECT Name,Id FROM Location__c WHERE Area_Name__c='" + dest.Value.Trim() + "'");
                Booking__c bc = new Booking__c { Destination__c = d1.Records[0].Id, Pick_Up__c = "a0728000000qCRg", pick_up_time__c = "2015-07-21T20:21:00Z", Rider__c = x2 };
                
                string x3 = await forceClient.CreateAsync("Booking__c", bc);
                Salesforce.Common.Models.QueryResult<Driver__c> d = await forceClient.QueryAsync<Driver__c>("SELECT Id,Address__c,Age__c,License_Number__c,Name__c,Phone__c,Status__c,Vehicle__c FROM Driver__c WHERE Status__c='For Hire'");
                d.Records[0].Status__c = "Hired";
                string ii = d.Records[0].Id;
                d.Records[0].Id = null;
                
                await forceClient.UpdateAsync("Driver__c", ii, d.Records[0]);

                Journey__c jc = new Journey__c { Distance_kms__c = rnd.Next(10, 100).ToString(), Rider_c = x2, Driver_c = ii };
                string x4 = await forceClient.CreateAsync("Journey__c", jc);
                
            }
            catch (Exception ex)
            {
                Response.Write("<script>alert(" + ex.Message + " - " + ex.InnerException + ")</script>");
            }
        }
        public async Task <SalesForceModels.SalesForceResponseModel> CreateLead(ForceClient client, SalesForceModels.LeadModel lead)
        {
            var result = await client.CreateAsync("Lead", lead);

            // by accessing result.Id you can obtain the unique SalesForce ID for the lead you just created
            return(new SalesForceModels.SalesForceResponseModel
            {
                IsSuccess = result.Success,
                Details = result.Success ? "Lead successfully created." : "Problem while creating lead into SFDC.Please refresh the page and try again."
            });
        }
示例#11
0
        public async Task CreateLotsOfAccounts(ForceClient forceClient)
        {
            var account = new Account {
                Name = "Test Account", Description = "New Account Description"
            };

            for (var i = 0; i < 1000; i++)
            {
                account.Name = "Test Account (" + i + ")";
                await forceClient.CreateAsync("Account", account);
            }
        }
示例#12
0
        public async Task <bool> InsertUpdateObject(object myObject, string objectName, string id)
        {
            SuccessResponse response = string.IsNullOrEmpty(id) ?
                                       await _client.CreateAsync(objectName, myObject) :
                                       await _client.UpdateAsync(objectName, id.ToString(), myObject);

            if (!response.Success)
            {
                _log.Error(response.Errors.ToString());
            }

            return(response.Success);
        }
示例#13
0
        public async Task<ActionResult> Create([Bind(Include = "CaseNumber, Type, Subject, Description")] CaseModel caseModel)
        {
            var accessToken = Session["AccessToken"].ToString();
            var apiVersion = Session["ApiVersion"].ToString();
            var instanceUrl = Session["InstanceUrl"].ToString();

            var client = new ForceClient(instanceUrl, accessToken, apiVersion);
            if (caseModel.Status == null && caseModel.Subject == null)
            {
                return View(caseModel);
            }
            await client.CreateAsync("Case", caseModel);
            return RedirectToAction("Index");
            
        }
示例#14
0
        public async Task <ActionResult> Create([Bind(Include = "CaseNumber, Type, Subject, Description")] CaseModel caseModel)
        {
            var accessToken = Session["AccessToken"].ToString();
            var apiVersion  = Session["ApiVersion"].ToString();
            var instanceUrl = Session["InstanceUrl"].ToString();

            var client = new ForceClient(instanceUrl, accessToken, apiVersion);

            if (caseModel.Status == null && caseModel.Subject == null)
            {
                return(View(caseModel));
            }
            await client.CreateAsync("Case", caseModel);

            return(RedirectToAction("Index"));
        }
        public async Task <bool> CreateSFObject <T>(T sfObject, string objectName, IConfiguration config)
        {
            var  securityToken  = config["SalesForceCredentials:SecurityToken"];
            var  consumerKey    = config["SalesForceCredentials:ConsumerKey"];
            var  consumerSecret = config["SalesForceCredentials:ConsumerSecret"];
            var  username       = config["SalesForceCredentials:Username"];
            var  password       = config["SalesForceCredentials:Password"];
            var  isSandboxUser  = config["SalesForceCredentials:IsSandboxUser"];
            var  url            = config["SalesForceCredentials:URL"];
            bool result         = false;

            try
            {
                var auth = new AuthenticationClient();

                // Authenticate with Salesforce
                await auth.UsernamePasswordAsync(consumerKey, consumerSecret, username, password + securityToken, url);

                var client = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);
                ////create a lead from our form values
                var response = await client.CreateAsync(objectName, sfObject);

                if (response.Id == null)
                {
                    Trace.TraceWarning("Failed to create " + objectName);
                }
                else
                {
                    result = true;
                    Trace.TraceInformation("Created " + objectName + "Successfully!!!");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                while (ex.InnerException != null)
                {
                    Trace.TraceInformation("Error While creating" + objectName);
                    Trace.TraceError(ex.Message + ex.InnerException);
                }
            }

            return(result);
        }
示例#16
0
        /// <summary>
        /// Demonstrates creating an Apex trigger in a client's Salesforce instance.
        /// </summary>
        private async Task CreateTriggerAsync(WebhookModel webhookModel, ForceClient client)
        {
            var triggerBody = GetApexCode("SalesforceIntegration.ApexTemplates.TriggerTemplate.txt", webhookModel);

            var apexTrigger = new ApexTrigger
            {
                ApiVersion    = _apiVersion.TrimStart('v'),
                Body          = triggerBody,
                Name          = "ActionRelayTrigger" + webhookModel.Name,
                TableEnumOrId = webhookModel.SObject
            };

            var success = await client.CreateAsync("ApexTrigger", apexTrigger);

            if (!success.Success)
            {
                throw new HttpException((int)HttpStatusCode.InternalServerError, "Create Failed!");
            }
        }
示例#17
0
        public IActionResult RequestFilePost()
        {
            var auth = new AuthenticationClient();

            auth.UsernamePasswordAsync(_configuration.GetValue <string>("SFConsumerKey"), _configuration.GetValue <string>("SFConsumerSecret"), _configuration.GetValue <string>("SFUserName"), _configuration.GetValue <string>("SFPassword")).Wait();

            var instanceUrl = auth.InstanceUrl;
            var accessToken = auth.AccessToken;
            var apiVersion  = auth.ApiVersion;

            var client = new ForceClient(instanceUrl, accessToken, apiVersion);

            string fileName = string.Empty;

            foreach (string key in Request.Form.Keys)
            {
                if (key != "__RequestVerificationToken")
                {
                    fileName = key;
                    break;
                }
            }

            if (!string.IsNullOrEmpty(fileName))
            {
                FileRequest fileRequest = new FileRequest()
                {
                    UserName__c = User.Identity.Name,
                    FileName__c = fileName,
                    Status__c   = "Processing"
                };
                var success = client.CreateAsync("FileRequest__c", fileRequest).Result;
                if (success.Success)
                {
                    fileRequest.Id = success.Id;
                }
            }

            return(RedirectToAction("RequestFile"));
        }
示例#18
0
        public async Task AsyncTaskCompletion_ExpandoObject()
        {
            dynamic account = new ExpandoObject();

            account.Name        = "ExpandoName" + DateTime.Now.Ticks;
            account.Description = "ExpandoDescription" + DateTime.Now.Ticks;

            var result = await _client.CreateAsync("Account", account);

            Assert.IsNotNull(result);
        }
示例#19
0
        public async Task <HttpResponseMessage> CreateLead(Lead odatas)
        {
            dynamic oLeadModels  = new LeadModels();
            dynamic Lead         = new ExpandoObject();
            var     leaCustom    = (from a in odatas.oLead select new { a }).FirstOrDefault();
            var     datasLeadobj = new JavaScriptSerializer().Serialize(leaCustom.a);
            JObject lead         = JObject.Parse(datasLeadobj);

            lead.Property("CustomFields").Remove();
            lead.Merge(leaCustom.a.CustomFields);
            Lead = lead;

            dynamic oCredential   = new SFCredential();
            dynamic Credential    = new ExpandoObject();
            var     CredCustom    = (from a in odatas.oCredential select new { a }).FirstOrDefault();
            var     Credentialobj = new JavaScriptSerializer().Serialize(CredCustom.a);
            JObject credential    = JObject.Parse(Credentialobj);

            Credential = credential;

            //Request Log
            dynamic oSalesforceModels = new LeadModels();
            dynamic Salesforce        = new ExpandoObject();
            JObject salesforce        = new JObject();

            salesforce.Add("Lead", Lead);
            salesforce.Add("Credential", Credential);
            Salesforce = salesforce;


            try
            {
                var    leadId     = string.Empty;
                var    campaignId = string.Empty;
                var    contactId  = string.Empty;
                var    Accountid  = string.Empty;
                string productId  = string.Empty;
                var    statuscode = string.Empty;

                #region Object Declarations



                #endregion
                ConfigurationModels oConfigurationmodels = new ConfigurationModels();
                oConfigurationmodels.ApplicationId = Credential.ApplicationId;
                var authResult = Configurations.Authentication(oConfigurationmodels);
                if (authResult != "Success")
                {
                    return(response = Request.CreateResponse(HttpStatusCode.Forbidden, authResult));
                }
                else
                {
                    var response11 = new HttpResponseMessage(HttpStatusCode.Unauthorized);
                    #region API details
                    //ConfigurationModels oConfigurationmodels = new ConfigurationModels();
                    //oConfigurationmodels.ApplicationId = Credential.ApplicationId;
                    var OCustomerId = Configurations.GetCustomerId(oConfigurationmodels);
                    oConfigurationmodels.CustomerId = Convert.ToInt32(OCustomerId[0].CustomerId);
                    var OConfigurationModels = Configurations.GetConfigurationDetails(oConfigurationmodels);
                    clientId           = OConfigurationModels[0].ConsumerId;
                    clientSecretKey    = OConfigurationModels[0].ConsumerSecretKey;
                    salesforceUserName = OConfigurationModels[0].SalesForceUserName;
                    salesforcePassword = OConfigurationModels[0].SalesForceUserPassword;
                    securityToken      = OConfigurationModels[0].SecurityToken;
                    SalesforceTokenURL = OConfigurationModels[0].SalesforceTokenURL;
                    CustomerID         = Convert.ToInt32(OConfigurationModels[0].CustomerId);
                    LeadSetting        = true;
                    CampaignSetting    = true;

                    //Request Log
                    int requestId = Errorlog.LogRequestToSF(CustomerID, Convert.ToString(Salesforce));

                    var auth = new AuthenticationClient();
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
                    await auth.UsernamePasswordAsync(clientId, clientSecretKey, salesforceUserName, salesforcePassword + securityToken, SalesforceTokenURL);

                    var forceClient = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);

                    //Errorlog.LogRequestToSF(CustomerID, request, orderId);
                    #endregion

                    #region Lead

                    if (LeadSetting)
                    {
                        var leadResult = await forceClient.QueryAsync <dynamic>("SELECT Id FROM Lead WHERE (FirstName='" + Lead.FirstName + "' and LastName='" + Lead.LastName + "' and Email='" + Lead.Email + "') and Status='Open - Not Contacted' and LeadSource = '" + Lead.LeadSource + "'");

                        if ((leadResult).TotalSize > 0)
                        {
                            leadId = (leadResult.Records[0].Id).Value;
                            var leadUpdateResult = await forceClient.UpdateAsync("Lead", leadId, Lead);

                            Errorlog.LogResponseToSF(CustomerID, string.Format(Thread.CurrentThread.CurrentCulture, Helper.Messages.LEAD_UPDATE, leadId), requestId, statuscode);
                            response = Request.CreateResponse(HttpStatusCode.Created, "Lead Updated Successfully");
                        }
                        else
                        {
                            leadResult = await forceClient.CreateAsync("Lead", Lead);

                            leadId = (leadResult.Id);
                            Errorlog.LogResponseToSF(CustomerID, string.Format(Thread.CurrentThread.CurrentCulture, Helper.Messages.LEAD_CREATE, leadId), requestId, statuscode);
                            response = Request.CreateResponse(HttpStatusCode.Created, "Lead Created Successfully");
                        }

                        if (CampaignSetting)
                        {
                            #region Campaign
                            // Get Campaign Id based on its Name
                            var campaignResult = await forceClient.QueryAsync <dynamic>("SELECT ID FROM Campaign WHERE Name = '" + Lead.LeadSource + "' ");

                            campaignId = (campaignResult.Records[0].Id).Value;

                            // Checks whether the Lead already associated with corresponding campagign.
                            var campaignMemberResult = await forceClient.QueryAsync <dynamic>("SELECT Id FROM CampaignMember WHERE CampaignId = '" + campaignId + "' AND LeadId = '" + leadId + "'");

                            if (campaignMemberResult.TotalSize <= 0)
                            {
                                // Lead campaign member association
                                dynamic campaignMember = new ExpandoObject();
                                campaignMember.LeadId     = leadId;
                                campaignMember.CampaignId = campaignId;
                                campaignMember.Status     = "Sent";
                                var campaignid = await forceClient.CreateAsync("CampaignMember", campaignMember);

                                Errorlog.LogResponseToSF(CustomerID, string.Format(Thread.CurrentThread.CurrentCulture, Helper.Messages.CAMPAING_CREATE, campaignId), requestId, statuscode);
                                response = Request.CreateResponse(HttpStatusCode.Created, "Lead and Campaign Created Successfully");
                            }
                            #endregion
                        }
                    }
                    #endregion
                    return(response);
                }
            }
            catch (Exception ex)
            {
                Email email = new Email();
                errorMessage = ex.Message.ToString();
                errorMessage = (errorMessage == "authentication failure") ? "Please Check your salesforce UserName ,Password , SecurityToken and SalesforceTokenURL" : (errorMessage == "invalid client credentials") ? "Please Check your salesforce clientId and clientSecretKey  " : errorMessage;
                Errorlog.ErrorDetail(CustomerID, orderId, "CreateLead", errorMessage, 1);
                email.SendMailForError("Salesforce Lead Creation Error", email.BodyService(Convert.ToString(Lead.FirstName + " " + Lead.LastName), Convert.ToString(Lead.Email), Convert.ToString(Credential.ApplicationId), ex.Message.ToString(), ex.StackTrace.ToString()));
                response = Request.CreateResponse(HttpStatusCode.InternalServerError, errorMessage);
                return(response);
            }
        }
        private static async Task RunSample()
        {
            var auth = new AuthenticationClient();

            // Authenticate with Salesforce
            Console.WriteLine("Authenticating with Salesforce");
            await auth.UsernamePasswordAsync(ConsumerKey, ConsumerSecret, Username, Password);
            Console.WriteLine("Connected to Salesforce");

            var client = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);

            // Create a sample record
            Console.WriteLine("Creating test record.");
            var account = new Account { Name = "Test Account" };
            account.Id = await client.CreateAsync(Account.SObjectTypeName, account);
            if (account.Id == null)
            {
                Console.WriteLine("Failed to create test record.");
                return;
            }

            Console.WriteLine("Successfully created test record.");

            // Update the sample record
            // Shows that annonymous types can be used as well
            Console.WriteLine("Updating test record.");
            var success = await client.UpdateAsync(Account.SObjectTypeName, account.Id, new { Name = "Test Update" });
            if (!success)
            {
                Console.WriteLine("Failed to update test record!");
                return;
            }

            Console.WriteLine("Successfully updated the record.");

            // Retrieve the sample record
            // How to retrieve a single record if the id is known
            Console.WriteLine("Retrieving the record by ID.");
            account = await client.QueryByIdAsync<Account>(Account.SObjectTypeName, account.Id);
            if (account == null)
            {
                Console.WriteLine("Failed to retrieve the record by ID!");
                return;
            }

            Console.WriteLine("Retrieved the record by ID.");

            // Query for record by name
            Console.WriteLine("Querying the record by name.");
            var accounts = await client.QueryAsync<Account>("SELECT ID, Name FROM Account WHERE Name = '" + account.Name + "'");
            account = accounts.FirstOrDefault();
            if (account == null)
            {
                Console.WriteLine("Failed to retrieve account by query!");
                return;
            }

            Console.WriteLine("Retrieved the record by name.");

            // Delete account
            Console.WriteLine("Deleting the record by ID.");
            success = await client.DeleteAsync(Account.SObjectTypeName, account.Id);
            if (!success)
            {
                Console.WriteLine("Failed to delete the record by ID!");
                return;
            }
            Console.WriteLine("Deleted the record by ID.");
        }
示例#21
0
        private static async Task RunSample()
        {
            var auth = new AuthenticationClient();

            // Authenticate with Salesforce
            Console.WriteLine("Authenticating with Salesforce");
            var url = IsSandboxUser.Equals("true", StringComparison.CurrentCultureIgnoreCase)
                ? "https://test.salesforce.com/services/oauth2/token"
                : "https://login.salesforce.com/services/oauth2/token";

            await auth.UsernamePasswordAsync(ConsumerKey, ConsumerSecret, Username, Password, url);        
            Console.WriteLine("Connected to Salesforce");

            var client = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);

            string sql = "SELECT Id, CaseNumber, Current_Version__c, Priority, Go_Live_Critical__c, Case.Account.name, " +
            "Case.Owner.name, Origin, Patch_Number__c, Subject, OwnerId, Type, Description, CreatedDate, " +
            "Case.createdBy.name, status, bzid__c, product__c, Customer__r.name, " +
            "( SELECT CommentBody, CaseComment.createdBy.name, CaseComment.lastModifiedBy.name, CreatedDate, LastModifiedDate FROM CaseComments ORDER BY CreatedDate DESC NULLS LAST LIMIT 1 ) " +
            "FROM Case WHERE Status ='Eng New' AND Case.product__c='Accela ACA' AND Case.Owner.name='Engineering'";

            //const string qry = "SELECT ID, Name FROM Account";
            var accts = new List<Account>();
            var results = await client.QueryAsync<Account>(sql);
            var totalSize = results.TotalSize;

            Console.WriteLine("Queried " + totalSize + " records.");

            accts.AddRange(results.Records);
            var nextRecordsUrl = results.NextRecordsUrl;

            if (!string.IsNullOrEmpty(nextRecordsUrl))
            {
                Console.WriteLine("Found nextRecordsUrl.");

                while (true)
                {
                    var continuationResults = await client.QueryContinuationAsync<Account>(nextRecordsUrl);
                    totalSize = continuationResults.TotalSize;
                    Console.WriteLine("Queried an additional " + totalSize + " records.");

                    accts.AddRange(continuationResults.Records);
                    if (string.IsNullOrEmpty(continuationResults.NextRecordsUrl)) break;

                    //pass nextRecordsUrl back to client.QueryAsync to request next set of records
                    nextRecordsUrl = continuationResults.NextRecordsUrl;
                }
            }
            Console.WriteLine("Retrieved accounts = " + accts.Count() + ", expected size = " + totalSize);

            // Create a sample record
            Console.WriteLine("Creating test record.");
            var account = new Account { Name = "Test Account" };
            account.Id = await client.CreateAsync(Account.SObjectTypeName, account);
            if (account.Id == null)
            {
                Console.WriteLine("Failed to create test record.");
                return;
            }

            Console.WriteLine("Successfully created test record.");

            // Update the sample record
            // Shows that annonymous types can be used as well
            Console.WriteLine("Updating test record.");
            var success = await client.UpdateAsync(Account.SObjectTypeName, account.Id, new { Name = "Test Update" });
            if (!string.IsNullOrEmpty(success.Errors.ToString()))
            {
                Console.WriteLine("Failed to update test record!");
                return;
            }

            Console.WriteLine("Successfully updated the record.");

            // Retrieve the sample record
            // How to retrieve a single record if the id is known
            Console.WriteLine("Retrieving the record by ID.");
            account = await client.QueryByIdAsync<Account>(Account.SObjectTypeName, account.Id);
            if (account == null)
            {
                Console.WriteLine("Failed to retrieve the record by ID!");
                return;
            }

            Console.WriteLine("Retrieved the record by ID.");

            // Query for record by name
            Console.WriteLine("Querying the record by name.");
            var accounts = await client.QueryAsync<Account>("SELECT ID, Name FROM Account WHERE Name = '" + account.Name + "'");
            account = accounts.Records.FirstOrDefault();
            if (account == null)
            {
                Console.WriteLine("Failed to retrieve account by query!");
                return;
            }

            Console.WriteLine("Retrieved the record by name.");

            // Delete account
            Console.WriteLine("Deleting the record by ID.");
            var deleted = await client.DeleteAsync(Account.SObjectTypeName, account.Id);
            if (!deleted)
            {
                Console.WriteLine("Failed to delete the record by ID!");
                return;
            }
            Console.WriteLine("Deleted the record by ID.");

            // Selecting multiple accounts into a dynamic
            Console.WriteLine("Querying multiple records.");
            var dynamicAccounts = await client.QueryAsync<dynamic>("SELECT ID, Name FROM Account LIMIT 10");
            foreach (dynamic acct in dynamicAccounts.Records)
            {
                Console.WriteLine("Account - " + acct.Name);
            }

            // Creating parent - child records using a Dynamic
            Console.WriteLine("Creating a parent record (Account)");
            dynamic a = new ExpandoObject();
            a.Name = "Account from .Net Toolkit";
            a.Id = await client.CreateAsync("Account", a);
            if (a.Id == null)
            {
                Console.WriteLine("Failed to create parent record.");
                return;
            }

            Console.WriteLine("Creating a child record (Contact)");
            dynamic c = new ExpandoObject();
            c.FirstName = "Joe";
            c.LastName = "Blow";
            c.AccountId = a.Id;
            c.Id = await client.CreateAsync("Contact", c);
            if (c.Id == null)
            {
                Console.WriteLine("Failed to create child record.");
                return;
            }

            Console.WriteLine("Deleting parent and child");

            // Delete account (also deletes contact)
            Console.WriteLine("Deleting the Account by Id.");
            deleted = await client.DeleteAsync(Account.SObjectTypeName, a.Id);
            if (!deleted)
            {
                Console.WriteLine("Failed to delete the record by ID!");
                return;
            }
            Console.WriteLine("Deleted the Account and Contact.");

        }
        private static async Task RunSample()
        {
            var auth = new AuthenticationClient();

            // Authenticate with Salesforce
            Console.WriteLine("Authenticating with Salesforce");
            var url = IsSandboxUser.Equals("true", StringComparison.CurrentCultureIgnoreCase)
                ? "https://test.salesforce.com/services/oauth2/token"
                : "https://login.salesforce.com/services/oauth2/token";

            await auth.UsernamePasswordAsync(ConsumerKey, ConsumerSecret, Username, Password, url);
            Console.WriteLine("Connected to Salesforce");

            var client = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);

            // retrieve all accounts
            Console.WriteLine("Get Accounts");

            const string qry = "SELECT ID, Name FROM Account";
            var accts = new List<Account>();
            var results = await client.QueryAsync<Account>(qry);
            var totalSize = results.TotalSize;

            Console.WriteLine("Queried " + totalSize + " records.");

            accts.AddRange(results.Records);
            var nextRecordsUrl = results.NextRecordsUrl;

            if (!string.IsNullOrEmpty(nextRecordsUrl))
            {
                Console.WriteLine("Found nextRecordsUrl.");

                while (true)
                {
                    var continuationResults = await client.QueryContinuationAsync<Account>(nextRecordsUrl);
                    totalSize = continuationResults.TotalSize;
                    Console.WriteLine("Queried an additional " + totalSize + " records.");

                    accts.AddRange(continuationResults.Records);
                    if (string.IsNullOrEmpty(continuationResults.NextRecordsUrl)) break;

                    //pass nextRecordsUrl back to client.QueryAsync to request next set of records
                    nextRecordsUrl = continuationResults.NextRecordsUrl;
                }
            }
            Console.WriteLine("Retrieved accounts = " + accts.Count() + ", expected size = " + totalSize);

            // Create a sample record
            Console.WriteLine("Creating test record.");
            var account = new Account { Name = "Test Account" };
            var response = await client.CreateAsync(Account.SObjectTypeName, account);
            if (!string.Equals(response.Success, "true", StringComparison.OrdinalIgnoreCase))
            {
                Console.WriteLine("Failed to create test record.");
                return;
            }

            Console.WriteLine("Successfully created test record.");

            // Update the sample record
            // Shows that annonymous types can be used as well
            Console.WriteLine("Updating test record.");
            var success = await client.UpdateAsync(Account.SObjectTypeName, account.Id, new { Name = "Test Update" });
            if (!string.IsNullOrEmpty(success.Errors.ToString()))
            {
                Console.WriteLine("Failed to update test record!");
                return;
            }

            Console.WriteLine("Successfully updated the record.");

            // Retrieve the sample record
            // How to retrieve a single record if the id is known
            Console.WriteLine("Retrieving the record by ID.");
            account = await client.QueryByIdAsync<Account>(Account.SObjectTypeName, account.Id);
            if (account == null)
            {
                Console.WriteLine("Failed to retrieve the record by ID!");
                return;
            }

            Console.WriteLine("Retrieved the record by ID.");

            // Query for record by name
            Console.WriteLine("Querying the record by name.");
            var accounts = await client.QueryAsync<Account>("SELECT ID, Name FROM Account WHERE Name = '" + account.Name + "'");
            account = accounts.Records.FirstOrDefault();
            if (account == null)
            {
                Console.WriteLine("Failed to retrieve account by query!");
                return;
            }

            Console.WriteLine("Retrieved the record by name.");

            // Delete account
            Console.WriteLine("Deleting the record by ID.");
            var deleted = await client.DeleteAsync(Account.SObjectTypeName, account.Id);
            if (!deleted)
            {
                Console.WriteLine("Failed to delete the record by ID!");
                return;
            }
            Console.WriteLine("Deleted the record by ID.");

            // Selecting multiple accounts into a dynamic
            Console.WriteLine("Querying multiple records.");
            var dynamicAccounts = await client.QueryAsync<dynamic>("SELECT ID, Name FROM Account LIMIT 10");
            foreach (dynamic acct in dynamicAccounts.Records)
            {
                Console.WriteLine("Account - " + acct.Name);
            }

            // Creating parent - child records using a Dynamic
            Console.WriteLine("Creating a parent record (Account)");
            dynamic a = new ExpandoObject();
            a.Name = "Account from .Net Toolkit";
            a.Id = await client.CreateAsync("Account", a);
            if (a.Id == null)
            {
                Console.WriteLine("Failed to create parent record.");
                return;
            }

            Console.WriteLine("Creating a child record (Contact)");
            dynamic c = new ExpandoObject();
            c.FirstName = "Joe";
            c.LastName = "Blow";
            c.AccountId = a.Id;
            c.Id = await client.CreateAsync("Contact", c);
            if (c.Id == null)
            {
                Console.WriteLine("Failed to create child record.");
                return;
            }

            Console.WriteLine("Deleting parent and child");

            // Delete account (also deletes contact)
            Console.WriteLine("Deleting the Account by Id.");
            deleted = await client.DeleteAsync(Account.SObjectTypeName, a.Id);
            if (!deleted)
            {
                Console.WriteLine("Failed to delete the record by ID!");
                return;
            }
            Console.WriteLine("Deleted the Account and Contact.");

        }
        public async void Create_Account_Typed()
        {
            var account = new Account {
                Name = "New Account", Description = "New Account Description"
            };
            var id = await _client.CreateAsync("Account", account);

            Assert.IsNotNullOrEmpty(id);
        }
示例#24
0
        public async Task <HttpResponseMessage> SalesforceSync(datas odatas)
        {
            dynamic oLeadModels  = new LeadModels();
            dynamic Lead         = new ExpandoObject();
            var     leaCustom    = (from a in odatas.oLead select new { a }).FirstOrDefault();
            var     datasLeadobj = new JavaScriptSerializer().Serialize(leaCustom.a);
            JObject lead         = JObject.Parse(datasLeadobj);

            lead.Property("CustomFields").Remove();
            lead.Merge(leaCustom.a.CustomFields);
            Lead = lead;

            dynamic Account     = new ExpandoObject();
            var     accCustom   = (from a in odatas.oAccount select new { a }).FirstOrDefault();
            var     datasAccobj = new JavaScriptSerializer().Serialize(accCustom.a);
            JObject account     = JObject.Parse(datasAccobj);

            account.Property("CustomFields").Remove();
            account.Merge(accCustom.a.CustomFields);
            Account = account;

            dynamic Contact      = new ExpandoObject();
            var     cont         = (from a in odatas.oContacts select new { a }).FirstOrDefault();
            var     datasContobj = new JavaScriptSerializer().Serialize(cont.a);
            JObject contacts     = JObject.Parse(datasContobj);

            contacts.Property("CustomFields").Remove();
            contacts.Merge(cont.a.CustomFields);
            Contact = contacts;

            dynamic Opportunity = new ExpandoObject();
            var     opp         = (from a in odatas.oOpportunity select new { a }).FirstOrDefault();
            var     datasOppobj = new JavaScriptSerializer().Serialize(opp.a);
            JObject opporunity  = JObject.Parse(datasOppobj);

            opporunity.Property("CustomFields").Remove();
            opporunity.Merge(opp.a.CustomFields);
            Opportunity = opporunity;

            dynamic CartItems    = new ExpandoObject();
            var     cart         = (from a in odatas.oCartItems select new { a }).FirstOrDefault();
            var     datasCartobj = new JavaScriptSerializer().Serialize(cart.a);
            JObject CartItem     = JObject.Parse(datasCartobj);

            CartItems = CartItem;

            dynamic ProductItems    = new ExpandoObject();
            var     productItem     = (from a in odatas.oShipping select new { a }).FirstOrDefault();
            var     datasProductobj = new JavaScriptSerializer().Serialize(productItem.a);
            JObject ProductItem     = JObject.Parse(datasProductobj);

            ProductItems = ProductItem;

            dynamic DiscountItems    = new ExpandoObject();
            var     discountItem     = (from a in odatas.oDiscount select new { a }).FirstOrDefault();
            var     datasDiscountobj = new JavaScriptSerializer().Serialize(discountItem.a);
            JObject DiscountItem     = JObject.Parse(datasDiscountobj);

            DiscountItems = DiscountItem;

            dynamic oCredential   = new SFCredential();
            dynamic Credential    = new ExpandoObject();
            var     CredCustom    = (from a in odatas.oCredential select new { a }).FirstOrDefault();
            var     Credentialobj = new JavaScriptSerializer().Serialize(CredCustom.a);
            JObject credential    = JObject.Parse(Credentialobj);

            Credential = credential;

            //Request Log
            dynamic oSalesforceModels = new LeadModels();
            dynamic Salesforce        = new ExpandoObject();
            JObject salesforce        = new JObject();

            salesforce.Add("Lead", Lead);
            salesforce.Add("Account", Account);
            salesforce.Add("Contact", Contact);
            salesforce.Add("Opportunity", Opportunity);
            salesforce.Add("CartItems", CartItems);
            salesforce.Add("ProductItems", ProductItems);
            salesforce.Add("DiscountItems", DiscountItems);
            salesforce.Add("Credential", Credential);
            Salesforce = salesforce;


            try
            {
                var    LeadId           = string.Empty;
                var    campaignId       = string.Empty;
                var    contactId        = string.Empty;
                var    Accountid        = string.Empty;
                string productId        = string.Empty;
                var    pricebookID      = string.Empty;
                var    accountIds       = string.Empty;
                var    products         = string.Empty;
                var    Shippingproducts = string.Empty;
                var    opportunityId    = string.Empty;
                var    statuscode       = string.Empty;

                #region Object Declaration

                #endregion
                ConfigurationModels oConfigurationmodels = new ConfigurationModels();
                oConfigurationmodels.ApplicationId = Credential.ApplicationId;
                var authResult = Configurations.Authentication(oConfigurationmodels);
                if (authResult != "Success")
                {
                    return(response = Request.CreateResponse(HttpStatusCode.Forbidden, authResult));
                }
                else
                {
                    orderId = Convert.ToString(Opportunity.Order_Number__c);
                    string request = Convert.ToString(((dynamic)(odatas)));

                    var OCustomerId = Configurations.GetCustomerId(oConfigurationmodels);
                    oConfigurationmodels.CustomerId = Convert.ToInt32(OCustomerId[0].CustomerId);

                    var OConfigurationModels = Configurations.GetConfigurationDetails(oConfigurationmodels);
                    clientId           = OConfigurationModels[0].ConsumerId;
                    clientSecretKey    = OConfigurationModels[0].ConsumerSecretKey;
                    salesforceUserName = OConfigurationModels[0].SalesForceUserName;
                    salesforcePassword = OConfigurationModels[0].SalesForceUserPassword;
                    securityToken      = OConfigurationModels[0].SecurityToken;
                    SalesforceTokenURL = OConfigurationModels[0].SalesforceTokenURL;
                    CustomerID         = Convert.ToInt32(OConfigurationModels[0].CustomerId);

                    //Request Log
                    int requestId = Errorlog.LogRequestToSF(CustomerID, Convert.ToString(Salesforce));

                    var auth = new AuthenticationClient();
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
                    await auth.UsernamePasswordAsync(clientId, clientSecretKey, salesforceUserName, salesforcePassword + securityToken, SalesforceTokenURL);

                    var forceClient = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);
                    //Errorlog.LogRequestToSF(CustomerID, request, orderId);


                    #region Lead Conversion
                    //Get contact details based on First Name, Last Name, Email and Parent Account
                    var contact = await forceClient.QueryAsync <dynamic>("SELECT Id,AccountId  FROM Contact WHERE Firstname= '" + Lead.FirstName + "' AND LastName = '" + Lead.LastName + "' AND Email='" + Lead.Email + "' ");

                    //Get lead details based on First Name, Last Name, Email, Status and Lead Source
                    var leadDetail = await forceClient.QueryAsync <dynamic>("SELECT Id,Company FROM Lead WHERE ( LastName='" + Lead.LastName + "' and Email='" + Lead.Email + "') and Status='Open - Not Contacted' ");

                    //var priceBook2Iddetail = await forceClient.QueryAsync<dynamic>("SELECT Id FROM Pricebook2 WHERE IsActive = false AND IsStandard = true ");
                    priceBook2Id = CartItems.PriceBook2Id;
                    //priceBook2Id = (priceBook2Iddetail.Records[0].Id).Value;


                    if (leadDetail.TotalSize > 0)
                    {
                        Lead.FirstName = Lead.FirstName;
                        Lead.LastName  = Lead.LastName;
                        LeadId         = (leadDetail.Records[0].Id).Value;
                        var success = await forceClient.UpdateAsync("Lead", LeadId, Lead);
                    }

                    #endregion

                    #region Account
                    // Creating Account in Salesforce
                    Account.ParentId = CartItems.ParentAccountID;
                    if (contact.TotalSize > 0)
                    {
                        var Accountids    = (contact.Records[0].AccountId).Value;
                        var accountResult = await forceClient.UpdateAsync("Account", Accountids, Account);

                        Accountid = Accountids;
                        Errorlog.LogResponseToSF(CustomerID, string.Format(Thread.CurrentThread.CurrentCulture, Helper.Messages.ACCOUNT_UPDATE, Accountid), requestId, statuscode);
                        response = Request.CreateResponse(HttpStatusCode.Created, "Account Updated");
                    }
                    else
                    {
                        var accountIdResult = await forceClient.CreateAsync("Account", Account);

                        Accountid = (accountIdResult.Id);
                        Errorlog.LogResponseToSF(CustomerID, string.Format(Thread.CurrentThread.CurrentCulture, Helper.Messages.ACCOUNT_CREATE, Accountid), requestId, statuscode);
                        response = Request.CreateResponse(HttpStatusCode.Created, "Account Created");
                    }
                    #endregion

                    #region Contact
                    var contactDetail = await forceClient.QueryAsync <dynamic>("SELECT Id from Contact WHERE AccountId='" + Accountid + "'");

                    if (contactDetail.TotalSize > 0)
                    {
                        //Update Contact
                        var contactIdValue = (contactDetail.Records[0].Id).Value;
                        contactId = contactIdValue;
                        await forceClient.UpdateAsync("Contact", contactId, Contact);

                        Errorlog.LogResponseToSF(CustomerID, string.Format(Thread.CurrentThread.CurrentCulture, Helper.Messages.CONTACT_UPDATE, contactId), requestId, statuscode);
                        response = Request.CreateResponse(HttpStatusCode.Created, "Contact and Account Updated");
                    }
                    else
                    {
                        //Create Contact
                        Contact.AccountId = Accountid;
                        var contactIds = await forceClient.CreateAsync("Contact", Contact);

                        contactId = (contactIds.Id);
                        Errorlog.LogResponseToSF(CustomerID, string.Format(Thread.CurrentThread.CurrentCulture, Helper.Messages.CONTACT_CREATE, contactId), requestId, statuscode);
                        response = Request.CreateResponse(HttpStatusCode.Created, "Contact and Account Created");
                    }
                    #endregion

                    #region Opportunity

                    Opportunity.AccountId = Accountid;
                    var OpportunityId = await forceClient.CreateAsync("Opportunity", Opportunity);

                    opportunityId = (OpportunityId.Id);
                    Errorlog.LogResponseToSF(CustomerID, string.Format(Thread.CurrentThread.CurrentCulture, Helper.Messages.OPPORTUNITY_CREATE, opportunityId), requestId, statuscode);
                    response = Request.CreateResponse(HttpStatusCode.Created, "Opportunity, Contact and Account Created Successfully");

                    #endregion

                    #region Opportunitycontactrole
                    // Inserting Opportunitycontactrole
                    dynamic OpportunityContactRole = new ExpandoObject();
                    {
                        OpportunityContactRole.ContactId     = contactId;
                        OpportunityContactRole.OpportunityId = (OpportunityId.Id);
                        OpportunityContactRole.Role          = "Business User";
                    }
                    var ContactRole = await forceClient.CreateAsync("OpportunityContactRole", OpportunityContactRole);

                    #endregion

                    #region kitproduct details for opportunity line item
                    List <CartItems> cartItem = new List <CartItems>();

                    foreach (var cartItems in ((dynamic)(odatas)).oCartItems)
                    {
                        string sku         = cartItems.sku;
                        string description = "Product";
                        if (sku.Substring(sku.Length - 1).Equals("-"))
                        {
                            sku = sku.Substring(0, sku.Length - 1);
                        }

                        // Get the pricebookentryid
                        double totalprice = Convert.ToDouble(cartItems.price * cartItems.quantity);

                        var productDetails = await forceClient.QueryAsync <dynamic>("SELECT ID FROM PricebookEntry WHERE ProductCode ='" + sku + "'AND PRICEBOOK2ID='" + priceBook2Id + "'");

                        if (productDetails.TotalSize == 0)
                        {
                            // Create a new product
                            dynamic Product2 = new ExpandoObject();
                            Product2.Name        = cartItems.productName;
                            Product2.ProductCode = sku;
                            Product2.IsActive    = true;
                            var product = await forceClient.QueryAsync <dynamic>("SELECT Id FROM Product2 WHERE ProductCode ='" + sku + "'");

                            if (product.TotalSize > 0)
                            {
                                var ProductID = (product.Records[0].Id).Value;
                                productId = ProductID;
                                await forceClient.UpdateAsync("Product2", productId, Product2);
                            }
                            else
                            {
                                var productsId = await forceClient.CreateAsync("Product2", Product2);

                                productId = productsId.Id;
                            }


                            // Create a pricebook entry for standard pricebook
                            dynamic PricebookEntry = new ExpandoObject();
                            PricebookEntry.Pricebook2Id     = priceBook2Id;
                            PricebookEntry.Product2Id       = productId;
                            PricebookEntry.IsActive         = true;
                            PricebookEntry.UnitPrice        = cartItems.price;
                            PricebookEntry.UseStandardPrice = false;
                            var pricebookid = await forceClient.CreateAsync("PricebookEntry", PricebookEntry);

                            pricebookID = pricebookid.Id;
                            Errorlog.LogRequestToSF(CustomerID, " productId '" + productId + "'Created Sucessfully");
                        }


                        //pricebookID = (productDetails.Records[0].Id);
                        string  PricebookEntryId    = !string.IsNullOrEmpty(pricebookID) ? pricebookID : (productDetails.Records[0].Id);
                        dynamic opportunitylineItem = new ExpandoObject();
                        //Assign values to opportunity line item
                        opportunitylineItem.OpportunityId    = (OpportunityId.Id);
                        opportunitylineItem.PricebookEntryId = PricebookEntryId;
                        opportunitylineItem.TotalPrice       = Convert.ToDouble(totalprice);
                        opportunitylineItem.Description      = description;

                        if (cartItems.isAKit == true)
                        {
                            long kitCount = cartItems.kitCount;

                            kitCount++;
                            {
                                opportunitylineItem.Quantity = kitCount * cartItems.quantity;
                                var OpportunityLineItemResult = await forceClient.CreateAsync("OpportunityLineItem", opportunitylineItem); //Insert Opportunity line item
                            }
                        }
                        else
                        {
                            opportunitylineItem.Quantity = cartItems.quantity;
                            var OpportunityLineItemResult = await forceClient.CreateAsync("OpportunityLineItem", opportunitylineItem); //Update Opportunity line item
                        }
                    }
                    //FedEx Shipping Line Item
                    shipMethod = ProductItems.SalesforceShippingMethod;
                    //shipMethod = "Test Shiping Method";
                    if (!string.IsNullOrEmpty(shipMethod) && Opportunity.ShippingTotal__c != 0)
                    {
                        pricebookID = "";
                        productId   = "";
                        var priceBookDetail = await forceClient.QueryAsync <dynamic>("SELECT ID FROM PricebookEntry WHERE NAME ='" + shipMethod + "'AND PRICEBOOK2ID='" + priceBook2Id + "'");

                        if (priceBookDetail.TotalSize == 0)
                        {
                            // Create a new product
                            dynamic Product2 = new ExpandoObject();
                            Product2.Name = shipMethod;
                            var Shippingproduct = await forceClient.QueryAsync <dynamic>("SELECT Id FROM Product2 WHERE Name ='" + shipMethod + "'");

                            if (Shippingproduct.TotalSize > 0)
                            {
                                var ProductID = (Shippingproduct.Records[0].Id).Value;
                                productId = ProductID;
                                await forceClient.UpdateAsync("Product2", productId, Product2);
                            }
                            else
                            {
                                var productsId = await forceClient.CreateAsync("Product2", Product2);

                                productId = productsId.Id;
                            }
                            Errorlog.LogRequestToSF(CustomerID, " productId '" + productId + "'Created Sucessfully");
                            // Create a pricebook entry for standard pricebook
                            dynamic PricebookEntry = new ExpandoObject();
                            PricebookEntry.Pricebook2Id     = priceBook2Id;
                            PricebookEntry.Product2Id       = productId;
                            PricebookEntry.IsActive         = true;
                            PricebookEntry.UnitPrice        = Convert.ToDouble(Opportunity.ShippingTotal__c);
                            PricebookEntry.UseStandardPrice = false;
                            var pricebookid = await forceClient.CreateAsync("PricebookEntry", PricebookEntry);

                            pricebookID = pricebookid.Id;
                        }

                        dynamic OpportunityLineItem = new ExpandoObject();
                        OpportunityLineItem.OpportunityId    = (OpportunityId.Id);
                        OpportunityLineItem.PricebookEntryId = !string.IsNullOrEmpty(pricebookID) ? pricebookID : (priceBookDetail.Records[0].Id);
                        OpportunityLineItem.Description      = "Shipping Product";
                        OpportunityLineItem.Quantity         = 1.0;
                        OpportunityLineItem.TotalPrice       = Convert.ToDouble(Opportunity.ShippingTotal__c);
                        var OpportunityLineItemResult = await forceClient.CreateAsync("OpportunityLineItem", OpportunityLineItem);
                    }
                    //Discount Line item

                    if (DiscountItems.orderCount < 0)
                    {
                        pricebookID = "";
                        productId   = "";
                        //var priceBook2IdDiscount = await forceClient.QueryAsync<dynamic>("SELECT Id FROM Pricebook2 WHERE IsActive = false AND IsStandard = true ");
                        var priceBook2IdDiscount = await forceClient.QueryAsync <dynamic>("SELECT ID FROM PricebookEntry WHERE NAME ='Discount Amount' AND PRICEBOOK2ID='" + priceBook2Id + "'");

                        if (priceBook2IdDiscount.TotalSize == 0)
                        {
                            // Create a new product
                            dynamic Product2 = new ExpandoObject();
                            Product2.Name = "Discount Amount";
                            var Discountproduct = await forceClient.QueryAsync <dynamic>("SELECT Id FROM Product2 WHERE Name = ' Discount Amount ' ");

                            if (Discountproduct.TotalSize > 0)
                            {
                                var DiscountID = (Discountproduct.Records[0].Id).Value;
                                productId = DiscountID;
                                await forceClient.UpdateAsync("Product2", productId, Product2);
                            }
                            else
                            {
                                var productsId = await forceClient.CreateAsync("Product2", Product2);

                                productId = productsId.Id;
                            }
                            Errorlog.LogRequestToSF(CustomerID, " productId '" + productId + "'Created Sucessfully");
                            // Create a pricebook entry for standard pricebook
                            dynamic PricebookEntry = new ExpandoObject();
                            PricebookEntry.Pricebook2Id     = priceBook2Id;
                            PricebookEntry.Product2Id       = productId;
                            PricebookEntry.IsActive         = true;
                            PricebookEntry.UnitPrice        = DiscountItems.orderCount;
                            PricebookEntry.UseStandardPrice = false;
                            var pricebookid = await forceClient.CreateAsync("PricebookEntry", PricebookEntry);

                            pricebookID = pricebookid.Id;
                        }

                        dynamic OpportunityLineItem = new ExpandoObject();
                        OpportunityLineItem.OpportunityId    = (OpportunityId.Id);
                        OpportunityLineItem.PricebookEntryId = !string.IsNullOrEmpty(pricebookID) ? pricebookID : (priceBook2IdDiscount.Records[0].Id);
                        //OpportunityLineItem.PricebookEntryId = PricebookEntryId;
                        OpportunityLineItem.Description = "Discount Total";
                        OpportunityLineItem.Quantity    = 1.0;
                        OpportunityLineItem.TotalPrice  = DiscountItems.orderCount;
                        var OpportunityLineItemResult = await forceClient.CreateAsync("OpportunityLineItem", OpportunityLineItem);
                    }
                    Errorlog.LogResponseToSF(CustomerID, string.Format(Thread.CurrentThread.CurrentCulture, Helper.Messages.SUCCESS_RESPONSE, contactId), requestId, statuscode = "OK");
                    #endregion
                    return(response);
                }
            }
            catch (Exception ex)
            {
                Email email = new Email();
                errorMessage = ex.Message.ToString();
                errorMessage = (errorMessage == "authentication failure") ? "Please Check your salesforce UserName ,Password , SecurityToken and SalesforceTokenURL" : (errorMessage == "invalid client credentials") ? "Please Check your salesforce clientId and clientSecretKey  " : errorMessage;
                Errorlog.ErrorDetail(CustomerID, orderId, "SalesforceSync", errorMessage, 1);
                email.SendMailForError("Salesforce Account Sync Error", email.BodyService(Convert.ToString(Lead.FirstName + " " + Lead.LastName), Convert.ToString(Lead.Email), Convert.ToString(Credential.ApplicationId), ex.Message.ToString(), ex.StackTrace.ToString()));
                response = Request.CreateResponse(HttpStatusCode.InternalServerError, errorMessage);
                return(response);
            }
        }
示例#25
0
        public async Task <SuccessResponse> Insert(TEntity entity)
        {
            var successResponse = await _client.CreateAsync(entity.GetType().Name + "__c", entity);

            return(successResponse);
        }
        private static async Task RunSample()
        {
            var auth = new AuthenticationClient();

            // Authenticate with Salesforce
            Console.WriteLine("Authenticating with Salesforce");
            await auth.UsernamePasswordAsync(ConsumerKey, ConsumerSecret, Username, Password);
            Console.WriteLine("Connected to Salesforce");

            var client = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);

            // Create a sample record
            Console.WriteLine("Creating test record.");
            var account = new Account { Name = "Test Account" };
            account.Id = await client.CreateAsync(Account.SObjectTypeName, account);
            if (account.Id == null)
            {
                Console.WriteLine("Failed to create test record.");
                return;
            }

            Console.WriteLine("Successfully created test record.");

            // Update the sample record
            // Shows that annonymous types can be used as well
            Console.WriteLine("Updating test record.");
            var success = await client.UpdateAsync(Account.SObjectTypeName, account.Id, new { Name = "Test Update" });
            if (!success)
            {
                Console.WriteLine("Failed to update test record!");
                return;
            }

            Console.WriteLine("Successfully updated the record.");

            // Retrieve the sample record
            // How to retrieve a single record if the id is known
            Console.WriteLine("Retrieving the record by ID.");
            account = await client.QueryByIdAsync<Account>(Account.SObjectTypeName, account.Id);
            if (account == null)
            {
                Console.WriteLine("Failed to retrieve the record by ID!");
                return;
            }

            Console.WriteLine("Retrieved the record by ID.");

            // Query for record by name
            Console.WriteLine("Querying the record by name.");
            var accounts = await client.QueryAsync<Account>("SELECT ID, Name FROM Account WHERE Name = '" + account.Name + "'");
            account = accounts.records.FirstOrDefault();
            if (account == null)
            {
                Console.WriteLine("Failed to retrieve account by query!");
                return;
            }

            Console.WriteLine("Retrieved the record by name.");

            // Delete account
            Console.WriteLine("Deleting the record by ID.");
            success = await client.DeleteAsync(Account.SObjectTypeName, account.Id);
            if (!success)
            {
                Console.WriteLine("Failed to delete the record by ID!");
                return;
            }
            Console.WriteLine("Deleted the record by ID.");

            // Selecting multiple accounts into a dynamic
            Console.WriteLine("Querying multiple records.");
            var dynamicAccounts = await client.QueryAsync<dynamic>("SELECT ID, Name FROM Account LIMIT 10");
            foreach (dynamic acct in dynamicAccounts.records)
            {
                Console.WriteLine("Account - " + acct.Name);
            }

            // Creating parent - child records using a Dynamic
            Console.WriteLine("Creating a parent record (Account)");
            dynamic a = new ExpandoObject();
            a.Name = "Account from .Net Toolkit";
            a.Id = await client.CreateAsync("Account", a);
            if (a.Id == null)
            {
                Console.WriteLine("Failed to create parent record.");
                return;
            }

            Console.WriteLine("Creating a child record (Contact)");
            dynamic c = new ExpandoObject();
            c.FirstName = "Joe";
            c.LastName = "Blow";
            c.AccountId = a.Id;
            c.Id = await client.CreateAsync("Contact", c);
            if (c.Id == null)
            {
                Console.WriteLine("Failed to create child record.");
                return;
            }

            Console.WriteLine("Press Enter to delete parent and child and continue");
            Console.Read();

            // Delete account (also deletes contact)
            Console.WriteLine("Deleting the Account by Id.");
            success = await client.DeleteAsync(Account.SObjectTypeName, a.Id);
            if (!success)
            {
                Console.WriteLine("Failed to delete the record by ID!");
                return;
            }
            Console.WriteLine("Deleted the Account and Contact.");

        }
示例#27
0
        private static async Task RunSample()
        {
            var auth = new AuthenticationClient();

            // Authenticate with Salesforce
            Console.WriteLine("Authenticating with Salesforce");
            await auth.UsernamePasswordAsync(ConsumerKey, ConsumerSecret, Username, Password);

            Console.WriteLine("Connected to Salesforce");

            var client = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);

            // Create a sample record
            Console.WriteLine("Creating test record.");
            var account = new Account {
                Name = "Test Account"
            };

            account.Id = await client.CreateAsync(Account.SObjectTypeName, account);

            if (account.Id == null)
            {
                Console.WriteLine("Failed to create test record.");
                return;
            }

            Console.WriteLine("Successfully created test record.");

            // Update the sample record
            // Shows that annonymous types can be used as well
            Console.WriteLine("Updating test record.");
            var success = await client.UpdateAsync(Account.SObjectTypeName, account.Id, new { Name = "Test Update" });

            if (!success)
            {
                Console.WriteLine("Failed to update test record!");
                return;
            }

            Console.WriteLine("Successfully updated the record.");

            // Retrieve the sample record
            // How to retrieve a single record if the id is known
            Console.WriteLine("Retrieving the record by ID.");
            account = await client.QueryByIdAsync <Account>(Account.SObjectTypeName, account.Id);

            if (account == null)
            {
                Console.WriteLine("Failed to retrieve the record by ID!");
                return;
            }

            Console.WriteLine("Retrieved the record by ID.");

            // Query for record by name
            Console.WriteLine("Querying the record by name.");
            var accounts = await client.QueryAsync <Account>("SELECT ID, Name FROM Account WHERE Name = '" + account.Name + "'");

            account = accounts.records.FirstOrDefault();
            if (account == null)
            {
                Console.WriteLine("Failed to retrieve account by query!");
                return;
            }

            Console.WriteLine("Retrieved the record by name.");

            // Delete account
            Console.WriteLine("Deleting the record by ID.");
            success = await client.DeleteAsync(Account.SObjectTypeName, account.Id);

            if (!success)
            {
                Console.WriteLine("Failed to delete the record by ID!");
                return;
            }
            Console.WriteLine("Deleted the record by ID.");

            // Selecting multiple accounts into a dynamic
            Console.WriteLine("Querying multiple records.");
            var dynamicAccounts = await client.QueryAsync <dynamic>("SELECT ID, Name FROM Account LIMIT 10");

            foreach (dynamic acct in dynamicAccounts.records)
            {
                Console.WriteLine("Account - " + acct.Name);
            }

            // Creating parent - child records using a Dynamic
            Console.WriteLine("Creating a parent record (Account)");
            dynamic a = new ExpandoObject();

            a.Name = "Account from .Net Toolkit";
            a.Id   = await client.CreateAsync("Account", a);

            if (a.Id == null)
            {
                Console.WriteLine("Failed to create parent record.");
                return;
            }

            Console.WriteLine("Creating a child record (Contact)");
            dynamic c = new ExpandoObject();

            c.FirstName = "Joe";
            c.LastName  = "Blow";
            c.AccountId = a.Id;
            c.Id        = await client.CreateAsync("Contact", c);

            if (c.Id == null)
            {
                Console.WriteLine("Failed to create child record.");
                return;
            }

            Console.WriteLine("Press Enter to delete parent and child and continue");
            Console.Read();

            // Delete account (also deletes contact)
            Console.WriteLine("Deleting the Account by Id.");
            success = await client.DeleteAsync(Account.SObjectTypeName, a.Id);

            if (!success)
            {
                Console.WriteLine("Failed to delete the record by ID!");
                return;
            }
            Console.WriteLine("Deleted the Account and Contact.");
        }
示例#28
0
        private static async Task RunSample()
        {
            try
            {
                var auth = new AuthenticationClient();

                // Authenticate with Salesforce
                Console.WriteLine("Authenticating with Salesforce...");
                var url = IsSandboxUser.Equals("true", StringComparison.CurrentCultureIgnoreCase)
                    ? "https://login.salesforce.com/services/oauth2/token "
                    : "https://test.salesforce.com/services/oauth2/token";

                await auth.UsernamePasswordAsync(ConsumerKey, ConsumerSecret, Username, Password, url);

                Console.WriteLine("Connected to Salesforce.");
                var client = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);
                // Retrieve all accounts
                Console.WriteLine("Get Accounts");
                // Initialization
                PhoneBook phoneBook = new PhoneBook();

                // Create Query
                var addPhoneData = new PhoneBook {
                    Email__c = "*****@*****.**", FirstName__c = "John", LastName__c = "Doe", Phone__c = 9876543210
                };
                var result = await client.CreateAsync(PhoneBook.SObjectTypeName, addPhoneData);

                if (result.Id == null)
                {
                    Console.WriteLine("Cannot insert data to Phonebook!");
                    return;
                }
                Console.WriteLine("Successfully added the record.");

                // Update Query
                var success = await client.UpdateAsync(PhoneBook.SObjectTypeName, result.Id, new { FirstName__c = "Tim" });

                if (!string.IsNullOrEmpty(success.Errors.ToString()))
                {
                    Console.WriteLine("Failed to update test record!");
                    return;
                }
                Console.WriteLine("Successfully updated the record.");

                // Delete Query
                Console.WriteLine("Deleting the record by ID.");
                var deleted = await client.DeleteAsync(PhoneBook.SObjectTypeName, result.Id);

                if (!deleted)
                {
                    Console.WriteLine("Failed to delete the record by ID!");
                    return;
                }
                Console.WriteLine("Successfully deleted the record.");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
            }
        }
示例#29
0
        public IActionResult SFExamplePost()
        {
            var auth = new AuthenticationClient();

            auth.UsernamePasswordAsync(_configuration.GetValue <string>("SFConsumerKey"), _configuration.GetValue <string>("SFConsumerSecret"), _configuration.GetValue <string>("SFUserName"), _configuration.GetValue <string>("SFPassword")).Wait();

            var instanceUrl = auth.InstanceUrl;
            var accessToken = auth.AccessToken;
            var apiVersion  = auth.ApiVersion;

            var    client             = new ForceClient(instanceUrl, accessToken, apiVersion);
            string virtualMachineName = string.Empty;
            string status             = string.Empty;
            string envRecordId        = string.Empty;
            string accReqRecordId     = string.Empty;

            if (!string.IsNullOrEmpty(Request.Form["btnRequestVM"]))
            {
                virtualMachineName = Request.Form["txtVirtualMachineName"];
                status             = "Processing";
                // Add an environment
                Environment environment = new Environment()
                {
                    UserName__c           = User.Identity.Name,
                    VirtualMachineName__c = virtualMachineName,
                    Status__c             = status
                };
                var success = client.CreateAsync("Environment__c", environment).Result;
                if (success.Success)
                {
                    envRecordId = success.Id;
                }
                else
                {
                    // Handle error here
                }
            }
            else if (!string.IsNullOrEmpty(Request.Form["btnCheckStatus"]))
            {
                envRecordId        = Request.Form["hidEnvRecordId"];
                virtualMachineName = Request.Form["hidVirtualMachineName"];
                status             = "Processing";

                // Check the environment status
                var environments = client.QueryAsync <Environment>(string.Format("SELECT id, UserName__c, VirtualMachineName__c, Status__c FROM Environment__c WHERE id = '{0}'", envRecordId)).Result;

                if (environments.Records.Count > 0)
                {
                    if (environments.Records[0].Status__c == "Ready")
                    {
                        status = "Ready";
                    }
                }
            }
            else if (!string.IsNullOrEmpty(Request.Form["btnRequestAccess"]))
            {
                virtualMachineName = Request.Form["hidVirtualMachineName"];
                status             = "Requested";

                AccessRequest accessRequest = new AccessRequest()
                {
                    UserName__c           = User.Identity.Name,
                    VirtualMachineName__c = virtualMachineName,
                    IPAddress__c          = Request.HttpContext.Connection.RemoteIpAddress.ToString(),
                    Status__c             = status
                };
                var success = client.CreateAsync("AccessRequest__c", accessRequest).Result;
                if (success.Success)
                {
                    accReqRecordId = success.Id;
                }
                else
                {
                    // Handle error here
                }
            }
            else if (!string.IsNullOrEmpty(Request.Form["btnCheckAccess"]))
            {
                accReqRecordId     = Request.Form["hidAccReqRecordId"];
                virtualMachineName = Request.Form["hidVirtualMachineName"];
                status             = "Requested";

                // Check the access request status
                var accessRequests = client.QueryAllAsync <AccessRequest>(string.Format("SELECT id, UserName__c, VirtualMachineName__c, IPAddress__c, Status__c FROM AccessRequest__c WHERE id = '{0}'", accReqRecordId)).Result;

                if (accessRequests.Records.Count > 0)
                {
                    if (accessRequests.Records[0].Status__c == "Granted")
                    {
                        status = "Granted";
                    }
                }
            }
            ViewBag.VirtualMachineName = virtualMachineName;
            ViewBag.Status             = status;
            ViewBag.User           = User.Identity.Name;
            ViewBag.IPAddress      = Request.HttpContext.Connection.RemoteIpAddress;
            ViewBag.EnvRecordId    = envRecordId;
            ViewBag.AccReqRecordId = accReqRecordId;
            return(View());
        }
示例#30
0
        private static async Task RunSample()
        {
            var auth = new AuthenticationClient();

            // Authenticate with Salesforce
            Console.WriteLine("Authenticating with Salesforce");
            var url = IsSandboxUser.Equals("true", StringComparison.CurrentCultureIgnoreCase)
                ? "https://test.salesforce.com/services/oauth2/token"
                : "https://login.salesforce.com/services/oauth2/token";

            await auth.UsernamePasswordAsync(ConsumerKey, ConsumerSecret, Username, Password, url);

            Console.WriteLine("Connected to Salesforce");

            var client = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);

            // retrieve all accounts
            Console.WriteLine("Get Accounts");

            const string qry     = "SELECT ID, Name FROM Account";
            var          accts   = new List <Account>();
            var          results = await client.QueryAsync <Account>(qry);

            var totalSize = results.TotalSize;

            Console.WriteLine("Queried " + totalSize + " records.");

            accts.AddRange(results.Records);
            var nextRecordsUrl = results.NextRecordsUrl;

            if (!string.IsNullOrEmpty(nextRecordsUrl))
            {
                Console.WriteLine("Found nextRecordsUrl.");

                while (true)
                {
                    var continuationResults = await client.QueryContinuationAsync <Account>(nextRecordsUrl);

                    totalSize = continuationResults.TotalSize;
                    Console.WriteLine("Queried an additional " + totalSize + " records.");

                    accts.AddRange(continuationResults.Records);
                    if (string.IsNullOrEmpty(continuationResults.NextRecordsUrl))
                    {
                        break;
                    }

                    //pass nextRecordsUrl back to client.QueryAsync to request next set of records
                    nextRecordsUrl = continuationResults.NextRecordsUrl;
                }
            }
            Console.WriteLine("Retrieved accounts = " + accts.Count() + ", expected size = " + totalSize);

            // Create a sample record
            Console.WriteLine("Creating test record.");
            var account = new Account {
                Name = "Test Account"
            };
            var createAccountResponse = await client.CreateAsync(Account.SObjectTypeName, account);

            account.Id = createAccountResponse.Id;
            if (account.Id == null)
            {
                Console.WriteLine("Failed to create test record.");
                return;
            }

            Console.WriteLine("Successfully created test record.");

            // Update the sample record
            // Shows that annonymous types can be used as well
            Console.WriteLine("Updating test record.");
            var success = await client.UpdateAsync(Account.SObjectTypeName, account.Id, new { Name = "Test Update" });

            if (!string.IsNullOrEmpty(success.Errors.ToString()))
            {
                Console.WriteLine("Failed to update test record!");
                return;
            }

            Console.WriteLine("Successfully updated the record.");

            // Retrieve the sample record
            // How to retrieve a single record if the id is known
            Console.WriteLine("Retrieving the record by ID.");
            account = await client.QueryByIdAsync <Account>(Account.SObjectTypeName, account.Id);

            if (account == null)
            {
                Console.WriteLine("Failed to retrieve the record by ID!");
                return;
            }

            Console.WriteLine("Retrieved the record by ID.");

            // Query for record by name
            Console.WriteLine("Querying the record by name.");
            var accounts = await client.QueryAsync <Account>("SELECT ID, Name FROM Account WHERE Name = '" + account.Name + "'");

            account = accounts.Records.FirstOrDefault();
            if (account == null)
            {
                Console.WriteLine("Failed to retrieve account by query!");
                return;
            }

            Console.WriteLine("Retrieved the record by name.");

            // Delete account
            Console.WriteLine("Deleting the record by ID.");
            var deleted = await client.DeleteAsync(Account.SObjectTypeName, account.Id);

            if (!deleted)
            {
                Console.WriteLine("Failed to delete the record by ID!");
                return;
            }
            Console.WriteLine("Deleted the record by ID.");

            // Selecting multiple accounts into a dynamic
            Console.WriteLine("Querying multiple records.");
            var dynamicAccounts = await client.QueryAsync <dynamic>("SELECT ID, Name FROM Account LIMIT 10");

            foreach (dynamic acct in dynamicAccounts.Records)
            {
                Console.WriteLine("Account - " + acct.Name);
            }

            // Creating parent - child records using a Dynamic
            Console.WriteLine("Creating a parent record (Account)");
            dynamic a = new ExpandoObject();

            a.Name = "Account from .Net Toolkit";
            var createParentAccountResponse = await client.CreateAsync("Account", a);

            a.Id = createParentAccountResponse.Id;
            if (a.Id == null)
            {
                Console.WriteLine("Failed to create parent record.");
                return;
            }

            Console.WriteLine("Creating a child record (Contact)");
            dynamic c = new ExpandoObject();

            c.FirstName = "Joe";
            c.LastName  = "Blow";
            c.AccountId = a.Id;
            var createContactResponse = await client.CreateAsync("Contact", c);

            c.Id = createContactResponse.Id;
            if (c.Id == null)
            {
                Console.WriteLine("Failed to create child record.");
                return;
            }

            Console.WriteLine("Deleting parent and child");

            // Delete account (also deletes contact)
            Console.WriteLine("Deleting the Account by Id.");
            deleted = await client.DeleteAsync(Account.SObjectTypeName, a.Id);

            if (!deleted)
            {
                Console.WriteLine("Failed to delete the record by ID!");
                return;
            }
            Console.WriteLine("Deleted the Account and Contact.");
        }