/// <summary> /// Saves the specified so. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="so">The so.</param> /// <returns>T.</returns> /// <exception cref="System.Exception"></exception> public T Save <T>(T so) where T : sObject { SaveResult[] saveResults; if (string.IsNullOrEmpty(so.Id)) { saveResults = _binding.create(new sObject[] { so }); } else { saveResults = _binding.update(new sObject[] { so }); } if (saveResults.Any(sr => !sr.success)) { var errorString = string.Join("", saveResults.Where(sr => !sr.success) .Select( (sr, i) => $"\r\n\tError {i}:\r\n\t\t" + string.Join("\r\n\t\t", sr.errors.Select(e => e.message)))); throw new Exception($"Salesforce save failed with following errors: {errorString}"); } so.Id = saveResults[0].id; return(so); }
public void CreateSalesForceQualifiedAmbassador(Ambassador__c QualifiedAmbassador) { SforceService SfdcBinding = SalesForceSession(); try { //Campaign compaign = new Campaign(); //compaign.Name="IndiaHicks"; //sfdcLead.c = compaign; SaveResult[] saveResults = SfdcBinding.create(new sObject[] { QualifiedAmbassador }); if (saveResults[0].success) { string Id = ""; Id = saveResults[0].id; } else { string result = ""; result = saveResults[0].errors[0].message; } } catch (Exception) { throw; } }
public void CreateSalesForceLead(Lead lead) { SforceService SfdcBinding = SalesForceSession(); Lead sfdcLead = new Lead(); sfdcLead = lead; try { //Campaign compaign = new Campaign(); //compaign.Name="IndiaHicks"; //sfdcLead.c = compaign; SaveResult[] saveResults = SfdcBinding.create(new sObject[] { sfdcLead }); if (saveResults[0].success) { string Id = ""; Id = saveResults[0].id; } else { string result = ""; result = saveResults[0].errors[0].message; } } catch (Exception) { throw; } }
public void upLoad() { ServicePointManager.Expect100Continue = true; //Enables prolonged use ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; //Sets needed security level var list = new List <string>(); //List to hold case numbers that have been used string user = ""; //Test salesforce user string pass = ""; //Test salesforce pass binding = new SforceService(); //Initializs binding object binding.Timeout = 60000; //Sets maximum time per binding WebReference.LoginResult lr; //lr is my login result lr = binding.login(user, pass); //Used lr to create credentials string authEndPoint = binding.Url; //Not sure what this does honestly binding.Url = lr.serverUrl; //Sets binding to correct server binding.SessionHeaderValue = new SessionHeader(); //Header needed for API format binding.SessionHeaderValue.sessionId = lr.sessionId; //Gives binder the session id try { Case c = new Case(); Case[] cases = new Case[1]; CaseComment com = new CaseComment(); CaseComment[] coms = new CaseComment[1]; //c.AccountId = "GBS Non Case Events"; //c.Subject = "API Test"; //c.Type = "MAC - Non-Billable"; //c.Case_Product_Category__c = "Project"; //c.Product_Subcategory__c = "Training"; //c.Priority = "SLA - 5 - Client Request/Client Created Issue"; //c.Origin = "Phone"; //c.Reason = "Test Description"; //c.Status = "Case Opened"; //c.OwnerId = "Firaus Odeh"; //c.ContactId = ""; //c.Description = "Test"; //c.IsEscalated = false; //c.SuppliedName = "Test Case"; //c.SuppliedEmail = ""; //c.SuppliedPhone = ""; //c.SuppliedCompany = ""; //SaveResult[] results = binding.create(cases); //Debug.WriteLine("valid Data"); c.Id = "5000g000026SPQ8AAO"; string query1 = "Insert into Case (Comments) Value ('Test') Where CaseNumber = '00311360'"; QueryResult result = binding.query(query1); com.Id = result.ToString(); c.Subject = "Test"; com.CommentBody = "Test comment"; c.Comments = "test"; coms[0] = com; SaveResult[] check = binding.create(coms); } catch { Debug.WriteLine("Invalid data"); } }
public ActionResult Insert() { Product2 insertProduct = new Product2(); insertProduct.IsActive = true; insertProduct.IsActiveSpecified = true; insertProduct.Name = "Test Product"; insertProduct.ProductCode = "Test"; Response.Write("Name:" + insertProduct.Name); Response.Write("<br/>ProductCode:" + insertProduct.ProductCode); SaveResult[] createResults = sfdcBinding.create(new sObject[] { insertProduct }); if (createResults[0].success) { string id = createResults[0].id; Response.Write("<br/>ID:" + id); Response.Write("<br/>INSERT Product Successfully!!!"); } else { string result = createResults[0].errors[0].message; Response.Write("<br/>ERROR:" + result); } return(View("Index")); }
public string InsertSObject(string sobjectName, sObject obj) { LoginIfRequired(); sObject[] objArray = new sObject[] { obj }; var saveResults = _binding.create(objArray); CheckSaveResults(saveResults, string.Format("Creation of {0}", sobjectName), true); if (saveResults.Length != 1) { throw new ApplicationException(string.Format("Expected one saveresult back for creation of {0} but got {1}", sobjectName, saveResults.Length)); } var rowResult = saveResults[0]; return(rowResult.id); }
//Create a new record public static void connectWithTridionAndWriteDataInSF(List <SalesforceIntegrationWithSDLWeb8.DAL.Model.Lead> cmsLeadData) { SforceService SfdcBinding = null; LoginResult CurrentLoginResult = null; SfdcBinding = new SforceService(); try { CurrentLoginResult = SfdcBinding.login(ConfigurationManager.AppSettings["uName"].ToString(), ConfigurationManager.AppSettings["pWD"].ToString()); //Change the binding to the new endpoint SfdcBinding.Url = CurrentLoginResult.serverUrl; //Create a new session header object and set the session id to that returned by the login SfdcBinding.SessionHeaderValue = new SessionHeader(); SfdcBinding.SessionHeaderValue.sessionId = CurrentLoginResult.sessionId; com.salesforce.ap2.Lead sfLead = new com.salesforce.ap2.Lead(); //string firstName = "Hem"; //string lastName = "Kant"; //string email = "*****@*****.**"; //string company = "ABC Corp."; foreach (var item in cmsLeadData) { sfLead.FirstName = item.FName.Text; sfLead.LastName = item.LName.Text; sfLead.Email = item.EmaiID.Text; sfLead.Company = item.Company.Text; SaveResult[] saveResults = SfdcBinding.create(new sObject[] { sfLead }); if (saveResults[0].success) { string Id = ""; Id = saveResults[0].id; } else { string result = ""; result = saveResults[0].errors[0].message; } } } catch (System.Web.Services.Protocols.SoapException e) { // This is likley to be caused by bad username or password SfdcBinding = null; throw (e); } catch (Exception e) { // This is something else, probably comminication SfdcBinding = null; throw (e); } }
/// <summary> /// Creates Salesforce. /// </summary> /// <param name="objectTypeName">Object type name.</param> /// <param name="values">Object values.</param> /// <returns>Operation result.</returns> public bool CreateObject(string objectTypeName, Dictionary <string, IConvertible> values) { bool result = false; if (CheckConnected()) { if (String.IsNullOrEmpty(objectTypeName)) { throw (new ArgumentNullException("objectTypeName")); } if (values == null) { throw (new ArgumentNullException("values")); } if (values.Count > 0) { if (!values.ContainsKey(ID_FIELD_NAME)) { SaveResult[] saveResults = _binding.create ( new sObject[] { Constructor.ConstructSObject(objectTypeName, values) } ); result = ((saveResults.Length > 0) && (saveResults[0].success)); } else { throw (new InvalidOperationException(Errors.ERR_ID_FIELD_IS_AUTOGENERATED)); } } else { throw (new InvalidOperationException(Errors.ERR_FIELDS_ARE_EMPTY)); } } return(result); }
public void CreateLeadeTask(Task task) { SforceService SfdcBinding = SalesForceSession(); SaveResult[] results = null; try { results = SfdcBinding.create(new Task[] { task }); } catch (Exception ce) { } }
public void CreateLeadEvent(Common.SforceServices.Event evnt) { SforceService SfdcBinding = SalesForceSession(); SaveResult[] results = null; try { results = SfdcBinding.create(new Event[] { evnt }); } catch (Exception ce) { } }
/// <summary> /// /// </summary> /// <returns></returns> public int CreateEvent(SalesForceEvent eventsales) { List <SalesForceEvent> listEvents = new List <SalesForceEvent>(); try { Event salesevent = new Event(); salesevent.Subject = eventsales.Subject; salesevent.StartDateTime = eventsales.StartDate; salesevent.EndDateTime = eventsales.EndDate; salesevent.Location = eventsales.Location; salesevent.Description = eventsales.Description; salesevent.StartDateTimeSpecified = true; salesevent.EndDateTimeSpecified = true; QueryResult queryResult = null; SaveResult[] results = SfdcBinding.create(new sObject[] { salesevent }); //for (int i = 0; i < queryResult.size; i++) //{ // SalesForceEvent sfEvent = new SalesForceEvent(); // Event salesforceEvent = (Event)queryResult.records[i]; // sfEvent.Subject = salesforceEvent.Subject; // sfEvent.StartDate = salesforceEvent.StartDateTime; // sfEvent.EndDate = salesforceEvent.EndDateTime; ; // sfEvent.Id = i; // listEvents.Add(sfEvent); //} return(1); } catch (Exception e) { EventLog.WriteEntry("SalesForcceIntegration", e.Message, EventLogEntryType.Error); return(0); } }
private void button1_Click(object sender, EventArgs e) { if (!IsConnected()) { getSessionInfo(); _sforceRef.Url = _loginResult.serverUrl; // MessageBox.Show(_sforceRef.Url.ToString()); _sforceRef.SessionHeaderValue = new SessionHeader(); _sforceRef.SessionHeaderValue.sessionId = _loginResult.sessionId; Lead l1 = new Lead(); l1.LastName = textBox1.Text; l1.Company = textBox2.Text; l1.Status = textBox3.Text; SaveResult[] createResult = _sforceRef.create(new sObject[] { l1 }); if (createResult[0].success) { MessageBox.Show("Lead Inserted Succesfully "); } } }
///<summary> ///Create any sObject such as Opportunity, Account, CustomObject__c ///</summary> ///<param name="model"> ///model.Type = "Account" ///model.Fields = new List(ElementField)(){ ElementField ={Key ="Name", Value = "My new Account Name"} etc.} ///</param> ///<returns></returns> public SaveResult[] CreateElement(CreateSObject model) { if (model?.Fields == null) { return(new SaveResult[] { new SaveResult() { success = false, errors = new Error[] { new Error() { message = "UpdateSObject or UpdateSObject.Fields cannot be null" } } } }); } sObject element = new sObject(); XmlDocument doc = new XmlDocument(); XmlElement[] fields = new XmlElement[model.Fields.Count]; for (int i = 0; i < model.Fields.Count; ++i) { fields[i] = doc.CreateElement(model.Fields[i].Key); fields[i].InnerText = model.Fields[i].Value; } element.type = model.Type; element.Any = fields; return(_binding .create(new sObject[] { element })); }
protected override void Execute(CodeActivityContext context) { { System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; string userName; string password; userName = Username.Get(context); //username from context password = Password.Get(context) + SecurityToken.Get(context); //password+token from context SforceService SfdcBinding = null; LoginResult CurrentLoginResult = null; SfdcBinding = new SforceService(); try { CurrentLoginResult = SfdcBinding.login(userName, password); } catch (System.Web.Services.Protocols.SoapException e) { // This is likley to be caused by bad username or password SfdcBinding = null; throw (e); } catch (Exception e) { // This is something else, probably comminication SfdcBinding = null; throw (e); } //Change the binding to the new endpoint SfdcBinding.Url = CurrentLoginResult.serverUrl; //Console.WriteLine(SfdcBinding.Url); //Console.ReadLine(); //Create a new session header object and set the session id to that returned by the login SfdcBinding.SessionHeaderValue = new SessionHeader(); SfdcBinding.SessionHeaderValue.sessionId = CurrentLoginResult.sessionId; String[] fieldNames = FieldNames.Get(context); String[] fieldValues = FieldValues.Get(context); sObject obj = new sObject(); System.Xml.XmlElement[] objFields = new System.Xml.XmlElement[fieldNames.Length]; System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); for (int i = 0; i < fieldNames.Length; i++) { objFields[i] = doc.CreateElement(fieldNames[i]); } for (int j = 0; j < fieldValues.Length; j++) { objFields[j].InnerText = fieldValues[j]; } obj.type = ObjectName.Get(context); obj.Any = objFields; sObject[] objList = new sObject[1]; objList[0] = obj; SaveResult[] results = SfdcBinding.create(objList); for (int j = 0; j < results.Length; j++) { if (results[j].success) { RecordID.Set(context, results[j].id); } else { // There were errors during the create call, // go through the errors array and write // them to the console String error; for (int i = 0; i < results[j].errors.Length; i++) { Error err = results[j].errors[i]; error = "Errors was found on item " + j.ToString() + Environment.NewLine + "Error code is: " + err.statusCode.ToString() + Environment.NewLine + "Error message: " + err.message; RecordID.Set(context, error); } } } } }
public string createCTA(string name, string comments, CUser user, out ArrayList messages, out bool success) { if (user.Company == null) { throw new Exception("Can't create a CTA without a company and an Integration"); } if (user.Company.Intgr == null) { throw new Exception("Can't create a CTA without a company and an Integration"); } if (user.Company.Intgr.GainsightCTAStatus == null) { throw new Exception("Can't create a CTA without a Gainsight Info setup!"); } if (user == null || user.ExternalSystemId == null) { throw new Exception("Can't create a CTA without a salesforce Account Id on the User record!"); } Integrations integrations = user.Company.Intgr; //set up returns success = false; messages = new ArrayList(); //the id to return string idcreated = ""; //first login if (!login(out messages)) { success = false; //throw new Exception("Could not login to Salesforce"); } try { // Create a new sObject of type Contact // and fill out its fields. sObject CTA = new SFAccess.sObject(); System.Xml.XmlElement[] CTAFields = new System.Xml.XmlElement[12]; // Create the ticket's fields System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); CTAFields[0] = doc.CreateElement("JBCXM__Account__c"); CTAFields[0].InnerText = user.ExternalSystemId; CTAFields[1] = doc.CreateElement("JBCXM__Assignee__c"); CTAFields[1].InnerText = integrations.GainsightCTAUserId;// "00541000001LJxYAAW"; //------------------------------------me CTAFields[2] = doc.CreateElement("JBCXM__DueDate__c"); CTAFields[2].InnerText = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd"); CTAFields[3] = doc.CreateElement("JBCXM__Priority__c"); //Alert Severity CTAFields[3].InnerText = integrations.GainsightCTAPriority; // "a0D41000001qZtYEAU"; //-------------------------------------high priority CTAFields[4] = doc.CreateElement("JBCXM__Stage__c"); //Alert STatus CTAFields[4].InnerText = integrations.GainsightCTAStatus; // "a0D41000001qZsCEAU";//---------------- stands for Open - this is like a status CTAFields[5] = doc.CreateElement("JBCXM__Type__c"); CTAFields[5].InnerText = integrations.GainsightCTAType; // "a1141000000cVEcAAM";//--------------------------------------what is type id ; CTAFields[7] = doc.CreateElement("JBCXM__Reason__c"); CTAFields[7].InnerText = integrations.GainsightCTAReason; // "a0D41000001qZsIEAU"; CTAFields[8] = doc.CreateElement("JBCXM__Comments__c"); CTAFields[8].InnerText = comments; //-------------------------------------- CTAFields[9] = doc.CreateElement("Name"); CTAFields[9].InnerText = name; CTAFields[10] = doc.CreateElement("JBCXM__CreatedDate__c"); CTAFields[10].InnerText = DateTime.Now.ToString("yyyy-MM-dd"); CTAFields[11] = doc.CreateElement("JBCXM__Playbook__c"); CTAFields[11].InnerText = integrations.GainsightCTAPlaybook;// "a0d41000000inGeAAI"; //field to set picklist Category other //JBCXM__Priority__c Alert Severity //JBCXM__Stage__c Alert Status //JBCXM__Reason__c Alert Reason //JBCXM__TypeName__c ? different object - type of CTA? event or trial //JBCXM__Account__c from account object //JBCXM__Assignee__c this is from a user //JBCXM__DueDate__c user input //JBCXM__Comments__c user input CTA.type = "JBCXM__CTA__c"; CTA.Any = CTAFields; // Add this sObject to an array sObject[] CTAList = new sObject[1]; CTAList[0] = CTA; // Make a create call and pass it the array of sObjects SaveResult[] results = binding.create(CTAList); // Iterate through the results list // and write the ID of the new sObject // or the errors if the object creation failed. // In this case, we only have one result // since we created one ticket. for (int j = 0; j < results.Length; j++) { if (results[j].success) { messages.Add("\nA CTA was created with an ID of: " + results[j].id); idcreated = results[j].id; } else { // There were errors during the create call, // go through the errors array and write // them to the console for (int i = 0; i < results[j].errors.Length; i++) { Error err = results[j].errors[i]; messages.Add("Errors were found on item " + j.ToString()); messages.Add("Error code is: " + err.statusCode.ToString()); messages.Add("Error message: " + err.message); } } } } catch (SoapException e) { messages.Add("An unexpected error has occurred: " + e.Message + " Stack trace: " + e.StackTrace); } //now logout logout(); return(idcreated); }
public void PreSend(List<DataForAPI> listToSend) { // CreateNewJob(); // // AddBatchesToTheJob(); try { var salesForceService = new SforceService(); var userName = Config.Dictionaries.AppSettings.ServiceProviders.SalesForce.Login; var securityToken = Config.Dictionaries.AppSettings.ServiceProviders.SalesForce.SecurityToken; var password = Config.Dictionaries.AppSettings.ServiceProviders.SalesForce.Password + securityToken; var loginResult = salesForceService.login(userName, password); if (!loginResult.passwordExpired) { salesForceService.Url = loginResult.serverUrl; salesForceService.SessionHeaderValue = new SessionHeader { sessionId = loginResult.sessionId }; var sObjectArraysList = RegularizeList(listToSend); foreach (var sObjectArray in sObjectArraysList) { var elqaMarketingActivityArray = CreateTransferObjectsArray(sObjectArray); var saveResults = salesForceService.create(elqaMarketingActivityArray); for (int i = 0; i < saveResults.Length; i++) { if (saveResults[i].success) { sObjectArray[i].DataBaseAccess.UpdateEntity(sObjectArray[i].SourceEntity, true, string.Empty); } else { sObjectArray[i].DataBaseAccess.UpdateEntity(sObjectArray[i].SourceEntity, false, saveResults[i].errors[0].statusCode + " " + saveResults[i].errors[0].message); } switch (sObjectArray[i].ProcessType) { case Enums.ProcessType.JPMarginCall: sObjectArray[i].DataBaseAccess.UpdateMarginCall(sObjectArray[i].SourceEntity); break; case Enums.ProcessType.JPInactivityDeletion: sObjectArray[i].DataBaseAccess.UpdateJapanInactivity(sObjectArray[i].SourceEntity); break; case Enums.ProcessType.AUHKMarginUtilization: sObjectArray[i].DataBaseAccess.UpdateHighMarginThresholdBreachesToEloqua(sObjectArray[i].SourceEntity); break; } } } } else { _logger.LogEvent(() => Config.AppEvents.GainWinServicesExactTarget.ExactTargetWarning, "Password Expired. Login: "******" Password: "******"SalesForceApi.PreSend " + e); } }
public string createCTA(string Subject, string Description, CUser user) { //to use in the CTA object for Gainsight /*JBCXM__Account__c, * JBCXM__Assignee__c, * JBCXM__DueDate__c, * JBCXM__Priority__c, * JBCXM__Reason__c, * JBCXM__Stage__c, * JBCXM__Type__c, = 'a3SG000000073q9MAA' * JBCXM__TypeName__c, * */ //the id to return string idcreated = ""; //first login if (!login()) { throw new Exception("Could not login to Salesforce"); } try { // Create a new sObject of type Contact // and fill out its fields. sObject CTA = new SFAccess.sObject(); System.Xml.XmlElement[] CTAFields = new System.Xml.XmlElement[8]; // Create the ticket's fields System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); CTAFields[0] = doc.CreateElement("JBCXM__Account__c"); CTAFields[0].InnerText = user.ExternalSystemId; CTAFields[1] = doc.CreateElement("JBCXM__Assignee__c"); CTAFields[1].InnerText = "pkumar"; //------------------------------------what is this one? id CTAFields[2] = doc.CreateElement("JBCXM__DueDate__c"); CTAFields[2].InnerText = DateTime.Now.ToString(); CTAFields[3] = doc.CreateElement("JBCXM__Priority__c"); //Alert Severity CTAFields[3].InnerText = "a3SG00000005SJQMA2"; //-------------------------------------high priority CTAFields[4] = doc.CreateElement("JBCXM__Stage__c"); //Alert STatus CTAFields[4].InnerText = "a3SG000000073q9MAA"; //---------------- stands for Open - this is like a status // CTAFields[5] = doc.CreateElement("JBCXM__Type__c"); //CTAFields[5].InnerText = "a5UG0000000GoSUMA0";//--------------------------------------what is type id ; CTAFields[6] = doc.CreateElement("JBCXM__TypeName__c"); CTAFields[6].InnerText = "Event"; //--------------------------------------Event //field to set picklist Category other //JBCXM__Priority__c Alert Severity //JBCXM__Stage__c Alert Status //JBCXM__Reason__c Alert Reason //JBCXM__TypeName__c ? different object - type of CTA? event or trial //JBCXM__Account__c from account object //JBCXM__Assignee__c this is from a user //JBCXM__DueDate__c user input //JBCXM__Comments__c user input CTA.type = "JBCXM__CTA__c"; CTA.Any = CTAFields; // Add this sObject to an array sObject[] CTAList = new sObject[1]; CTAList[0] = CTA; // Make a create call and pass it the array of sObjects SaveResult[] results = binding.create(CTAList); // Iterate through the results list // and write the ID of the new sObject // or the errors if the object creation failed. // In this case, we only have one result // since we created one ticket. for (int j = 0; j < results.Length; j++) { if (results[j].success) { Console.Write("\nA CTA was created with an ID of: " + results[j].id); idcreated = results[j].id; } else { // There were errors during the create call, // go through the errors array and write // them to the console for (int i = 0; i < results[j].errors.Length; i++) { Error err = results[j].errors[i]; Console.WriteLine("Errors were found on item " + j.ToString()); Console.WriteLine("Error code is: " + err.statusCode.ToString()); Console.WriteLine("Error message: " + err.message); } } } } catch (SoapException e) { Console.WriteLine("An unexpected error has occurred: " + e.Message + " Stack trace: " + e.StackTrace); } //now logout logout(); return(idcreated); }
public string Register(SalesforceUpdateRequest model) { //LOGIN TO SALESFORCE //Prevent using TLS 1.0 which is outdated System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; string userName = _configService.getConfigValusAsString("SalesforceUserName"); string password = _configService.getConfigValusAsString("SalesforcePassword"); SforceService SfdcBinding = null; LoginResult CurrentLoginResult = null; SfdcBinding = new SforceService(); try { CurrentLoginResult = SfdcBinding.login(userName, password); } catch (System.Web.Services.Protocols.SoapException e) { // This is likley to be caused by bad username or password SfdcBinding = null; throw (e); } catch (Exception e) { // This is something else, probably comminication SfdcBinding = null; throw (e); } //Change the binding to the new endpoint SfdcBinding.Url = CurrentLoginResult.serverUrl; //Create a new session header object and set the session id to that returned by the login SfdcBinding.SessionHeaderValue = new SessionHeader(); SfdcBinding.SessionHeaderValue.sessionId = CurrentLoginResult.sessionId; //UPDATE -- to (spunkydrewster002's) salesforce Leads QueryResult queryResult = null; string emailToUpdate = model.Email; String SOQL = "select Id from Lead where Email = '" + emailToUpdate + "'"; queryResult = SfdcBinding.query(SOQL); //If email exists, update with first/last name if (queryResult.size > 0) { //UPDATE -- to (spunkydrewster002's) salesforce Leads Lead lead = (Lead)queryResult.records[0]; string Id = lead.Id; Lead updateLead = new Lead(); updateLead.Id = Id; updateLead.Email = model.Email; updateLead.FirstName = model.FirstName; updateLead.LastName = model.LastName; SaveResult[] saveResults = SfdcBinding.update(new sObject[] { updateLead }); string result = ""; if (saveResults[0].success) { result = "The update of Lead ID " + saveResults[0].id + " was succesful"; return(result); } else { result = "There was an error updating the Lead. The error returned was " + saveResults[0].errors[0].message; return(result); } } //If email doesn't exist, insert email with first/last name else { //POST - to (spunkydrewster002's) salesforce Leads Lead sfdcLead = new Lead(); sfdcLead.Email = model.Email; //Fields required for lead but wont be submitted on homepage, so placeholders are used. sfdcLead.FirstName = model.FirstName; sfdcLead.LastName = model.LastName; string companyName = "Grader Registered User"; sfdcLead.Company = companyName; SaveResult[] saveResults = SfdcBinding.create(new sObject[] { sfdcLead }); if (saveResults[0].success) { string resultId = ""; resultId = saveResults[0].id; return(resultId); } else { string result = ""; result = saveResults[0].errors[0].message; return(result); } } }
internal List <Dictionary <UpsertKind, SaveResult> > UpsertItems(string objectName, DataTable items, bool hasEpmLiveId) { var objectsToInsert = new List <sObject>(); var objectsToUpdate = new List <sObject>(); foreach (DataRow dataRow in items.Rows) { var sObject = new sObject { type = objectName }; object oId = dataRow["ID"]; if (oId != null && oId != DBNull.Value) { sObject.Id = oId.ToString(); } var fieldsToNull = new List <string>(); var xmlElements = new List <XmlElement>(); var xmlDocument = new XmlDocument(); if (hasEpmLiveId) { XmlElement spIdElement = xmlDocument.CreateElement(_appNamespace + EXT_ID_FIELD); spIdElement.InnerText = dataRow["SPID"].ToString(); xmlElements.Add(spIdElement); } foreach (DataColumn dataColumn in items.Columns) { string columnName = dataColumn.ColumnName; if (columnName.ToLower().Equals("id") || columnName.Equals("SPID") || columnName.Equals(_appNamespace + EXT_ID_FIELD)) { continue; } object oValue = dataRow[dataColumn]; if (oValue == null || oValue == DBNull.Value) { fieldsToNull.Add(columnName); continue; } string sValue = oValue.ToString(); if (string.IsNullOrEmpty(sValue)) { fieldsToNull.Add(columnName); continue; } XmlElement xmlElement = xmlDocument.CreateElement(columnName); xmlElement.InnerText = sValue; xmlElements.Add(xmlElement); } sObject.Any = xmlElements.ToArray(); sObject.fieldsToNull = fieldsToNull.ToArray(); if (string.IsNullOrEmpty(sObject.Id)) { objectsToInsert.Add(sObject); } else { objectsToUpdate.Add(sObject); } } var upsertResults = new List <Dictionary <UpsertKind, SaveResult> >(); if (objectsToInsert.Count > 0) { upsertResults.AddRange( _sforceService.create(objectsToInsert.ToArray()) .Select(r => new Dictionary <UpsertKind, SaveResult> { { UpsertKind.INSERT, r } })); } if (objectsToUpdate.Count > 0) { upsertResults.AddRange( _sforceService.update(objectsToUpdate.ToArray()) .Select(r => new Dictionary <UpsertKind, SaveResult> { { UpsertKind.UPDATE, r } })); } return(upsertResults); }
public void Upload() { LoginResult lr = sflogin.getLoginResult(); SforceService binding = new SforceService(); binding.SessionHeaderValue = new SessionHeader(); binding.SessionHeaderValue.sessionId = lr.sessionId; binding.Url = lr.serverUrl; bool errorFlag = false; try { DirectoryInfo dir = new DirectoryInfo(this.targetPath); FileInfo[] files = dir.GetFiles(); foreach (FileInfo file in files) { if (form1.CheckState() == false) { if (Path.GetExtension(Path.GetFullPath(file.FullName)) == ".txt") { file.Delete(); } } else { Attachment oppattach = new Attachment(); string filename = file.FullName; byte[] bytes = System.IO.File.ReadAllBytes(filename); oppattach.Body = bytes; oppattach.Name = file.Name; oppattach.ParentId = this.form1.getOppID(); sObject[] attachments = new Attachment[1]; attachments[0] = oppattach; SaveResult[] result = binding.create(attachments); for (int i = 0; i < attachments.Length; i++) { if (result[i].success) { form1.appendTextBox5("A Document was created"); } else { form1.appendTextBox5("Item had an error updating"); errorFlag = true; } } } } if (!(errorFlag)) { form1.clearDirectory(); form1.updateTextBox1("Upload Successful. Files removed from " + this.targetPath); } } catch (SoapException e) { form1.appendTextBox1("Upload failed"); form1.appendTextBox1(e.Detail.ToString()); } }
private void Form1_Load(object sender, EventArgs e) { string userName = "******"; string password = "******"; string securityToken = "YOUR REGENERATED SECURITY TOKEN"; SforceService sfdcBinding = null; LoginResult currentLoginResult = null; sfdcBinding = new SforceService(); try { currentLoginResult = sfdcBinding.login(userName, password + securityToken); } catch (System.Web.Services.Protocols.SoapException ex) { // This is likley to be caused by bad username or password sfdcBinding = null; throw (ex); } catch (Exception ex) { // This is something else, probably comminication sfdcBinding = null; throw (ex); } //Change the binding to the new endpoint sfdcBinding.Url = currentLoginResult.serverUrl; //Create a new session header object and set the session id to that returned by the login sfdcBinding.SessionHeaderValue = new SessionHeader(); sfdcBinding.SessionHeaderValue.sessionId = currentLoginResult.sessionId; //Create a case Case myNewCase = new Case(); //The status of the case, such as “New,” “Closed,” or “Escalated.” This field directly controls the IsClosed flag. Each predefined Status value implies an IsClosed flag value. For more information, see CaseStatus. myNewCase.Status = "New"; //The reason why the case was created, such as Instructions not clear, or User didn’t attend training. myNewCase.Reason = "TESTING CASE CREATION"; //The subject of the case. Limit: 255 characters myNewCase.Subject = "TEST CASE"; //The name that was entered when the case was created. This field can't be updated after the case has been created. Label is Name. myNewCase.SuppliedName = "TEST CASE"; //High, Medium, or Low myNewCase.Priority = "High"; SaveResult[] createResults = sfdcBinding.create(new sObject[] { myNewCase }); if (createResults[0].success) { string id = createResults[0].id; } else { string result = createResults[0].errors[0].message; } }
public string InsertFB(SalesforceAddRequest model) { //LOGIN TO SALESFORCE //Prevent using TLS 1.0 which is outdated System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; string userName = _configService.getConfigValusAsString("SalesforceUserName"); string password = _configService.getConfigValusAsString("SalesforcePassword"); SforceService SfdcBinding = null; LoginResult CurrentLoginResult = null; SfdcBinding = new SforceService(); try { CurrentLoginResult = SfdcBinding.login(userName, password); } catch (System.Web.Services.Protocols.SoapException e) { SfdcBinding = null; throw (e); } catch (Exception e) { SfdcBinding = null; throw (e); } SfdcBinding.Url = CurrentLoginResult.serverUrl; SfdcBinding.SessionHeaderValue = new SessionHeader(); SfdcBinding.SessionHeaderValue.sessionId = CurrentLoginResult.sessionId; //Check if email already exists QueryResult queryResult = null; String SOQL = "select Id from Lead where Email = '" + model.Email + "'"; queryResult = SfdcBinding.query(SOQL); //If email exists, update with facebook url if (queryResult.size > 0) { //UPDATE -- to (spunkydrewster002's) salesforce Leads Lead lead = (Lead)queryResult.records[0]; string Id = lead.Id; Lead updateLead = new Lead(); updateLead.Id = Id; updateLead.Email = model.Email; updateLead.Facebook_Page__c = model.Website; SaveResult[] saveResults = SfdcBinding.update(new sObject[] { updateLead }); string result = ""; if (saveResults[0].success) { result = "The update of Lead ID " + saveResults[0].id + " was succesful"; return(result); } else { result = "There was an error updating the Lead. The error returned was " + saveResults[0].errors[0].message; return(result); } } //If email doesn't exist, insert facebook url else { //POST - to (spunkydrewster002's) salesforce Leads Lead sfdcLead = new Lead(); sfdcLead.Email = model.Email; sfdcLead.Facebook_Page__c = model.Website; sfdcLead.Campaign_Source__c = model.AdSource; sfdcLead.Campaign_Medium__c = model.AdMedium; sfdcLead.Campaign_Name__c = model.AdName; sfdcLead.Campaign_Term__c = model.AdTerm; sfdcLead.Campaign_Content__c = model.AdContent; sfdcLead.Campaign_ID__c = model.AdId; //Fields required for lead but wont be submitted on homepage, so placeholders are used. string firstName = "Social"; string lastName = "Media"; string companyName = "Grader User"; sfdcLead.FirstName = firstName; sfdcLead.LastName = lastName; sfdcLead.Company = companyName; SaveResult[] saveResults = SfdcBinding.create(new sObject[] { sfdcLead }); if (saveResults[0].success) { string resultId = ""; resultId = saveResults[0].id; return(resultId); } else { string result = ""; result = saveResults[0].errors[0].message; return(result); } } }
public void SalesForceQualifiedAmbassadors() { SforceService SfdcBinding = SalesForceSession(); // GET LIST OF Qualified Ambassadors FROM DATABASE AND INSERT INTO sALESFORCE List <QualifiedAmbassadors> customers = new List <QualifiedAmbassadors>(); using (var context = Exigo.Sql()) { string sqlQuery = string.Format(@"select * from dbo.AmbassadorsList order by customerid asc "); customers = context.Query <QualifiedAmbassadors>(sqlQuery).ToList(); } if (customers.Count() == 0) { return; } List <Ambassador__c> Ambassador = new List <Ambassador__c>(); foreach (QualifiedAmbassadors Customer in customers) { Ambassador__c node = new Ambassador__c(); node.AmbassadorID__c = Customer.CustomerID.ToString(); node.Name = Customer.FirstName + " " + Customer.LastName; if (!string.IsNullOrEmpty(Customer.JoinDate)) { try { node.JoinDate__cSpecified = true; node.JoinDate__c = DateTime.Parse(Customer.JoinDate); } catch (Exception) { } } if (!string.IsNullOrEmpty(Customer.LeaveDate)) { try { node.LeaveDate__cSpecified = true; node.LeaveDate__c = DateTime.Parse(Customer.LeaveDate); } catch (Exception) { } } node.webalias__c = Customer.WebAlias; node.Q_Ambassador_Email__c = Customer.email; node.Zip_Code__c = Customer.MainZip; node.Phone__c = Customer.phone; node.Mobile_Phone__c = Customer.MobilePhone; node.SponsorID__cSpecified = true; node.SponsorID__c = double.Parse(Customer.EnrollerID.ToString()); node.Available_To_Receive_Leads__cSpecified = true; node.Available_To_Receive_Leads__c = true; node.CreatedDate = DateTime.Now; // node.CreatedById = "00536000000zbwiAAA"; Ambassador.Add(node); } if (Ambassador.Count > 0) { try { IEnumerable <List <Ambassador__c> > listambassadorlist = splitList(Ambassador.ToList()); foreach (List <Ambassador__c> list in listambassadorlist) { SaveResult[] saveResults = SfdcBinding.create(list.ToArray()); if (saveResults[0].success) { string Id = ""; Id = saveResults[0].id; } else { string result = ""; result = saveResults[0].errors[0].message; } } } catch (Exception ex) { throw; } } }
/// <summary> /// Pass a populated Member in and it will update salesforce. /// </summary> /// <param name="newMember"></param> /// <returns>SalesforceSaveResult with success/fail bool & message if there was an error</returns> public SalesforceActionResult CreateWebsiteMemberAsContact(Member newMember, string newMemberEmail) //member needs to be updated to have an email field { ////sf upserts have to happen in the proper order. upsert the member first // each join / lookup value can be upsert after the member exists // then we upsert child // then we can upsert child lookup values SalesforceActionResult sfResult = new SalesforceActionResult(); Contact newSalesforceContact = new Contact(); //Created an account for Understood.org newSalesforceContact.AccountId = "001F0000014EhHtIAK"; //todo Move this and other similar values into a config //check required values if (string.IsNullOrEmpty(newMember.FirstName)) { throw new Exception("First Name is required to save a new Contact Member to Service."); } else { newSalesforceContact.FirstName = newMember.FirstName; newSalesforceContact.member_FirstName__c = newMember.FirstName; } if (string.IsNullOrEmpty(newMember.LastName)) { //last name will always be empty for now. //throw new Exception("Last Name is required to save a new Website Contact Member to Service."); newMember.LastName = "NotSpecified"; newSalesforceContact.LastName = newMember.LastName; newSalesforceContact.member_LastName__c = newMember.LastName; } else { newSalesforceContact.LastName = newMember.LastName; newSalesforceContact.member_LastName__c = newMember.LastName; } newSalesforceContact.member_MemberId__c = newMember.MemberId.ToString(); //member_MemberId__c is our sfdc external uid on Contact newSalesforceContact.member_UserId__c = newMember.UserId.ToString(); if (newMember.ScreenName == "Screen Name")//more garbage coming through { Random random = new Random(); int randomNumber = random.Next(0, 30000); newMember.ScreenName = "ScreenName_" + randomNumber.ToString(); } newSalesforceContact.member_ScreenName__c = newMember.ScreenName; //Discovered that if you do not set both the field, and the specififed field, you don't update the checkbocx newSalesforceContact.member_allowConnections__c = newMember.allowConnections; newSalesforceContact.member_allowConnections__cSpecified = newMember.allowConnections; newSalesforceContact.member_allowNewsletter__c = newMember.allowNewsletter; newSalesforceContact.member_allowNewsletter__cSpecified = newMember.allowNewsletter; newSalesforceContact.member_emailSubscription__c = newMember.emailSubscription; newSalesforceContact.member_emailSubscription__cSpecified = newMember.emailSubscription; newSalesforceContact.member_hasOtherChildren__c = newMember.hasOtherChildren; newSalesforceContact.member_hasOtherChildren__cSpecified = newMember.hasOtherChildren; newSalesforceContact.member_isFacebookUser__c = newMember.isFacebookUser; newSalesforceContact.member_isFacebookUser__cSpecified = newMember.isFacebookUser; newSalesforceContact.member_isPrivate__c = newMember.isPrivate; newSalesforceContact.member_isPrivate__cSpecified = newMember.isPrivate; newSalesforceContact.member_ZipCode__c = newMember.ZipCode; newSalesforceContact.Email = newMemberEmail; //garbage is getting in still. if (newMember.Role != new Guid("{00000000-0000-0000-0000-000000000000}")) { newSalesforceContact.member_Role__c = Constants.SalesforceLookupDictionary[newMember.Role]; } //Journey may be null if (newMember.Journeys.Count >= 1) { newSalesforceContact.Journey__c = Constants.SalesforceLookupDictionary[newMember.Journeys.First().Key]; } //ContactsPersonality //THERE IS ALSO A PERSONALITYTYPE IN THE WSDL. DO NOT USE IT. if (!string.IsNullOrEmpty(newMember.PersonalityType.ToString())) { //garbage is getting in. skip garbage. if (newMember.PersonalityType != new Guid("{00000000-0000-0000-0000-000000000000}")) { newSalesforceContact.member_Personality__c = Constants.SalesforceLookupDictionary[newMember.PersonalityType];//.ToString(); } } //exernal id field name is not the value of the userid. its our guid for member. the name of the field/column in sfdc //sfdc needs to know the primary, unique key to look for when updating existing rows UpsertResult result = _sfs.upsert("member_MemberId__c", new sObject[] { newSalesforceContact })[0]; string SalesforceNewContactId = string.Empty; if (result.success == false) //failed to create member. stop upserts. return. { sfResult.Success = false; sfResult.Message = "An error occured during the upsert to Salesforce." + Environment.NewLine; foreach (Error e in result.errors) { sfResult.Message += "* " + e.message + Environment.NewLine; } return(sfResult); } else { SalesforceNewContactId = result.id; // lets see if this was smart enough to update our contact } //create entrires for Interests foreach (Interest i in newMember.Interests) { MemberToInterests__c sfdcMembertoInterest = new MemberToInterests__c(); //i believe that I am going to need to get the ID of the user that was just created. // membertoInterest.MemberMaster__c = newMember.UserId.ToString(); sfdcMembertoInterest.MemberMaster__c = SalesforceNewContactId; //lookup the Salesforce Id from the Sitecore Guid sfdcMembertoInterest.MemberInterest__c = Constants.SalesforceLookupDictionary[i.Key]; sfdcMembertoInterest.Name = i.Value; //NEED to use an exernal id for any upserted rows.... //i think for masterdetail records we want to just do an INSERT SaveResult interestSaveResult = _sfs.create(new sObject[] { sfdcMembertoInterest })[0]; if (interestSaveResult.success == false) { sfResult.Success = false; sfResult.Message = "An error occured during the upsert to Salesforce. Upserting Interest entries did not succeed." + Environment.NewLine + "Error Messages: " + Environment.NewLine; foreach (Error e in interestSaveResult.errors) { sfResult.Message += "Status code: (" + e.statusCode + ") Message: " + e.message + Environment.NewLine; } return(sfResult); } } //add children to salesforce foreach (Child c in newMember.Children) { Children__c sfdcChild = new Children__c(); sfdcChild.ContactChild__c = SalesforceNewContactId; sfdcChild.Grade__c = Constants.SalesforceLookupDictionary[(c.Grades.First().Key)]; //these are blowing up with garbage values getting through if (c.Section504Status != new Guid("{00000000-0000-0000-0000-000000000000}")) { sfdcChild.ChildTo504Status__c = Constants.SalesforceLookupDictionary[c.Section504Status]; } if (c.EvaluationStatus != new Guid("{00000000-0000-0000-0000-000000000000}")) { sfdcChild.ChildToEvaluationStatus__c = Constants.SalesforceLookupDictionary[c.EvaluationStatus]; } if (c.IEPStatus != new Guid("{00000000-0000-0000-0000-000000000000}")) { sfdcChild.ChildToIEPStatus__c = Constants.SalesforceLookupDictionary[c.IEPStatus]; } sfdcChild.Nickname__c = c.Nickname; sfdcChild.Name = c.Nickname; //include a guid for the child's id sfdcChild.UnderstoodChildId__c = c.ChildId.ToString(); SaveResult sfdcChildSaveResult = _sfs.create(new sObject[] { sfdcChild })[0]; if (sfdcChildSaveResult.success == false) { sfResult.Success = false; sfResult.Message = "An error occured during the upsert to Salesforce. Upserting the Members Children did not succeed." + Environment.NewLine + "Error Messages: " + Environment.NewLine; foreach (Error e in sfdcChildSaveResult.errors) { sfResult.Message += "Status code: (" + e.statusCode + ") Message: " + e.message + Environment.NewLine; } return(sfResult); } //===================================================================================================== //with this child successfully created, we can now add rows to other objects that reference the child //get the new child's salesforce id and add in issues into the salesforce lookup object foreach (Issue childIssue in c.Issues) { ChildToIssues__c sfdcforceChildIssues = new ChildToIssues__c(); sfdcforceChildIssues.ChildMaster__c = sfdcChildSaveResult.id; //we get back the ID that salesforce made during create sfdcforceChildIssues.ChildIssue__c = Constants.SalesforceLookupDictionary[childIssue.Key]; sfdcforceChildIssues.Name = childIssue.Value; SaveResult sr = _sfs.create(new sObject[] { sfdcforceChildIssues })[0]; if (sr.success == false) { sfResult.Success = false; sfResult.Message = "An error occured during the upsert to Salesforce. Creating the Issues of Children did not succeed." + Environment.NewLine + "Error Messages: " + Environment.NewLine; foreach (Error e in sr.errors) { sfResult.Message += "Status code: (" + e.statusCode + ") Message: " + e.message + Environment.NewLine; } return(sfResult); }//------------------- sfResult.Message = Environment.NewLine + "Save Result for Issue (Name:" + sfdcforceChildIssues.Name + Environment.NewLine + "|Issue:" + sfdcforceChildIssues.ChildIssue__c + Environment.NewLine + " |Success:" + sr.success.ToString(); } //save child diagnosis values foreach (Diagnosis childDiagnosis in c.Diagnoses) { ChildToDiagnosis__c salesforceChildDiagnosis = new ChildToDiagnosis__c(); salesforceChildDiagnosis.ChildMaster__c = sfdcChildSaveResult.id; salesforceChildDiagnosis.ChildDiagnosis__c = Constants.SalesforceLookupDictionary[childDiagnosis.Key]; salesforceChildDiagnosis.Name = childDiagnosis.Value; SaveResult sr = _sfs.create(new sObject[] { salesforceChildDiagnosis })[0]; if (sr.success == false) { sfResult.Success = false; sfResult.Message = "Error when saving child Diagnosis: " + sr.errors.First().message; return(sfResult); } } } // return(sfResult); }
public string InsertWidget(SalesforceAddRequest model) { //LOGIN TO SALESFORCE //Prevent using TLS 1.0 which is outdated System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; string userName = _configService.getConfigValusAsString("SalesforceUsername"); string password = _configService.getConfigValusAsString("SalesforcePassword"); SforceService SfdcBinding = null; LoginResult CurrentLoginResult = null; SfdcBinding = new SforceService(); try { CurrentLoginResult = SfdcBinding.login(userName, password); } catch (System.Web.Services.Protocols.SoapException e) { SfdcBinding = null; throw (e); } catch (Exception e) { SfdcBinding = null; throw (e); } SfdcBinding.Url = CurrentLoginResult.serverUrl; SfdcBinding.SessionHeaderValue = new SessionHeader(); SfdcBinding.SessionHeaderValue.sessionId = CurrentLoginResult.sessionId; //POST - to (spunkydrewster002's) salesforce Leads Lead sfdcLead = new Lead(); sfdcLead.Website = model.Website; sfdcLead.Campaign_Source__c = model.AdSource; sfdcLead.Campaign_Medium__c = model.AdMedium; sfdcLead.Campaign_Name__c = model.AdName; sfdcLead.Campaign_Term__c = model.AdTerm; sfdcLead.Campaign_Content__c = model.AdContent; sfdcLead.Campaign_ID__c = model.AdId; //Fields required for lead but wont be submitted on homepage, so placeholders are used. string firstName = "Unknown"; string lastName = "User"; string companyName = "WidgetUser"; sfdcLead.FirstName = firstName; sfdcLead.LastName = lastName; sfdcLead.Company = companyName; SaveResult[] saveResults = SfdcBinding.create(new sObject[] { sfdcLead }); if (saveResults[0].success) { string resultId = ""; resultId = saveResults[0].id; return(resultId); } else { string result = ""; result = saveResults[0].errors[0].message; return(result); } }