Exemple #1
0
        public static void UpdateLastTextDate(SforceService _binding, string LeadID)
        {
            Dealer_Lead__c application = new Dealer_Lead__c();

            application.Id = LeadID;
            application.BRGCaseMail_DateTime_Last_Text__c          = DateTime.Now;
            application.BRGCaseMail_DateTime_Last_Text__cSpecified = true;
            application.BRGCaseMail_Number_Texts_Sent__c           = application.BRGCaseMail_Number_Texts_Sent__c + 1;
            application.BRGCaseMail_Number_Texts_Sent__cSpecified  = true;

            if (application.BRGCaseMail_Number_Texts_Sent__c != null)
            {
                application.BRGCaseMail_Number_Texts_Sent__c += 1;
            }
            else
            {
                application.BRGCaseMail_Number_Texts_Sent__c = 1;
            }

            //call update passing an array of object

            // assuming that you've already established an enterprise WSDL binding

            SaveResult[] saveResults = _binding.update(
                new sObject[] { application });
        }
Exemple #2
0
        public UpdateSObjectsResult[] UpdateSObjects(string sobjectName, sObject[] objArray)
        {
            LoginIfRequired();
            var res         = new UpdateSObjectsResult[objArray.Length];
            var saveResults = _binding.update(objArray);

            if (saveResults.Length != objArray.Length)
            {
                throw new ApplicationException(string.Format("Sent {0} objects to update api call but got {1} results back. Numbers should match.",
                                                             objArray.Length, saveResults.Length));
            }
            for (int i = 0; i < saveResults.Length; i++)
            {
                res[i] = new UpdateSObjectsResult();
                if (saveResults[i].success)
                {
                    res[i].Success = true;
                }
                else
                {
                    res[i].ErrorMessage = GetSaveResultErrorText(saveResults[i]);
                }
            }

            return(res);
        }
Exemple #3
0
        /// <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);
        }
Exemple #4
0
        public void UpateSalesForceLead(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.update(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;
            }
        }
Exemple #5
0
        public string update_rma(string id, string finding, string asset_tag, string rci)
        {
            string message = "RMA Info Updated";

            try
            {
                conn.Open();
                MySqlCommand command = conn.CreateCommand();
                command.CommandText = "UPDATE rma set production_finding = '" + finding + "' WHERE ictag = '" + asset_tag + "'";
                command.ExecuteNonQuery();
                conn.Close();


                string userName;
                string password;
                userName = "******";
                password = "******";
                //use default binding and address from app.config
                // string securityToken = "xxxxxxxxxxxxxxx";
                LoginResult   currentLoginResult = null;
                SforceService sfdcBinding        = null;



                sfdcBinding                              = new SforceService();
                currentLoginResult                       = sfdcBinding.login(userName, password);
                sfdcBinding.Url                          = currentLoginResult.serverUrl;
                sfdcBinding.SessionHeaderValue           = new SessionHeader();
                sfdcBinding.SessionHeaderValue.sessionId = currentLoginResult.sessionId;
                var update_case = new Case();

                update_case.RCI_Partner_Origin__c = rci;
                update_case.Reviewed_by_Production__cSpecified = true;
                update_case.Reviewed_by_Production__c          = true;
                update_case.Id = id;
                update_case.Production_Findings__c = finding;



                SaveResult[] saveResults = sfdcBinding.update(new sObject[] { update_case });


                if (saveResults[0].success)
                {
                    message = "The update of Lead ID " + saveResults[0].id + " was succesful";
                }
                else
                {
                    message = "There was an error updating the Lead. The error returned was " + saveResults[0].errors[0].message;
                }
            }
            catch (Exception e)
            {
                message = e.Message;
                conn.Close();
            }

            return(message);
        }
Exemple #6
0
        public bool update_rma(string rma_num, string finding)
        {
            bool   sucessful = false;
            string userName;
            string password;

            userName = "******";
            password = "******";
            //use default binding and address from app.config
            // string securityToken = "xxxxxxxxxxxxxxx";
            LoginResult   currentLoginResult = null;
            SforceService sfdcBinding        = null;

            var edit_case = (from t in db.rma where t.rma_number == rma_num select t).FirstOrDefault();

            using (var db = new db_a094d4_icdbEntities1())
            {
                db.Database.ExecuteSqlCommand("Update rma set production_finding = '" + finding + "' where rma_number ='" + rma_num + "'");
            }


            sfdcBinding                              = new SforceService();
            currentLoginResult                       = sfdcBinding.login(userName, password);
            sfdcBinding.Url                          = currentLoginResult.serverUrl;
            sfdcBinding.SessionHeaderValue           = new SessionHeader();
            sfdcBinding.SessionHeaderValue.sessionId = currentLoginResult.sessionId;
            var update_case = new Case();

            update_case.Reviewed_by_Production__c          = true;
            update_case.Reviewed_by_Production__cSpecified = true;
            update_case.Id = edit_case.id;
            update_case.Production_Findings__c = finding;



            SaveResult[] saveResults = sfdcBinding.update(new sObject[] { update_case });

            string result = "";

            if (saveResults[0].success)
            {
                sucessful = true;
                result    = "The update of Lead ID " + saveResults[0].id + " was succesful";
            }
            else
            {
                sucessful = false;
                result    = "There was an error updating the Lead. The error returned was " + saveResults[0].errors[0].message;
            }



            return(sucessful);
        }
Exemple #7
0
        public bool UpdateSalesForceColumnValue <TColumnType>(string accountName, TColumnType newValue, string columnName, string accountPropertyName = null)
        {
            try
            {
                var selectColumnNames = new List <string> {
                    columnName
                };

                accountName = accountName.Replace("\"", "'");
                var filterClause = string.Format("Name = {0}", accountName);

                var queryResult = ExecuteSelectQuery(filterClause, selectColumnNames);

                if (queryResult != null && queryResult.records != null && queryResult.records.Length > 0)
                {
                    sObject[] records = queryResult.records;
                    var       account = (Account)records[0];


                    accountPropertyName = accountPropertyName ?? columnName;
                    var accountType     = account.GetType();
                    var accountProperty = accountType.GetProperty(accountPropertyName);

                    if (accountProperty != null)
                    {
                        accountProperty.SetValue(account, newValue, null);
                        sObject[] updatedRecords = { account };
                        _salesforceService.update(updatedRecords);
                    }
                }
                return(true);
            }
            catch (Exception exception)
            {
                throw new Exception("There was an error updating values on sales force.")
                      {
                          Source = exception.Source
                      };
            }
        }
        /// <summary>
        /// Updates Salesforce object.
        /// </summary>
        /// <param name="objectTypeName">Object type name.</param>
        /// <param name="values">Object values.</param>
        /// <returns>Operation result.</returns>
        public bool UpdateObject(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.update
                                                   (
                            new sObject[] { Constructor.ConstructSObject(objectTypeName, values) }
                                                   );

                        result = ((saveResults.Length > 0) && (saveResults[0].success));
                    }
                    else
                    {
                        throw (new InvalidOperationException(Errors.ERR_ID_FIELD_IS_NOT_SET));
                    }
                }
                else
                {
                    throw (new InvalidOperationException(Errors.ERR_FIELDS_ARE_EMPTY));
                }
            }

            return(result);
        }
Exemple #9
0
        public static void ChangePassword(SforceService _binding, string Id, string NewPassword)
        {
            Account _account = new Account();

            _account.Id = Id;
            _account.BRGCaseMail_Password__c = NewPassword;

            //call update passing an array of object

            // assuming that you've already established an enterprise WSDL binding

            SaveResult[] saveResults = _binding.update(
                new sObject[] { _account });
        }
Exemple #10
0
        public void UpdateLeadEvent(Common.SforceServices.Event evnt)
        {
            SforceService SfdcBinding = SalesForceSession();

            SaveResult[] results = null;
            try
            {
                results = SfdcBinding.update(new Event[] {
                    evnt
                });
            }
            catch (Exception ce)
            {
            }
        }
Exemple #11
0
        public void UpdateLeadeTask(Task task)
        {
            SforceService SfdcBinding = SalesForceSession();

            SaveResult[] results = null;
            try
            {
                results = SfdcBinding.update(new Task[] {
                    task
                });
            }
            catch (Exception ce)
            {
            }
        }
Exemple #12
0
        public static void UpdateStatusToFresh(SforceService _binding, string LeadID)
        {
            Dealer_Lead__c application = new Dealer_Lead__c();

            application.Id = LeadID;
            application.BRGCaseMail_Lead_Status__c                    = "FRESH";
            application.BRGCaseMail_Resend_via_Email_Text__c          = false;
            application.BRGCaseMail_Resend_via_Email_Text__cSpecified = true;

            //call update passing an array of object

            // assuming that you've already established an enterprise WSDL binding

            SaveResult[] saveResults = _binding.update(
                new sObject[] { application });
        }
Exemple #13
0
        public static void UpdateLastViewedAndStatus(SforceService _binding, string Status, string LeadID)
        {
            Dealer_Lead__c application = new Dealer_Lead__c();

            application.Id = LeadID;
            application.BRGCaseMail_Lead_Status__c          = Status;
            application.BRGCaseMail_Last_Viewed__c          = DateTime.Now;
            application.BRGCaseMail_Last_Viewed__cSpecified = true;

            //call update passing an array of object

            // assuming that you've already established an enterprise WSDL binding

            SaveResult[] saveResults = _binding.update(
                new sObject[] { application });
        }
Exemple #14
0
        public void UpateSalesForceQualifiedAmbassador(Ambassador__c QualifiedAmbassador)
        {
            SforceService SfdcBinding = SalesForceSession();

            Ambassador__c sfdcQualifiedAmbassador = new Ambassador__c();


            if (QualifiedAmbassador.Available_To_Receive_Leads__cSpecified)
            {
                sfdcQualifiedAmbassador = QualifiedAmbassador;
                sfdcQualifiedAmbassador.Available_To_Receive_Leads__c          = true;
                sfdcQualifiedAmbassador.Available_To_Receive_Leads__cSpecified = true;
            }
            else
            {
                sfdcQualifiedAmbassador.Id                                     = QualifiedAmbassador.Id;
                sfdcQualifiedAmbassador.Name                                   = QualifiedAmbassador.Name;
                sfdcQualifiedAmbassador.Zip_Code__c                            = QualifiedAmbassador.Zip_Code__c;
                sfdcQualifiedAmbassador.Q_Ambassador_Email__c                  = QualifiedAmbassador.Q_Ambassador_Email__c;
                sfdcQualifiedAmbassador.Available_To_Receive_Leads__c          = false;
                sfdcQualifiedAmbassador.Available_To_Receive_Leads__cSpecified = true;
            }
            try
            {
                //Campaign compaign = new Campaign();
                //compaign.Name="IndiaHicks";
                //sfdcLead.c = compaign;

                SaveResult[] saveResults = SfdcBinding.update(new sObject[] { sfdcQualifiedAmbassador });
                if (saveResults[0].success)
                {
                    string Id = "";
                    Id = saveResults[0].id;
                }
                else
                {
                    string result = "";
                    result = saveResults[0].errors[0].message;
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemple #15
0
        public static void UpdateApplicationStatusAndGrossProfit(SforceService _binding, double _grossProfit, string Status, string LeadID)
        {
            Dealer_Lead__c application = new Dealer_Lead__c();

            application.Id = LeadID;

            if (_grossProfit > 0)
            {
                application.BRGCaseMail_Gross_Profit__c          = _grossProfit;
                application.BRGCaseMail_Gross_Profit__cSpecified = true;
            }

            application.BRGCaseMail_Lead_Status__c = Status;

            //call update passing an array of object

            // assuming that you've already established an enterprise WSDL binding

            SaveResult[] saveResults = _binding.update(
                new sObject[] { application });
        }
        ///<summary>
        ///Update any sObject such as Opportunity, Account, CustomObject__c
        ///</summary>
        ///<param name="model">
        ///model.Id = "SalesForceId"
        ///model.Type = "Account"
        ///model.Fields = new List(ElementField)(){ ElementField ={Key ="Name", Value = "My new Account Name"} etc.  }
        ///</param>
        ///<returns></returns>
        public SaveResult[] UpdateElement(UpdateSObject 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.Id   = model.Id;
            element.Any  = fields;

            return(_binding
                   .update(new sObject[] { element }));
        }
Exemple #17
0
        public ActionResult Update()
        {
            Product2 updateProduct = new Product2();

            updateProduct.Id   = "01t28000004sWTyAAM";
            updateProduct.Name = "Rohit Behera";

            SaveResult[] updatedResults = sfdcBinding.update(new sObject[] { updateProduct });

            if (updatedResults[0].success)
            {
                string id = updatedResults[0].id;
                Response.Write("<br/>ID:" + id);
                Response.Write("Name:<br/>" + updateProduct.Name);
                Response.Write("<br/>UPDATE Product Successfully!!!");
            }
            else
            {
                string result = updatedResults[0].errors[0].message;
                Response.Write("<br/>ERROR:" + result);
            }

            return(View("Index"));
        }
        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);
                }
            }
        }
Exemple #19
0
        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);
        }
Exemple #20
0
        public void UpdateSalesForceQualifiedAmbassadors()
        {
            SforceService SfdcBinding = SalesForceSession();
            QueryResult   qr          = CurrentSalesForceQualifiedAmbassadorslist();

            Common.SforceServices.sObject[] records = qr.records;
            if (records == null)
            {
                return;
            }
            // 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 (Ambassador__c node in records)
            {
                QualifiedAmbassadors Customer = customers.Where(s => s.CustomerID == int.Parse(node.AmbassadorID__c)).FirstOrDefault();
                if (Customer.CustomerID == 0)
                {
                    break;
                }
                node.Name = Customer.FirstName + " " + Customer.LastName;
                if (!string.IsNullOrEmpty(Customer.JoinDate))
                {
                    try
                    {
                        node.JoinDate__c = DateTime.Parse(Customer.JoinDate);
                    }
                    catch (Exception) { }
                }
                if (!string.IsNullOrEmpty(Customer.LeaveDate))
                {
                    try
                    {
                        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.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.update(list.ToArray());
                        if (saveResults[0].success)
                        {
                            string Id = "";
                            Id = saveResults[0].id;
                        }
                        else
                        {
                            string result = "";
                            result = saveResults[0].errors[0].message;
                        }
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
Exemple #21
0
        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;
                obj.Id   = ID.Get(context);

                sObject[] objList = new sObject[1];
                objList[0] = obj;

                SaveResult[] results = SfdcBinding.update(objList);

                for (int j = 0; j < results.Length; j++)
                {
                    if (results[j].success)
                    {
                        RecordID.Set(context, "Record Updated for ID: " + 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 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);
                }
            }
        }