/// <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);
        }
Exemple #2
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;

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

            UpsertResult[] results = SfdcBinding.upsert(ExternalIDFieldName.Get(context), objList);


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