public async Task <IActionResult> UpdateContact([FromBody] ViewModels.Contact item, string id)
        {
            if (id != null && item.id != null && id != item.id)
            {
                return(BadRequest());
            }

            // get the contact
            Guid contactId = Guid.Parse(id);

            MicrosoftDynamicsCRMcontact contact = await _dynamicsClient.GetContactById(contactId);

            if (contact == null)
            {
                return(new NotFoundResult());
            }
            MicrosoftDynamicsCRMcontact patchContact = new MicrosoftDynamicsCRMcontact();

            patchContact.CopyValues(item);
            try
            {
                await _dynamicsClient.Contacts.UpdateAsync(contactId.ToString(), patchContact);
            }
            catch (HttpOperationException httpOperationException)
            {
                _logger.LogError(httpOperationException, "Error updating contact");
            }

            contact = await _dynamicsClient.GetContactById(contactId);

            return(new JsonResult(contact.ToViewModel()));
        }
        public async Task <IActionResult> GetContact(string id)
        {
            ViewModels.Contact result = null;

            if (!string.IsNullOrEmpty(id))
            {
                var contactId = Guid.Parse(id);
                // query the Dynamics system to get the contact record.
                var contact = await _dynamicsClient.GetContactById(contactId);

                if (contact != null)
                {
                    result = contact.ToViewModel();
                }
                else
                {
                    return(new NotFoundResult());
                }
            }
            else
            {
                return(BadRequest());
            }

            return(new JsonResult(result));
        }
        private async Task HandleVerifiedIndividualLogin(UserSettings userSettings, HttpContext context)
        {
            IConfiguration    _configuration     = (IConfiguration)context.RequestServices.GetService(typeof(IConfiguration));
            IDynamicsClient   _dynamicsClient    = (IDynamicsClient)context.RequestServices.GetService(typeof(IDynamicsClient));
            FileManagerClient _fileManagerClient = (FileManagerClient)context.RequestServices.GetService(typeof(FileManagerClient));

            ViewModels.Contact contact = new ViewModels.Contact();
            contact.CopyHeaderValues(context.Request.Headers);

            MicrosoftDynamicsCRMcontact savedContact = _dynamicsClient.Contacts.GetByKey(userSettings.ContactId);

            if (savedContact.Address1Line1 != null && savedContact.Address1Line1 != contact.address1_line1)
            {
                MicrosoftDynamicsCRMadoxioPreviousaddress prevAddress = new MicrosoftDynamicsCRMadoxioPreviousaddress
                {
                    AdoxioStreetaddress = savedContact.Address1Line1,
                    AdoxioProvstate     = savedContact.Address1Stateorprovince,
                    AdoxioCity          = savedContact.Address1City,
                    AdoxioCountry       = savedContact.Address1Country,
                    AdoxioPostalcode    = savedContact.Address1Postalcode,
                    ContactIdODataBind  = _dynamicsClient.GetEntityURI("contacts", savedContact.Contactid)
                };
                _dynamicsClient.Previousaddresses.Create(prevAddress);
            }

            _dynamicsClient.Contacts.Update(userSettings.ContactId, contact.ToModel());
        }
        public async Task <IActionResult> UpdateContact([FromBody] ViewModels.Contact item, string id)
        {
            /*
             * if (id != item.id)
             * {
             *  return BadRequest();
             * }
             */

            // get the legal entity.
            Guid contactId = new Guid(id);

            DataServiceCollection <Interfaces.Microsoft.Dynamics.CRM.Contact> ContactCollection = new DataServiceCollection <Interfaces.Microsoft.Dynamics.CRM.Contact>(_system);


            Interfaces.Microsoft.Dynamics.CRM.Contact contact = await _system.Contacts.ByKey(contactId).GetValueAsync();

            _system.UpdateObject(contact);
            // copy values over from the data provided
            contact.CopyValues(item);

            DataServiceResponse dsr = await _system.SaveChangesAsync(SaveChangesOptions.PostOnlySetProperties | SaveChangesOptions.BatchWithIndependentOperations);

            foreach (OperationResponse result in dsr)
            {
                if (result.StatusCode == 500) // error
                {
                    return(StatusCode(500, result.Error.Message));
                }
            }
            return(Json(contact.ToViewModel()));
        }
        public IActionResult GetContact(string id)
        {
            ViewModels.Contact result = null;

            if (!string.IsNullOrEmpty(id) && Guid.TryParse(id, out Guid contactId))
            {
                // query the Dynamics system to get the contact record.
                MicrosoftDynamicsCRMcontact contact = _dynamicsClient.GetContactById(contactId);

                if (contact != null)
                {
                    result = contact.ToViewModel();
                }
                else
                {
                    return(new NotFoundResult());
                }
            }
            else
            {
                return(BadRequest());
            }

            return(Json(result));
        }
Пример #6
0
        /// <summary>
        /// Convert a given voteQuestion to a ViewModel
        /// </summary>
        public static ViewModels.Contact ToViewModel(this MicrosoftDynamicsCRMcontact contact)
        {
            ViewModels.Contact result = null;
            if (contact != null)
            {
                result = new ViewModels.Contact();
                if (contact.Contactid != null)
                {
                    result.id = contact.Contactid;
                }

                result.name                                          = contact.Fullname;
                result.address1_city                                 = contact.Address1City;
                result.address1_country                              = contact.Address1Country;
                result.address1_line1                                = contact.Address1Line1;
                result.address1_postalcode                           = contact.Address1Postalcode;
                result.address1_stateorprovince                      = contact.Address1Stateorprovince;
                result.adoxio_canattendcompliancemeetings            = contact.AdoxioCanattendcompliancemeetings;
                result.adoxio_canobtainlicenceinfofrombranch         = contact.AdoxioCanobtainlicenceinfofrombranch;
                result.adoxio_canrepresentlicenseeathearings         = contact.AdoxioCanrepresentlicenseeathearings;
                result.adoxio_cansigngrocerystoreproofofsalesrevenue = contact.AdoxioCansigngrocerystoreproofofsalesrevenue;
                result.adoxio_cansignpermanentchangeapplications     = contact.AdoxioCansignpermanentchangeapplications;
                result.adoxio_cansigntemporarychangeapplications     = contact.AdoxioCansigntemporarychangeapplications;
                result.emailaddress1                                 = contact.Emailaddress1;
                result.firstname                                     = contact.Firstname;
                result.middlename                                    = contact.Middlename;
                result.lastname                                      = contact.Lastname;
                result.telephone1                                    = contact.Telephone1;
            }
            return(result);
        }
        public async Task <IActionResult> UpdateContact([FromBody] ViewModels.Contact item, string id)
        {
            if (!string.IsNullOrEmpty(id) && Guid.TryParse(id, out Guid contactId))
            {
                // get the contact
                MicrosoftDynamicsCRMcontact contact = _dynamicsClient.GetContactById(contactId);
                if (contact == null)
                {
                    return(new NotFoundResult());
                }
                MicrosoftDynamicsCRMcontact patchContact = new MicrosoftDynamicsCRMcontact();
                patchContact.CopyValues(item);
                try
                {
                    await _dynamicsClient.Contacts.UpdateAsync(contactId.ToString(), patchContact);
                }
                catch (OdataerrorException odee)
                {
                    _logger.LogError("Error updating contact");
                    _logger.LogError("Request:");
                    _logger.LogError(odee.Request.Content);
                    _logger.LogError("Response:");
                    _logger.LogError(odee.Response.Content);
                }

                contact = _dynamicsClient.GetContactById(contactId);
                return(Json(contact.ToViewModel()));
            }
            else
            {
                return(BadRequest());
            }
        }
Пример #8
0
        public async Task <bool> Add(ViewModels.Contact contact)
        {
            var mc        = new MailChimpManager(ConfigurationManager.AppSettings.Get("MailChimpApiKey"));
            var newMember = new Member
            {
                EmailAddress = contact.Email,
                StatusIfNew  = Status.Subscribed,
                Status       = Status.Subscribed,
            };

            newMember.MergeFields.Add("FNAME", contact.FirstName);
            newMember.MergeFields.Add("LNAME", contact.LastName);
            newMember.MergeFields.Add("F3NAME", contact.F3Name);
            newMember.MergeFields.Add("WORKOUT", contact.Workout);
            newMember.MergeFields.Add("EH", contact.EH);
            newMember.MergeFields.Add("TWITTER", contact.Twitter);
            newMember.MergeFields.Add("NOTES", " ");
            newMember.Interests.Add("eb2db7a8fd", true);


            try
            {
                var member = await mc.Members.AddOrUpdateAsync(ConfigurationManager.AppSettings["F3List"], newMember);
            }
            catch (MailChimpException mexp)
            {
                System.Diagnostics.Debug.WriteLine(mexp);
                throw;
            }
            return(true);
        }
Пример #9
0
        public async Task <bool> Add(ViewModels.Contact contact)
        {
            var mc    = new MailChimpManager(ConfigurationManager.AppSettings.Get("MailChimpApiKey"));
            var email = new EmailParameter
            {
                Email = contact.Email
            };
            var name = new NameVar
            {
                FirstName = contact.FirstName,
                LastName  = contact.LastName,
                F3Name    = contact.F3Name,
                Workout   = contact.Workout,
                EH        = contact.EH,
                Twitter   = contact.Twitter,
                Groupings = new List <Grouping>
                {
                    new Grouping
                    {
                        Id         = 4293,
                        GroupNames = new List <string>
                        {
                            "Newsletter"
                        }
                    }
                }
            };
            var result = mc.Subscribe(ConfigurationManager.AppSettings.Get("F3List"), email, name, doubleOptIn: false,
                                      sendWelcome: true);

            return(true);
        }
Пример #10
0
        public static void CopyValues(this MicrosoftDynamicsCRMcontact to, ViewModels.Contact from)
        {
            to.Emailaddress1 = from.email;
            to.Firstname     = from.firstName;

            to.Lastname = from.lastName;

            to.Telephone1 = from.phoneNumber;
        }
        public async Task <IActionResult> UpdateContact([FromBody] ViewModels.Contact item, string id)
        {
            if (id != null && item.id != null && id != item.id)
            {
                return(BadRequest());
            }
            var accessGranted = false;

            // get the contact



            // Allow access if the current user is the contact - for scenarios such as a worker update.
            if (DynamicsExtensions.CurrentUserIsContact(id, _httpContextAccessor))
            {
                accessGranted = true;
            }
            else
            {
                var contact = await _dynamicsClient.GetContactById(id);

                // get the related account and determine if the current user is allowed access
                if (!string.IsNullOrEmpty(contact?._parentcustomeridValue))
                {
                    var accountId = Guid.Parse(contact._parentcustomeridValue);
                    accessGranted =
                        DynamicsExtensions.CurrentUserHasAccessToAccount(accountId, _httpContextAccessor,
                                                                         _dynamicsClient);
                }
            }

            if (!accessGranted)
            {
                _logger.LogError(LoggingEvents.BadRequest, $"Current user has NO access to the contact record. Aborting update to contact {id} ");
                return(NotFound());
            }

            var patchContact = new MicrosoftDynamicsCRMcontact();

            patchContact.CopyValues(item);
            try
            {
                await _dynamicsClient.Contacts.UpdateAsync(id, patchContact);
            }
            catch (HttpOperationException httpOperationException)
            {
                _logger.LogError(httpOperationException, "Error updating contact");
            }

            var result = await _dynamicsClient.GetContactById(id);

            return(new JsonResult(result.ToViewModel()));
        }
Пример #12
0
        public static bool HasValue(this ViewModels.Contact contact)
        {
            bool result = contact != null &&
                          !(string.IsNullOrEmpty(contact.email) &&
                            string.IsNullOrEmpty(contact.firstName) &&
                            string.IsNullOrEmpty(contact.lastName) &&
                            string.IsNullOrEmpty(contact.id) &&
                            string.IsNullOrEmpty(contact.phoneNumber) &&
                            string.IsNullOrEmpty(contact.phoneNumberAlt) &&
                            string.IsNullOrEmpty(contact.title));

            return(result);
        }
Пример #13
0
        public static Contact ToModel(this ViewModels.Contact contact)
        {
            Contact result = null;

            if (contact != null)
            {
                result = new Contact();
                if (!string.IsNullOrEmpty(contact.id))
                {
                    result.Contactid = new Guid(contact.id);
                }
                result.Fullname      = contact.name;
                result.Emailaddress1 = contact.emailaddress1;
                result.Firstname     = contact.firstname;
                result.Lastname      = contact.lastname;

                result.Address1_city                                 = contact.address1_city;
                result.Address1_line1                                = contact.address1_line1;
                result.Address1_postalcode                           = contact.address1_postalcode;
                result.Address1_stateorprovince                      = contact.address1_stateorprovince;
                result.Adoxio_canattendcompliancemeetings            = contact.adoxio_canattendcompliancemeetings;
                result.Adoxio_canobtainlicenceinfofrombranch         = contact.adoxio_canobtainlicenceinfofrombranch;
                result.Adoxio_canrepresentlicenseeathearings         = contact.adoxio_canrepresentlicenseeathearings;
                result.Adoxio_cansigngrocerystoreproofofsalesrevenue = contact.adoxio_cansigngrocerystoreproofofsalesrevenue;
                result.Adoxio_cansignpermanentchangeapplications     = contact.adoxio_cansignpermanentchangeapplications;
                result.Adoxio_cansigntemporarychangeapplications     = contact.adoxio_cansigntemporarychangeapplications;
                result.Telephone1 = contact.telephone1;


                if (string.IsNullOrEmpty(result.Fullname) && (!string.IsNullOrEmpty(result.Firstname) || !string.IsNullOrEmpty(result.Lastname)))
                {
                    result.Fullname = "";
                    if (!string.IsNullOrEmpty(result.Firstname))
                    {
                        result.Fullname += result.Firstname;
                    }
                    if (!string.IsNullOrEmpty(result.Lastname))
                    {
                        if (!string.IsNullOrEmpty(result.Fullname))
                        {
                            result.Fullname += " ";
                        }
                        result.Fullname += result.Lastname;
                    }
                }
            }
            return(result);
        }
Пример #14
0
        /// <summary>
        /// Convert a given voteQuestion to a ViewModel
        /// </summary>
        public static ViewModels.Contact ToViewModel(this MicrosoftDynamicsCRMcontact contact)
        {
            ViewModels.Contact result = null;
            if (contact != null)
            {
                result = new ViewModels.Contact();
                if (contact.Contactid != null)
                {
                    result.id = contact.Contactid;
                }

                result.name                                          = contact.Fullname;
                result.address1_city                                 = contact.Address1City;
                result.address1_country                              = contact.Address1Country;
                result.address1_line1                                = contact.Address1Line1;
                result.jobTitle                                      = contact.Jobtitle;
                result.address1_postalcode                           = contact.Address1Postalcode;
                result.address1_stateorprovince                      = contact.Address1Stateorprovince;
                result.address2_city                                 = contact.Address2City;
                result.address2_country                              = contact.Address2Country;
                result.address2_line1                                = contact.Address2Line1;
                result.address2_postalcode                           = contact.Address2Postalcode;
                result.address2_stateorprovince                      = contact.Address2Stateorprovince;
                result.adoxio_canattendcompliancemeetings            = contact.AdoxioCanattendcompliancemeetings;
                result.adoxio_canobtainlicenceinfofrombranch         = contact.AdoxioCanobtainlicenceinfofrombranch;
                result.adoxio_canrepresentlicenseeathearings         = contact.AdoxioCanrepresentlicenseeathearings;
                result.adoxio_cansigngrocerystoreproofofsalesrevenue = contact.AdoxioCansigngrocerystoreproofofsalesrevenue;
                result.adoxio_cansignpermanentchangeapplications     = contact.AdoxioCansignpermanentchangeapplications;
                result.adoxio_cansigntemporarychangeapplications     = contact.AdoxioCansigntemporarychangeapplications;
                result.emailaddress1                                 = contact.Emailaddress1;
                result.firstname                                     = contact.Firstname;
                result.middlename                                    = contact.Middlename;
                result.lastname                                      = contact.Lastname;
                result.telephone1                                    = contact.Telephone1;
                result.Birthdate                                     = contact.Birthdate;
                result.BirthPlace                                    = contact.AdoxioBirthplace;
                result.Gender                                        = (ViewModels.Gender?)contact.AdoxioGendercode;
                result.MobilePhone                                   = contact.Mobilephone;
                result.PrimaryIdNumber                               = contact.AdoxioPrimaryidnumber;
                result.SecondaryIdNumber                             = contact.AdoxioSecondaryidnumber;
                result.PrimaryIdentificationType                     = (IdentificationType?)contact.AdoxioIdentificationtype;
                result.SecondaryIdentificationType                   = (IdentificationType?)contact.AdoxioSecondaryidentificationtype;
                result.IsWorker                                      = contact.AdoxioIsworker;
                result.SelfDisclosure                                = contact.AdoxioSelfdisclosure;
            }
            return(result);
        }
        public static void CopyHeaderValues(this ViewModels.Contact to, IHeaderDictionary headers)
        {
            string smgov_useremail       = headers["smgov_useremail"];
            string smgov_birthdate       = headers["smgov_birthdate"];
            string smgov_sex             = headers["smgov_sex"];
            string smgov_streetaddress   = headers["smgov_streetaddress"];
            string smgov_city            = headers["smgov_city"];
            string smgov_postalcode      = headers["smgov_postalcode"];
            string smgov_stateorprovince = headers["smgov_province"];
            string smgov_country         = headers["smgov_country"];
            string smgov_givenname       = headers["smgov_givenname"];
            string smgov_givennames      = headers["smgov_givennames"];
            string smgov_surname         = headers["smgov_surname"];

            to.address1_line1           = smgov_streetaddress;
            to.address1_postalcode      = smgov_postalcode;
            to.address1_city            = smgov_city;
            to.address1_stateorprovince = smgov_stateorprovince;
            to.address1_country         = smgov_country;

            if (!string.IsNullOrEmpty(smgov_givenname))
            {
                to.firstname = smgov_givenname;
            }

            if (!string.IsNullOrEmpty(smgov_givennames))
            {
                to.middlename = smgov_givennames.Replace(smgov_givenname, "").Trim();
            }

            if (!string.IsNullOrEmpty(smgov_surname))
            {
                to.lastname = smgov_surname;
            }
            if (!string.IsNullOrEmpty(smgov_useremail))
            {
                to.emailaddress1 = smgov_useremail;
            }
            if (!string.IsNullOrEmpty(smgov_sex))
            {
                to.Gender = (Gender)GetIntGenderCode(smgov_sex);
            }
            if (!string.IsNullOrEmpty(smgov_birthdate) && DateTimeOffset.TryParse(smgov_birthdate, out DateTimeOffset tempDate))
            {
                to.Birthdate = tempDate;
            }
        }
        public async Task <IActionResult> CreateContact([FromBody] ViewModels.Contact viewModel)
        {
            Interfaces.Microsoft.Dynamics.CRM.Contact item = viewModel.ToModel();

            // create a new contact.
            Interfaces.Microsoft.Dynamics.CRM.Contact contact = new Interfaces.Microsoft.Dynamics.CRM.Contact();

            // create a DataServiceCollection to add the record
            DataServiceCollection <Interfaces.Microsoft.Dynamics.CRM.Contact> ContactCollection = new DataServiceCollection <Interfaces.Microsoft.Dynamics.CRM.Contact>(_system);

            // add a new contact.
            ContactCollection.Add(contact);

            // changes need to made after the add in order for them to be saved.
            contact.CopyValues(item);

            // PostOnlySetProperties is used so that settings such as owner will get set properly by the dynamics server.

            DataServiceResponse dsr = await _system.SaveChangesAsync(SaveChangesOptions.PostOnlySetProperties | SaveChangesOptions.BatchWithSingleChangeset);

            foreach (OperationResponse result in dsr)
            {
                if (result.StatusCode == 500) // error
                {
                    return(StatusCode(500, result.Error.Message));
                }
            }
            contact.Contactid = dsr.GetAssignedId();
            // if we have not yet authenticated, then this is the new record for the user.
            string       temp         = _httpContextAccessor.HttpContext.Session.GetString("UserSettings");
            UserSettings userSettings = JsonConvert.DeserializeObject <UserSettings>(temp);

            if (userSettings.IsNewUserRegistration)
            {
                if (string.IsNullOrEmpty(userSettings.ContactId))
                {
                    userSettings.ContactId = contact.Contactid.ToString();
                    string userSettingsString = JsonConvert.SerializeObject(userSettings);
                    // add the user to the session.
                    _httpContextAccessor.HttpContext.Session.SetString("UserSettings", userSettingsString);
                }
            }

            return(Json(contact.ToViewModel()));
        }
Пример #17
0
 public static void CopyValues(this Contact to, ViewModels.Contact from)
 {
     to.Fullname                                      = from.name;
     to.Emailaddress1                                 = from.emailaddress1;
     to.Firstname                                     = from.firstname;
     to.Lastname                                      = from.lastname;
     to.Address1_city                                 = from.address1_city;
     to.Address1_line1                                = from.address1_line1;
     to.Address1_postalcode                           = from.address1_postalcode;
     to.Address1_stateorprovince                      = from.address1_stateorprovince;
     to.Adoxio_canattendcompliancemeetings            = from.adoxio_canattendcompliancemeetings;
     to.Adoxio_canobtainlicenceinfofrombranch         = from.adoxio_canobtainlicenceinfofrombranch;
     to.Adoxio_canrepresentlicenseeathearings         = from.adoxio_canrepresentlicenseeathearings;
     to.Adoxio_cansigngrocerystoreproofofsalesrevenue = from.adoxio_cansigngrocerystoreproofofsalesrevenue;
     to.Adoxio_cansignpermanentchangeapplications     = from.adoxio_cansignpermanentchangeapplications;
     to.Adoxio_cansigntemporarychangeapplications     = from.adoxio_cansigntemporarychangeapplications;
     to.Telephone1                                    = from.telephone1;
 }
Пример #18
0
 /// <summary>
 /// Convert a given voteQuestion to a ViewModel
 /// </summary>
 public static ViewModels.Contact ToViewModel(this MicrosoftDynamicsCRMcontact contact)
 {
     ViewModels.Contact result = null;
     if (contact != null)
     {
         result = new ViewModels.Contact();
         if (contact.Contactid != null)
         {
             result.id = contact.Contactid;
         }
         result.title          = contact.Jobtitle;
         result.email          = contact.Emailaddress1;
         result.firstName      = contact.Firstname;
         result.lastName       = contact.Lastname;
         result.phoneNumber    = contact.Telephone1;
         result.phoneNumberAlt = contact.Telephone2;
     }
     return(result);
 }
Пример #19
0
        public static void CopyHeaderValues(this ViewModels.Contact to, IHeaderDictionary headers)
        {
            string smgov_useremail       = headers["smgov_useremail"];
            string smgov_birthdate       = headers["smgov_birthdate"];
            string smgov_sex             = headers["smgov_sex"];
            string smgov_streetaddress   = headers["smgov_streetaddress"];
            string smgov_city            = headers["smgov_city"];
            string smgov_postalcode      = headers["smgov_postalcode"];
            string smgov_stateorprovince = headers["smgov_province"];
            string smgov_country         = headers["smgov_country"];
            string smgov_givenname       = headers["smgov_givenname"];
            string smgov_givennames      = headers["smgov_givennames"];
            string smgov_surname         = headers["smgov_surname"];

            to.address1_line1           = smgov_streetaddress;
            to.address1_postalcode      = smgov_postalcode;
            to.address1_city            = smgov_city;
            to.address1_stateorprovince = smgov_stateorprovince;
            to.address1_country         = smgov_country;

            if (!string.IsNullOrEmpty(smgov_givenname))
            {
                to.firstname = smgov_givenname;
            }

            if (!string.IsNullOrEmpty(smgov_givennames))
            {
                to.middlename = smgov_givennames;
            }

            if (!string.IsNullOrEmpty(smgov_surname))
            {
                to.lastname = smgov_surname;
            }
            if (!string.IsNullOrEmpty(smgov_useremail))
            {
                to.emailaddress1 = smgov_useremail;
            }
        }
        public async Task <IActionResult> UpdateContactByToken([FromBody] ViewModels.Contact item, string token)
        {
            if (token == null || item == null)
            {
                return(BadRequest());
            }

            // get the contact
            var contactId   = EncryptionUtility.DecryptStringHex(token, _encryptionKey);
            var contactGuid = Guid.Parse(contactId);

            var contact = await _dynamicsClient.GetContactById(contactGuid);

            if (contact == null)
            {
                return(new NotFoundResult());
            }
            var patchContact = new MicrosoftDynamicsCRMcontact();

            patchContact.CopyValues(item);
            try
            {
                await _dynamicsClient.Contacts.UpdateAsync(contactGuid.ToString(), patchContact);
            }
            catch (HttpOperationException httpOperationException)
            {
                _logger.LogError(httpOperationException, "Error updating contact");
            }

            foreach (var alias in item.Aliases)
            {
                CreateAlias(alias, contactId);
            }

            contact = await _dynamicsClient.GetContactById(contactGuid);

            return(new JsonResult(contact.ToViewModel()));
        }
Пример #21
0
        public static MicrosoftDynamicsCRMcontact ToModel(this ViewModels.Contact contact)
        {
            MicrosoftDynamicsCRMcontact result = null;

            if (contact != null)
            {
                result = new MicrosoftDynamicsCRMcontact();
                if (!string.IsNullOrEmpty(contact.id))
                {
                    result.Contactid = contact.id;
                }

                result.Emailaddress1 = contact.email;
                result.Firstname     = contact.firstName;
                result.Lastname      = contact.lastName;
                result.Telephone1    = contact.phoneNumber;
                result.Telephone2    = contact.phoneNumberAlt;
                result.Jobtitle      = contact.title;

                if (string.IsNullOrEmpty(result.Fullname) && (!string.IsNullOrEmpty(result.Firstname) || !string.IsNullOrEmpty(result.Lastname)))
                {
                    result.Fullname = "";
                    if (!string.IsNullOrEmpty(result.Firstname))
                    {
                        result.Fullname += result.Firstname;
                    }
                    if (!string.IsNullOrEmpty(result.Lastname))
                    {
                        if (!string.IsNullOrEmpty(result.Fullname))
                        {
                            result.Fullname += " ";
                        }
                        result.Fullname += result.Lastname;
                    }
                }
            }
            return(result);
        }
        public async Task <IActionResult> GetContact(string id)
        {
            ViewModels.Contact result = null;
            // query the Dynamics system to get the contact record.

            Guid?contactId = new Guid(id);

            Interfaces.Microsoft.Dynamics.CRM.Contact contact = null;
            if (contactId != null)
            {
                try
                {
                    contact = await _system.Contacts.ByKey(contactId).GetValueAsync();

                    result = contact.ToViewModel();
                }
                catch (Microsoft.OData.Client.DataServiceQueryException dsqe)
                {
                    return(new NotFoundResult());
                }
            }

            return(Json(result));
        }
Пример #23
0
        public async Task <ViewModels.Contact> AddContact(ViewModels.Contact contact)
        {
            var cSvc = new ContactsService("F3Test").Credentials;

            var rs = new RequestSettings("F3Test", Token.AccessToken);

            // AutoPaging results in automatic paging in order to retrieve all contacts
            rs.AutoPaging = true;
            var cr = new ContactsRequest(rs);

            var newEntry = new Contact
            {
                Name = new Name()
                {
                    FullName   = string.Format("{0} {1}", contact.FirstName, contact.LastName),
                    GivenName  = contact.FirstName,
                    FamilyName = contact.LastName,
                }
            };

            // Set the contact's name.
            // Set the contact's e-mail addresses.
            newEntry.Emails.Add(new EMail
            {
                Primary = true,
                Rel     = ContactsRelationships.IsHome,
                Address = contact.Email
            });

            // Insert the contact.
            var feedUri      = new Uri(ContactsQuery.CreateContactsUri("default"));
            var createdEntry = cr.Insert(feedUri, newEntry);

            contact.Id = createdEntry.Id;
            return(contact);
        }
        public async Task <IActionResult> CreateWorkerContact([FromBody] ViewModels.Contact item)
        {
            // get the current user.
            UserSettings userSettings = UserSettings.CreateFromHttpContext(_httpContextAccessor);

            // first check to see that we have the correct inputs.
            var contactSiteminderGuid = userSettings.SiteMinderGuid;

            if (contactSiteminderGuid == null || contactSiteminderGuid.Length == 0)
            {
                _logger.LogDebug(LoggingEvents.Error, "No Contact Siteminder Guid exernal id");
                throw new Exception("Error. No ContactSiteminderGuid exernal id");
            }

            // get the contact record.
            MicrosoftDynamicsCRMcontact userContact = null;

            // see if the contact exists.
            try
            {
                userContact = _dynamicsClient.GetActiveContactByExternalId(contactSiteminderGuid);
                if (userContact != null)
                {
                    throw new Exception("Contact already Exists");
                }
            }
            catch (HttpOperationException httpOperationException)
            {
                _logger.LogError(httpOperationException, "Error getting contact by Siteminder Guid.");
                throw new HttpOperationException("Error getting contact by Siteminder Guid");
            }

            // create a new contact.
            var contact = new MicrosoftDynamicsCRMcontact();
            var worker  = new MicrosoftDynamicsCRMadoxioWorker
            {
                AdoxioFirstname  = item.firstname,
                AdoxioMiddlename = item.middlename,
                AdoxioLastname   = item.lastname,
                AdoxioIsmanual   = 0 // 0 for false - is a portal user.
            };


            contact.CopyValues(item);
            // set the type to Retail Worker.
            contact.Customertypecode = 845280000;

            if (userSettings.NewWorker != null)
            {
                // get additional information from the service card headers.
                contact.CopyContactUserSettings(userSettings.NewContact);
                worker.CopyValues(userSettings.NewWorker);
            }

            //Default the country to Canada
            if (string.IsNullOrEmpty(contact.Address1Country))
            {
                contact.Address1Country = "Canada";
            }
            if (string.IsNullOrEmpty(contact.Address2Country))
            {
                contact.Address2Country = "Canada";
            }


            contact.AdoxioExternalid = DynamicsExtensions.GetServiceCardID(contactSiteminderGuid);

            try
            {
                worker.AdoxioContactId = contact;

                worker = await _dynamicsClient.Workers.CreateAsync(worker);

                contact = await _dynamicsClient.GetContactById(Guid.Parse(worker._adoxioContactidValue));
                await CreateSharepointDynamicsLink(worker);
            }
            catch (HttpOperationException httpOperationException)
            {
                _logger.LogError(httpOperationException, "Error updating contact");
                _logger.LogError(httpOperationException.Response.Content);

                //fail
                throw httpOperationException;
            }


            // if we have not yet authenticated, then this is the new record for the user.
            if (userSettings.IsNewUserRegistration)
            {
                userSettings.ContactId = contact.Contactid;

                // we can now authenticate.
                if (userSettings.AuthenticatedUser == null)
                {
                    var user = new User();
                    user.Active    = true;
                    user.ContactId = Guid.Parse(userSettings.ContactId);
                    user.UserType  = userSettings.UserType;
                    user.SmUserId  = userSettings.UserId;
                    userSettings.AuthenticatedUser = user;
                }

                userSettings.IsNewUserRegistration = false;

                var userSettingsString = JsonConvert.SerializeObject(userSettings);
                _logger.LogDebug("userSettingsString --> " + userSettingsString);

                // add the user to the session.
                _httpContextAccessor.HttpContext.Session.SetString("UserSettings", userSettingsString);
                _logger.LogDebug("user added to session. ");
            }
            else
            {
                _logger.LogDebug(LoggingEvents.Error, "Invalid user registration.");
                throw new Exception("Invalid user registration.");
            }

            return(new JsonResult(contact.ToViewModel()));
        }
        public static MicrosoftDynamicsCRMcontact ToModel(this ViewModels.Contact contact)
        {
            MicrosoftDynamicsCRMcontact result = null;

            if (contact != null)
            {
                result = new MicrosoftDynamicsCRMcontact();
                if (!string.IsNullOrEmpty(contact.id))
                {
                    result.Contactid = contact.id;
                }
                result.Fullname      = contact.name;
                result.Emailaddress1 = contact.emailaddress1;
                result.Firstname     = contact.firstname;
                result.Lastname      = contact.lastname;
                result.Middlename    = contact.middlename;
                result.Jobtitle      = contact.jobTitle;

                result.Address1City                                 = contact.address1_city;
                result.Address1Country                              = contact.address1_country;
                result.Address1Line1                                = contact.address1_line1;
                result.Address1Postalcode                           = contact.address1_postalcode;
                result.Address1Stateorprovince                      = contact.address1_stateorprovince;
                result.AdoxioCanattendcompliancemeetings            = contact.adoxio_canattendcompliancemeetings;
                result.AdoxioCanobtainlicenceinfofrombranch         = contact.adoxio_canobtainlicenceinfofrombranch;
                result.AdoxioCanrepresentlicenseeathearings         = contact.adoxio_canrepresentlicenseeathearings;
                result.AdoxioCansigngrocerystoreproofofsalesrevenue = contact.adoxio_cansigngrocerystoreproofofsalesrevenue;
                result.AdoxioCansignpermanentchangeapplications     = contact.adoxio_cansignpermanentchangeapplications;
                result.AdoxioCansigntemporarychangeapplications     = contact.adoxio_cansigntemporarychangeapplications;
                result.Telephone1 = contact.telephone1;

                result.AdoxioCascomplete                = (int?)contact.CasComplete;
                result.AdoxioCasdatesubmitted           = contact.CasDateSubmitted;
                result.AdoxioConsentvalidated           = (int?)contact.CasConsentValidated;
                result.AdoxioConsentvalidatedexpirydate = contact.CasConsentValidatedExpiryDate;

                result.AdoxioPhslivesincanada                      = (int?)contact.PhsLivesInCanada;
                result.AdoxioPhshaslivedincanada                   = (int?)contact.PhsHasLivedInCanada;
                result.AdoxioPhsexpired                            = (int?)contact.PhsExpired;
                result.AdoxioPhscomplete                           = (int?)contact.PhsComplete;
                result.AdoxioPhsconnectionstootherlicences         = (int?)contact.PhsConnectionsToOtherLicences;
                result.AdoxioPhscanadiandrugalchoholdrivingoffence = (int?)contact.PhsCanadianDrugAlchoholDrivingOffence;
                result.AdoxioPhsdatesubmitted                      = contact.PhsDateSubmitted;
                result.AdoxioPhsforeigndrugalchoholoffence         = (int?)contact.PhsForeignDrugAlchoholOffence;
                result.AdoxioPhsconnectionsdetails                 = contact.PhsConnectionsDetails;

                result.AdoxioPhsexclusivemfg             = (int?)contact.PhsExclusiveMFG;
                result.AdoxioPhsexclusivedetails         = contact.phsExclusiveDetails;
                result.AdoxioPhsfinancialint             = (int?)contact.phsFinancialInt;
                result.AdoxioPhsfinancialinterestdetails = contact.phsFinancialIntDetails;
                result.AdoxioPhsprofitagreement          = (int?)contact.phsProfitAgreement;
                result.AdoxioPhsprofitagreementdetails   = contact.phsProfitAgreementDetails;


                if (string.IsNullOrEmpty(result.Fullname) && (!string.IsNullOrEmpty(result.Firstname) || !string.IsNullOrEmpty(result.Lastname)))
                {
                    result.Fullname = "";
                    if (!string.IsNullOrEmpty(result.Firstname))
                    {
                        result.Fullname += result.Firstname;
                    }
                    if (!string.IsNullOrEmpty(result.Lastname))
                    {
                        if (!string.IsNullOrEmpty(result.Fullname))
                        {
                            result.Fullname += " ";
                        }
                        result.Fullname += result.Lastname;
                    }
                }
            }
            return(result);
        }
        public async Task <IActionResult> CreateContact([FromBody] ViewModels.Contact item)
        {
            // get the current user.
            UserSettings userSettings = UserSettings.CreateFromHttpContext(_httpContextAccessor);

            // first check to see that a contact exists.
            var contactSiteminderGuid = userSettings.SiteMinderGuid;

            if (contactSiteminderGuid == null || contactSiteminderGuid.Length == 0)
            {
                _logger.LogDebug(LoggingEvents.Error, "No Contact Siteminder Guid exernal id");
                throw new Exception("Error. No ContactSiteminderGuid exernal id");
            }

            // get the contact record.
            MicrosoftDynamicsCRMcontact userContact = null;

            // see if the contact exists.
            try
            {
                userContact = _dynamicsClient.GetActiveContactByExternalId(contactSiteminderGuid);
                if (userContact != null)
                {
                    throw new Exception("Contact already Exists");
                }
            }
            catch (HttpOperationException httpOperationException)
            {
                _logger.LogError(httpOperationException, "Error getting contact by Siteminder Guid.");
                throw new HttpOperationException("Error getting contact by Siteminder Guid");
            }

            // create a new contact.
            var contact = new MicrosoftDynamicsCRMcontact();

            contact.CopyValues(item);


            if (userSettings.IsNewUserRegistration)
            {
                // get additional information from the service card headers.
                contact.CopyHeaderValues(_httpContextAccessor);
            }

            contact.AdoxioExternalid = DynamicsExtensions.GetServiceCardID(contactSiteminderGuid);
            try
            {
                contact = await _dynamicsClient.Contacts.CreateAsync(contact);
            }
            catch (HttpOperationException httpOperationException)
            {
                _logger.LogError(httpOperationException, "Error creating contact. ");
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Unknown error creating contact.");
            }

            // if we have not yet authenticated, then this is the new record for the user.
            if (userSettings.IsNewUserRegistration)
            {
                userSettings.ContactId = contact.Contactid;

                // we can now authenticate.
                if (userSettings.AuthenticatedUser == null)
                {
                    var user = new User();
                    user.Active    = true;
                    user.ContactId = Guid.Parse(userSettings.ContactId);
                    user.UserType  = userSettings.UserType;
                    user.SmUserId  = userSettings.UserId;
                    userSettings.AuthenticatedUser = user;
                }

                userSettings.IsNewUserRegistration = false;

                var userSettingsString = JsonConvert.SerializeObject(userSettings);
                _logger.LogDebug("userSettingsString --> " + userSettingsString);

                // add the user to the session.
                _httpContextAccessor.HttpContext.Session.SetString("UserSettings", userSettingsString);
                _logger.LogDebug("user added to session. ");
            }
            else
            {
                _logger.LogDebug(LoggingEvents.Error, "Invalid user registration.");
                throw new Exception("Invalid user registration.");
            }

            return(new JsonResult(contact.ToViewModel()));
        }
        public async Task <IActionResult> CreateWorkerContact([FromBody] ViewModels.Contact item)
        {
            // get UserSettings from the session
            string       temp         = _httpContextAccessor.HttpContext.Session.GetString("UserSettings");
            UserSettings userSettings = JsonConvert.DeserializeObject <UserSettings>(temp);

            // first check to see that a contact exists.
            string contactSiteminderGuid = userSettings.SiteMinderGuid;

            if (contactSiteminderGuid == null || contactSiteminderGuid.Length == 0)
            {
                _logger.LogError(LoggingEvents.Error, "No Contact Siteminder Guid exernal id");
                throw new Exception("Error. No ContactSiteminderGuid exernal id");
            }

            // get the contact record.
            MicrosoftDynamicsCRMcontact userContact = null;

            // see if the contact exists.
            try
            {
                userContact = _dynamicsClient.GetContactByExternalId(contactSiteminderGuid);
                if (userContact != null)
                {
                    throw new Exception("Contact already Exists");
                }
            }
            catch (OdataerrorException odee)
            {
                _logger.LogError(LoggingEvents.Error, "Error getting contact by Siteminder Guid.");
                _logger.LogError("Request:");
                _logger.LogError(odee.Request.Content);
                _logger.LogError("Response:");
                _logger.LogError(odee.Response.Content);
                throw new OdataerrorException("Error getting contact by Siteminder Guid");
            }

            // create a new contact.
            MicrosoftDynamicsCRMcontact      contact = new MicrosoftDynamicsCRMcontact();
            MicrosoftDynamicsCRMadoxioWorker worker  = new MicrosoftDynamicsCRMadoxioWorker()
            {
                AdoxioFirstname  = item.firstname,
                AdoxioMiddlename = item.middlename,
                AdoxioLastname   = item.lastname
            };

            contact.CopyValues(item);

            if (userSettings.IsNewUserRegistration && userSettings.NewWorker != null)
            {
                // get additional information from the service card headers.
                contact.CopyValues(userSettings.NewContact);
                worker.CopyValues(userSettings.NewWorker);
            }

            contact.AdoxioExternalid = DynamicsExtensions.GetServiceCardID(contactSiteminderGuid);

            try
            {
                worker.AdoxioContactId = contact;

                worker = await _dynamicsClient.Workers.CreateAsync(worker);

                contact = await _dynamicsClient.GetContactById(Guid.Parse(worker._adoxioContactidValue));
            }
            catch (OdataerrorException odee)
            {
                _logger.LogError("Error updating contact");
                _logger.LogError("Request:");
                _logger.LogError(odee.Request.Content);
                _logger.LogError("Response:");
                _logger.LogError(odee.Response.Content);
            }


            // if we have not yet authenticated, then this is the new record for the user.
            if (userSettings.IsNewUserRegistration)
            {
                userSettings.ContactId = contact.Contactid.ToString();

                // we can now authenticate.
                if (userSettings.AuthenticatedUser == null)
                {
                    Models.User user = new Models.User();
                    user.Active    = true;
                    user.ContactId = Guid.Parse(userSettings.ContactId);
                    user.UserType  = userSettings.UserType;
                    user.SmUserId  = userSettings.UserId;
                    userSettings.AuthenticatedUser = user;
                }

                userSettings.IsNewUserRegistration = false;

                string userSettingsString = JsonConvert.SerializeObject(userSettings);
                _logger.LogDebug("userSettingsString --> " + userSettingsString);

                // add the user to the session.
                _httpContextAccessor.HttpContext.Session.SetString("UserSettings", userSettingsString);
                _logger.LogDebug("user added to session. ");
            }
            else
            {
                _logger.LogError(LoggingEvents.Error, "Invalid user registration.");
                throw new Exception("Invalid user registration.");
            }

            return(Json(contact.ToViewModel()));
        }
        public async System.Threading.Tasks.Task TestCRUD()
        {
            string initialName = "TestFirst";
            string changedName = "ChangedName";
            string service     = "contact";

            // register and login as our first user
            var loginUser1 = randomNewUserName("TestServiceCardUser", 6);

            await ServiceCardLogin(loginUser1, loginUser1);

            // C - Create

            //First create the contact
            var request = new HttpRequestMessage(HttpMethod.Post, $"/api/{service}/worker");

            ViewModels.Contact contactVM = new ViewModels.Contact()
            {
                firstname  = initialName,
                middlename = "TestMiddle",
                lastname   = "TestLst"
            };

            string jsonString = JsonConvert.SerializeObject(contactVM);

            request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");

            var response = await _client.SendAsync(request);

            jsonString = await response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();

            contactVM = JsonConvert.DeserializeObject <ViewModels.Contact>(jsonString);

            // R -Read
            request  = new HttpRequestMessage(HttpMethod.Get, $"/api/worker/{contactVM.id}");
            response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();
            jsonString = await response.Content.ReadAsStringAsync();

            var workerVM = JsonConvert.DeserializeObject <ViewModels.Worker>(jsonString);

            Assert.NotNull(workerVM?.id);



            // U - Update
            workerVM.firstname = changedName;
            request            = new HttpRequestMessage(HttpMethod.Put, "/api/worker/" + workerVM.id)
            {
                Content = new StringContent(JsonConvert.SerializeObject(workerVM), Encoding.UTF8, "application/json")
            };
            response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();

            // verify that the update persisted.
            request  = new HttpRequestMessage(HttpMethod.Get, "/api/worker/" + contactVM.id);
            response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();

            jsonString = await response.Content.ReadAsStringAsync();

            var worker2 = JsonConvert.DeserializeObject <ViewModels.Worker>(jsonString);

            Assert.Equal(worker2.firstname, changedName);

            // D - Delete

            request  = new HttpRequestMessage(HttpMethod.Post, "/api/worker/" + workerVM.id + "/delete");
            response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();

            // second delete should return a 404.
            request  = new HttpRequestMessage(HttpMethod.Post, "/api/worker/" + workerVM.id + "/delete");
            response = await _client.SendAsync(request);

            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);

            // should get a 404 if we try a get now.
            request  = new HttpRequestMessage(HttpMethod.Get, "/api/worker/" + contactVM.id);
            response = await _client.SendAsync(request);

            jsonString = await response.Content.ReadAsStringAsync();

            var worker3 = JsonConvert.DeserializeObject <ViewModels.Worker>(jsonString);

            Assert.Null(worker3);
            await Logout();
        }
Пример #29
0
        public async System.Threading.Tasks.Task TestCRUD()
        {
            string initialAddress = "645 Tyee Road";
            string changedAddress = "123 ChangedAddress Ave";
            string service        = "contact";

            // register and login as our first user
            var loginUser1 = randomNewUserName("TestServiceCardUser", 6);

            await ServiceCardLogin(loginUser1, loginUser1);

            // C - Create

            //First create the contact
            var request = new HttpRequestMessage(HttpMethod.Post, $"/api/{service}/worker");

            ViewModels.Contact contactVM = new ViewModels.Contact()
            {
                firstname  = "TestFirst",
                middlename = "TestMiddle",
                lastname   = "TestLst"
            };

            string jsonString = JsonConvert.SerializeObject(contactVM);

            request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");

            var response = await _client.SendAsync(request);

            jsonString = await response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();

            contactVM = JsonConvert.DeserializeObject <ViewModels.Contact>(jsonString);

            // Get the worker
            request  = new HttpRequestMessage(HttpMethod.Get, $"/api/worker/contact/{contactVM.id}");
            response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();
            jsonString = await response.Content.ReadAsStringAsync();

            var workerVM = JsonConvert.DeserializeObject <List <ViewModels.Worker> >(jsonString).FirstOrDefault();

            var addressVM = new ViewModels.PreviousAddress()
            {
                streetaddress = initialAddress,
                contactId     = contactVM.id,
                workerId      = workerVM.id
            };

            request         = new HttpRequestMessage(HttpMethod.Post, $"/api/PreviousAddress");
            jsonString      = JsonConvert.SerializeObject(addressVM);
            request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
            response        = await _client.SendAsync(request);

            jsonString = await response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();
            addressVM = JsonConvert.DeserializeObject <ViewModels.PreviousAddress>(jsonString);


            // R - Read

            request  = new HttpRequestMessage(HttpMethod.Get, "/api/PreviousAddress/by-contactid/" + contactVM.id);
            response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();

            jsonString = await response.Content.ReadAsStringAsync();

            var address2 = (JsonConvert.DeserializeObject <List <ViewModels.PreviousAddress> >(jsonString)).FirstOrDefault();;

            Assert.Equal(address2.id, addressVM.id);


            // U - Update
            address2.streetaddress = changedAddress;
            request = new HttpRequestMessage(HttpMethod.Put, "/api/PreviousAddress/" + address2.id)
            {
                Content = new StringContent(JsonConvert.SerializeObject(address2), Encoding.UTF8, "application/json")
            };
            response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();

            // verify that the update persisted.
            request  = new HttpRequestMessage(HttpMethod.Get, "/api/PreviousAddress/by-contactid/" + contactVM.id);
            response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();

            jsonString = await response.Content.ReadAsStringAsync();

            var address3 = (JsonConvert.DeserializeObject <List <ViewModels.PreviousAddress> >(jsonString)).FirstOrDefault();;

            Assert.Equal(changedAddress, address3.streetaddress);

            // D - Delete

            request  = new HttpRequestMessage(HttpMethod.Post, "/api/PreviousAddress/" + addressVM.id + "/delete");
            response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();

            // second delete should return a 404.
            request  = new HttpRequestMessage(HttpMethod.Post, "/api/PreviousAddress/" + addressVM.id + "/delete");
            response = await _client.SendAsync(request);

            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);

            // should get a 404 if we try a get now.
            request  = new HttpRequestMessage(HttpMethod.Get, "/api/PreviousAddress/by-contactid/" + contactVM.id);
            response = await _client.SendAsync(request);

            jsonString = await response.Content.ReadAsStringAsync();

            var address4 = (JsonConvert.DeserializeObject <List <ViewModels.PreviousAddress> >(jsonString)).FirstOrDefault();

            Assert.Null(address4);
            await Logout();
        }
        public async System.Threading.Tasks.Task TestAdditionalContact()
        {
            string initialName           = "InitialName";
            string changedName           = "ChangedName";
            string initialPhoneNumber    = "1231231234";
            string changedPhoneNumber    = "987654321";
            string initialBusinessNumber = "123456789";
            string changedBusinessNumber = "987654321";

            string service = "account";

            // register and login as our first user
            var loginUser1 = randomNewUserName("TestAccountUser", 6);

            await Login(loginUser1);

            // C - Create
            var request = new HttpRequestMessage(HttpMethod.Post, "/api/" + service);


            ViewModels.Contact contact = new ViewModels.Contact()
            {
                firstName      = initialName,
                lastName       = initialName,
                title          = initialName,
                phoneNumber    = initialPhoneNumber,
                phoneNumberAlt = initialPhoneNumber,
                email          = initialName,
            };

            ViewModels.Account viewmodel_account = new ViewModels.Account()
            {
                businessType             = "PublicCorporation",
                businessLegalName        = initialName,
                businessDBAName          = initialName,
                businessNumber           = initialBusinessNumber,
                description              = initialName,
                businessEmail            = initialName,
                businessPhoneNumber      = initialName,
                mailingAddressName       = initialName,
                mailingAddressLine1      = initialName,
                mailingAddressCity       = initialName,
                mailingAddressCountry    = initialName,
                mailingAddressProvince   = initialName,
                mailingAddressPostalCode = initialName,
                additionalContact        = contact
            };

            string jsonString = JsonConvert.SerializeObject(viewmodel_account);

            request.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");

            var response = await _client.SendAsync(request);

            jsonString = await response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();

            // parse as JSON.
            ViewModels.Account responseViewModel = JsonConvert.DeserializeObject <ViewModels.Account>(jsonString);

            // verify the record.
            Assert.NotNull(responseViewModel.additionalContact);

            Guid id = new Guid(responseViewModel.id);

            //String strid = responseViewModel.externalId;
            //Assert.Equal(strid, viewmodel_account.externalId);

            // R - Read

            request  = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/" + id);
            response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();

            jsonString = await response.Content.ReadAsStringAsync();

            responseViewModel = JsonConvert.DeserializeObject <ViewModels.Account>(jsonString);

            // verify the record.

            Assert.NotNull(responseViewModel.additionalContact);
            Assert.Equal(initialName, responseViewModel.additionalContact.firstName);
            Assert.Equal(initialName, responseViewModel.additionalContact.lastName);
            Assert.Equal(initialName, responseViewModel.additionalContact.title);
            Assert.Equal(initialPhoneNumber, responseViewModel.additionalContact.phoneNumber);
            Assert.Equal(initialPhoneNumber, responseViewModel.additionalContact.phoneNumberAlt);
            Assert.Equal(initialName, responseViewModel.additionalContact.email);

            // U - Update
            ViewModels.Contact changedContact = new ViewModels.Contact()
            {
                id             = responseViewModel.additionalContact.id,
                firstName      = changedName,
                lastName       = changedName,
                title          = changedName,
                phoneNumber    = changedPhoneNumber,
                phoneNumberAlt = changedPhoneNumber,
                email          = changedName
            };

            ViewModels.Account changedAccount = new ViewModels.Account()
            {
                businessType             = "PublicCorporation",
                businessLegalName        = changedName,
                businessDBAName          = changedName,
                businessNumber           = changedBusinessNumber,
                description              = changedName,
                businessEmail            = changedName,
                businessPhoneNumber      = changedName,
                mailingAddressName       = changedName,
                mailingAddressLine1      = changedName,
                mailingAddressCity       = changedName,
                mailingAddressCountry    = changedName,
                mailingAddressProvince   = changedName,
                mailingAddressPostalCode = changedName,
                additionalContact        = changedContact
            };

            request = new HttpRequestMessage(HttpMethod.Put, "/api/" + service + "/" + id)
            {
                Content = new StringContent(JsonConvert.SerializeObject(changedAccount), Encoding.UTF8, "application/json")
            };
            response = await _client.SendAsync(request);

            jsonString = await response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();

            // verify that the update persisted.
            responseViewModel = JsonConvert.DeserializeObject <ViewModels.Account>(jsonString);
            // verify the record.
            Assert.Equal(changedName, responseViewModel.businessLegalName);
            Assert.Equal(changedName, responseViewModel.businessDBAName);
            Assert.Equal(changedBusinessNumber, responseViewModel.businessNumber);
            Assert.Equal(changedName, responseViewModel.description);
            Assert.Equal(changedName, responseViewModel.businessEmail);
            Assert.Equal(changedName, responseViewModel.businessPhoneNumber);
            Assert.Equal(changedName, responseViewModel.mailingAddressName);
            Assert.Equal(changedName, responseViewModel.mailingAddressLine1);
            Assert.Equal(changedName, responseViewModel.mailingAddressCity);
            Assert.Equal(changedName, responseViewModel.mailingAddressCountry);
            Assert.Equal(changedName, responseViewModel.mailingAddressProvince);
            Assert.Equal(changedName, responseViewModel.mailingAddressPostalCode);

            Assert.NotNull(responseViewModel.additionalContact);
            Assert.Equal(changedName, responseViewModel.additionalContact.firstName);
            Assert.Equal(changedName, responseViewModel.additionalContact.lastName);
            Assert.Equal(changedName, responseViewModel.additionalContact.title);
            Assert.Equal(changedPhoneNumber, responseViewModel.additionalContact.phoneNumber);
            Assert.Equal(changedPhoneNumber, responseViewModel.additionalContact.phoneNumberAlt);
            Assert.Equal(changedName, responseViewModel.additionalContact.email);

            request  = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/" + id);
            response = await _client.SendAsync(request);

            response.EnsureSuccessStatusCode();

            jsonString = await response.Content.ReadAsStringAsync();

            responseViewModel = JsonConvert.DeserializeObject <ViewModels.Account>(jsonString);
            Assert.Equal(changedName, responseViewModel.businessDBAName);

            // D - Delete

            request  = new HttpRequestMessage(HttpMethod.Post, "/api/" + service + "/" + id + "/delete");
            response = await _client.SendAsync(request);

            string responseText = await response.Content.ReadAsStringAsync();

            response.EnsureSuccessStatusCode();

            // second delete should return a 404.
            request  = new HttpRequestMessage(HttpMethod.Post, "/api/" + service + "/" + id + "/delete");
            response = await _client.SendAsync(request);

            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);

            // should get a 404 if we try a get now.
            request  = new HttpRequestMessage(HttpMethod.Get, "/api/" + service + "/" + id);
            response = await _client.SendAsync(request);

            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);

            await Logout();
        }