Beispiel #1
0
        public void Remove_ContactWithSameContactType_Success()
        {
            this.user.Add(UserContact.Create(this.user, Contact.PrimaryNumber, "000"));
            this.user.Remove(UserContact.Create(this.user, Contact.PrimaryNumber, "000"));

            this.user.Contacts.Should().BeEmpty();
        }
Beispiel #2
0
 void OnContactSearchCompleted(object sender, ContactsSearchEventArgs e)
 {
     try
     {
         Contacts = new List <UserContact>();
         var allContacts = new List <Contact>(e.Results.Where(x => x.PhoneNumbers.Count() > 0).OrderBy(c => c.DisplayName));
         foreach (Contact contact in allContacts)
         {
             UserContact SavedContact = new UserContact()
             {
                 Contact = contact
             };
             if (SavedContacts.Any(x => x.PhoneNumber == contact.PhoneNumbers.ElementAt(0).PhoneNumber))
             {
                 SavedContact.IsSelected = true;
             }
             else
             {
                 SavedContact.IsSelected = false;
             }
             Contacts.Add(SavedContact);
         }
     }
     catch (System.Exception ex)
     {
         MessageBox.Show("Error in retrieving contacts : " + ex.Message);
     }
 }
        public KeyValuePair <Contact, Server.Model.User.Denormalized.User> SaveUserWithContact(Server.Model.User.Denormalized.User user, Contact contact)
        {
            if (!Db.Set <Server.Model.User.Denormalized.User>().Any(usr => usr.Id == user.Id))
            {
                Db.Set <Server.Model.User.Denormalized.User>().Add(user);
            }
            else
            {
                Db.Entry(user).State = EntityState.Modified;
            }
            var uC = new UserContact
            {
                UserId    = user.Id,
                ContactId = contact.Id
            };

            if (!Db.Set <UserContact>().Any(usr => usr.UserId == user.Id && usr.ContactId == contact.Id))
            {
                Db.Set <UserContact>().Add(uC);
            }
            else
            {
                Db.Entry(uC).State = EntityState.Modified;
            }
            Db.SaveChanges();
            return(new KeyValuePair <Contact, Server.Model.User.Denormalized.User>(contact, user));
        }
        public Contact SaveContact(int userId, Contact contact)
        {
            if (!Db.Set <Contact>().Any(c => c.Id == contact.Id))
            {
                Db.Set <Contact>().Add(contact);
            }
            else
            {
                Db.Entry(contact).State = EntityState.Modified;
            }
            var uC = new UserContact
            {
                UserId    = userId,
                ContactId = contact.Id
            };

            if (!Db.Set <UserContact>().Any(usr => usr.UserId == userId && usr.ContactId == contact.Id))
            {
                Db.Set <UserContact>().Add(uC);
            }
            else
            {
                Db.Entry(uC).State = EntityState.Modified;
            }
            Db.SaveChanges();
            return(contact);
        }
Beispiel #5
0
 public string UserAddContact(AddcontactUsLR AdLR)
 {
     if (SecureAuthentication != null)
     {
         int Output = CheckLoginReturnUserId(SecureAuthentication).ValueFromSQL;
         if (Output > 0)
         {
             UserContact addpro  = new UserContact();
             int         OutSave = UserContact.Add_ConatctUS(AdLR).ValueFromSQL;
             if (OutSave == 1)
             {
                 return("{\"ContactUs\" : " + Serialize(new AuthResponse(1, "Success")) + "}");
             }
             else
             {
                 return("{\"ContactUs\" : " + Serialize(new AuthResponse(0, "Failed..!")) + "}");
             }
         }
         else
         {
             return(Serialize(new AuthResponse(0, Output == -1 ? "Authentication is NULL" : "Invalid Authentication")));
         }
     }
     return(Serialize(new AuthResponse(0, "Authentication information not provided.")));
 }
Beispiel #6
0
        public ActionResult Contact()
        {
            List <UserContact> model = new List <UserContact>();

            model = objcon.GetUserContactDetails();
            return(View(model));
        }
Beispiel #7
0
        private void spam()
        {
            if (Provider.User.IsAnonim())
            {
                return;
            }

            User user = Provider.Database.Read <User>("Nick={0}", context.Request["user"]);

            if (user == null)
            {
                throw new Exception("User unknown");
            }

            new BlockedUser {
                UserId = user.Id
            }.Save();
            new SpammerUser {
                UserId = user.Id
            }.Save();
            UserContact uc = Provider.Database.Read <UserContact>("UserId={0} and InsertUserId={1}", user.Id, Provider.User.Id);

            uc.Delete();

            context.Response.Write(new Result {
                Data = true
            }.ToJSON());
        }
Beispiel #8
0
        public ActionResult AddContact(int id)
        {
            UserProfile loggedUser = db.UserProfile.Where(u => u.UserName == User.Identity.Name).First();

            if (loggedUser == null)
            {
                return(HttpNotFound());
            }

            var foundContact = db.UserContact.Where(c => c.UserOwnerId == loggedUser.UserId).Where(c => c.UserMemberId == id).ToList();

            if (foundContact.Count == 1)
            {
                //ViewBag.Message = "Ten użytkownik znajduje się już na liście twoich kontaktów.";
                return(RedirectToAction("Details", new { id = id }));
            }

            UserProfile userToContact = db.UserProfile.Find(id);

            if (userToContact == null)
            {
                return(HttpNotFound());
            }

            UserContact newContact = new UserContact();

            newContact.UserMemberId = userToContact.UserId;
            newContact.UserOwnerId  = loggedUser.UserId;
            db.UserContact.Add(newContact);
            db.SaveChanges();

            return(RedirectToAction("Details", new { id = id }));
        }
Beispiel #9
0
        private void unfollow()
        {
            if (Provider.User.IsAnonim())
            {
                return;
            }

            User user = Provider.Database.Read <User>("Nick={0}", context.Request["user"]);

            if (user == null)
            {
                throw new Exception("User unknown");
            }

            UserContact uc = Provider.Database.Read <UserContact>("UserId={0} and InsertUserId={1}", user.Id, Provider.User.Id);

            if (uc != null)
            {
                uc.Delete();
            }

            context.Response.Write(new Result {
                Data = true
            }.ToJSON());
        }
Beispiel #10
0
        private void block()
        {
            if (Provider.User.IsAnonim())
            {
                return;
            }

            User user = Provider.Database.Read <User>("Nick={0}", context.Request["user"]);

            if (user == null)
            {
                throw new Exception("User unknown");
            }

            BlockedUser bu = Provider.Database.Read <BlockedUser>("select * from blockeduser where InsertUserId = {0} and UserId = {1}", Provider.User.Id, user.Id);

            if (bu == null)
            {
                bu = new BlockedUser {
                    UserId = user.Id
                }
            }
            ;

            bu.Save();

            UserContact uc = Provider.Database.Read <UserContact>("UserId={0} and InsertUserId={1}", user.Id, Provider.User.Id);

            uc.Delete();

            context.Response.Write(new Result {
                Data = true
            }.ToJSON());
        }
        public UsersControllerShould()
        {
            _mockConfig   = new Mock <IConfiguration>();
            _repository   = new Mock <IUserRepository>();
            _tokenManager = new Mock <ITokenManager>();
            _logger       = new Mock <ILogger <UsersController> >();
            _userMapping  = new Mock <IUserMappings>();
            _userContact  = new UserContact()
            {
                EmailAddress = "*****@*****.**"
            };
            _user = new User()
            {
                Id           = 1,
                FullName     = "User 1",
                EmailAddress = "*****@*****.**",
                Password     = "******"
            };

            _userWithoutSensitiveData = new UserWithoutSensitiveDataDto()
            {
                Id              = 1,
                FullName        = "User 1",
                EmailAddress    = "*****@*****.**",
                ActiveTenantIds = { 1 },
                AdminForTenants = { 1 }
            };

            _usersController = new UsersController(_logger.Object,
                                                   _repository.Object,
                                                   _userMapping.Object,
                                                   _tokenManager.Object);
        }
Beispiel #12
0
        private async Task UpdateSocial()
        {
            var type    = this.Update.UserContext.GetContext <UserContactType>("UserContactType");
            var contact = this.Update.Command;

            var user = await this.Context.Users
                       .Include(u => u.UserContacts)
                       .FirstOrDefaultAsync(u => u.TelegramId == this.Update.UserContext.TelegramId);

            UserContact userContacts = user.UserContacts.FirstOrDefault(uc => uc.Type == type);

            if (userContacts == null)
            {
                userContacts = new UserContact()
                {
                    UserId  = user.Id,
                    Type    = type,
                    Contact = contact,
                };
                await this.Context.AddAsync(userContacts);
            }
            else
            {
                userContacts.Contact = contact;
                this.Context.Update(userContacts);
            }

            await this.Context.SaveChangesAsync();

            this.Update.UserContext.RemoveContext("UserContactType");
            this.Update.UserContext.RemoveContext("ProfileEditType");

            await this.ProfileMain();
        }
Beispiel #13
0
        public async Task <IActionResult> AddFriend(int id, int friendId)
        {
            if (id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            if (await _repo.GetUserContact(id, friendId) != null)
            {
                return(BadRequest("You already add the user to your contact list"));
            }

            var userContact = new UserContact()
            {
                UserId = id, ContactId = friendId
            };

            _repo.Add <UserContact>(userContact);

            if (await _repo.SaveAll())
            {
                return(Ok(new {}));
            }
            return(BadRequest("Failed to add to contact list"));
        }
        public async Task <IActionResult> PutUserContact(int id, UserContact userContact)
        {
            if (id != userContact.Id)
            {
                return(BadRequest());
            }

            _context.Entry(userContact).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!UserContactExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
        public async Task <ActionResult <UserContact> > PostUserContact(UserContact userContact)
        {
            _context.UserContact.Add(userContact);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetUserContact", new { id = userContact.Id }, userContact));
        }
        private async Task ValidateUserContactAsync(AddUserToContactDto addUserToContactDto, CancellationToken ct)
        {
            User contact = await _unitOfWork.UserRepository.GetAsync(addUserToContactDto.UserId, ct);

            if (contact == null)
            {
                _logger.LogWarning("User with id {UserId} not found", addUserToContactDto.ContactId);
                throw new UserNotFoundException();
            }

            UserContact dbUserContact = await _unitOfWork.UserContactRepository.GetUserContactAsync(
                addUserToContactDto.UserId,
                addUserToContactDto.ContactId,
                ct);

            if (dbUserContact != null)
            {
                _logger.LogWarning(
                    "User with id {UserId} already has contact with Id {ContactId}",
                    addUserToContactDto.UserId,
                    addUserToContactDto.ContactId);

                throw new UserAlreadyInContactException();
            }
        }
        public async void ShouldThrowValidationExceptionOnAddWhenUserContactIsNullAndLogItAsync()
        {
            // given
            UserContact randomUserContact        = default;
            UserContact nullUserContact          = randomUserContact;
            var         nullUserContactException = new NullUserContactException();

            var expectedUserContactValidationException =
                new UserContactValidationException(nullUserContactException);

            // when
            ValueTask <UserContact> addUserContactTask =
                this.userContactService.AddUserContactAsync(nullUserContact);

            // then
            await Assert.ThrowsAsync <UserContactValidationException>(() =>
                                                                      addUserContactTask.AsTask());

            this.loggingBrokerMock.Verify(broker =>
                                          broker.LogError(It.Is(SameExceptionAs(expectedUserContactValidationException))),
                                          Times.Once);

            this.storageBrokerMock.Verify(broker =>
                                          broker.InsertUserContactAsync(It.IsAny <UserContact>()),
                                          Times.Never);

            this.loggingBrokerMock.VerifyNoOtherCalls();
            this.storageBrokerMock.VerifyNoOtherCalls();
        }
        public async void ShouldThrowValidationExceptionOnAddWhenContactIdIsInvalidAndLogItAsync()
        {
            // given
            UserContact randomUserContact = CreateRandomUserContact();
            UserContact inputUserContact  = randomUserContact;

            inputUserContact.ContactId = default;

            var invalidUserContactInputException = new InvalidUserContactInputException(
                parameterName: nameof(UserContact.ContactId),
                parameterValue: inputUserContact.ContactId);

            var expectedUserContactValidationException =
                new UserContactValidationException(invalidUserContactInputException);

            // when
            ValueTask <UserContact> addUserContactTask =
                this.userContactService.AddUserContactAsync(inputUserContact);

            // then
            await Assert.ThrowsAsync <UserContactValidationException>(() =>
                                                                      addUserContactTask.AsTask());

            this.loggingBrokerMock.Verify(broker =>
                                          broker.LogError(It.Is(SameExceptionAs(expectedUserContactValidationException))),
                                          Times.Once);

            this.storageBrokerMock.Verify(broker =>
                                          broker.InsertUserContactAsync(It.IsAny <UserContact>()),
                                          Times.Never);

            this.loggingBrokerMock.VerifyNoOtherCalls();
            this.storageBrokerMock.VerifyNoOtherCalls();
        }
Beispiel #19
0
        public async Task ShouldRetrieveUserContactById()
        {
            // given
            UserContact randomUserContact   = CreateRandomUserContact();
            UserContact storageUserContact  = randomUserContact;
            UserContact expectedUserContact = storageUserContact;

            this.storageBrokerMock.Setup(broker =>
                                         broker.SelectUserContactByIdAsync(randomUserContact.UserId, randomUserContact.ContactId))
            .ReturnsAsync(randomUserContact);

            // when
            UserContact actualUserContact = await
                                            this.userContactService.RetrieveUserContactByIdAsync(
                randomUserContact.UserId, randomUserContact.ContactId);

            // then
            actualUserContact.Should().BeEquivalentTo(expectedUserContact);

            this.storageBrokerMock.Verify(broker =>
                                          broker.SelectUserContactByIdAsync(randomUserContact.UserId, randomUserContact.ContactId),
                                          Times.Once);

            this.storageBrokerMock.VerifyNoOtherCalls();
            this.loggingBrokerMock.VerifyNoOtherCalls();
        }
Beispiel #20
0
        public async Task <bool> DeleteContact([FromBody] UserContact userContact, string userId)
        {
            try
            {
                var    contactsFilename = string.Format("https://storage.googleapis.com/www.archishainnovators.com/contacts/{0}", userId);
                string contactsJson;
                using (WebClient client = new WebClient())
                {
                    contactsJson = client.DownloadString(contactsFilename);
                }
                var user = await _credentialsIndex.LookupDocument <UserCredentialsIndexDoc>(userId);

                var userContacts = JsonConvert.DeserializeObject <UserContact[]>(contactsJson).ToList();
                // First delete from all contacts
                userContacts.RemoveAll(x => x.Email.Equals(userContact.Email));
                var deleted = await _ds.UploadUserContactsAsync(user.Id, JsonConvert.SerializeObject(userContacts));

                var userEmailContacts = user.InNetworkEmailContacts.ToList();
                userEmailContacts.RemoveAll(x => x.Equals(userContact.Email));
                user.InNetworkEmailContacts = userEmailContacts.ToArray();
                var update = await _credentialsIndex.UpdateDocument(user);

                return(deleted && update.Succeeded);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Beispiel #21
0
        public async Task ShouldAddUserContactAsync()
        {
            // given
            UserContact randomUserContact   = CreateRandomUserContact();
            UserContact inputUserContact    = randomUserContact;
            UserContact storageUserContact  = randomUserContact;
            UserContact expectedUserContact = storageUserContact;

            this.storageBrokerMock.Setup(broker =>
                                         broker.InsertUserContactAsync(inputUserContact))
            .ReturnsAsync(storageUserContact);

            // when
            UserContact actualUserContact =
                await this.userContactService.AddUserContactAsync(inputUserContact);

            // then
            actualUserContact.Should().BeEquivalentTo(expectedUserContact);

            this.storageBrokerMock.Verify(broker =>
                                          broker.InsertUserContactAsync(inputUserContact),
                                          Times.Once);

            this.storageBrokerMock.VerifyNoOtherCalls();
            this.storageBrokerMock.VerifyNoOtherCalls();
        }
Beispiel #22
0
 private static void ValidateStorageUserContact(UserContact storageUserContact, Guid userId, Guid contactId)
 {
     if (storageUserContact == null)
     {
         throw new NotFoundUserContactException(userId, contactId);
     }
 }
Beispiel #23
0
        public async Task AcceptFriendRequest(Guid userId, Guid requestId)
        {
            var friendRequest = await _context.Set <FriendsRequest>()
                                .SingleOrDefaultAsync(f => f.Id == requestId);

            if (friendRequest == null)
            {
                return;
            }

            friendRequest.Status = FriendsRequestEnum.ACCEPTED;

            var requester = await _context.Set <User>().SingleAsync(u => u.Id == friendRequest.RequesterId);

            var user = await _context.Set <User>().SingleAsync(user => user.Id == userId);

            var receivedContact = await _context.Set <Contact>().SingleAsync(x => x.UserId == user.Id);

            var requesterContact = await _context.Set <Contact>().SingleAsync(x => x.UserId == requester.Id);

            var userContact1 = new UserContact(user.Id, requesterContact.Id);
            var userContact2 = new UserContact(requester.Id, receivedContact.Id);

            await _context.Set <UserContact>().AddRangeAsync(userContact1, userContact2);

            await _context.SaveChangesAsync();
        }
        public ValueTask <UserContact> AddUserContactAsync(UserContact userContact) =>
        TryCatch(async() =>
        {
            ValidateUserContactOnAdd(userContact);

            return(await this.storageBroker.InsertUserContactAsync(userContact));
        });
Beispiel #25
0
 private static void ValidateUserContactIsNull(UserContact userContact)
 {
     if (userContact is null)
     {
         throw new NullUserContactException();
     }
 }
 public async Task <IActionResult> EditContact(Guid id, UserContact contact)
 {
     contact.Id = id;
     return(Ok(await Mediator.Send(new Edit.Command {
         UserContact = contact
     })));
 }
Beispiel #27
0
        public async Task <IHttpActionResult> PostUserContact(UserContact userContact)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            db.UserContacts.Add(userContact);

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (UserContactExists(userContact.UserID))
                {
                    return(Conflict());
                }
                else
                {
                    throw;
                }
            }

            return(CreatedAtRoute("DefaultApi", new { id = userContact.UserID }, userContact));
        }
Beispiel #28
0
        public async Task <IHttpActionResult> PutUserContact(int id, UserContact userContact)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != userContact.UserID)
            {
                return(BadRequest());
            }

            db.Entry(userContact).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!UserContactExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
        /// <summary>
        /// 1= Success, 0= Failed, 4= User not Found
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public APIReturnModel DeleteUserContacts(string id)
        {
            try
            {
                UserContact contact = Db.UserContacts.FirstOrDefault(d => d.Id == id);
                if (contact != null)
                {
                    contact.IsArchived = true;

                    Db.SaveChanges();
                    return(new APIReturnModel {
                        Status = 1, Value = contact.Id
                    });
                }
                else
                {
                    return new APIReturnModel {
                               Status = 4
                    }
                };
            }
            catch
            {
            }
            return(new APIReturnModel {
                Status = 0
            });
        }
        public async Task ShouldThrowServiceExceptionOnAddWhenExceptionOccursAndLogItAsync()
        {
            // given
            UserContact randomUserContact = CreateRandomUserContact();
            UserContact inputUserContact  = randomUserContact;
            var         exception         = new Exception();

            var expectedUserContactServiceException =
                new UserContactServiceException(exception);

            this.storageBrokerMock.Setup(broker =>
                                         broker.InsertUserContactAsync(inputUserContact))
            .ThrowsAsync(exception);

            // when
            ValueTask <UserContact> addUserContactTask =
                this.userContactService.AddUserContactAsync(inputUserContact);

            // then
            await Assert.ThrowsAsync <UserContactServiceException>(() =>
                                                                   addUserContactTask.AsTask());

            this.loggingBrokerMock.Verify(broker =>
                                          broker.LogError(It.Is(SameExceptionAs(expectedUserContactServiceException))),
                                          Times.Once);

            this.storageBrokerMock.Verify(broker =>
                                          broker.InsertUserContactAsync(inputUserContact),
                                          Times.Once);

            this.loggingBrokerMock.VerifyNoOtherCalls();
            this.storageBrokerMock.VerifyNoOtherCalls();
        }
        //main constructor is private because BoostLog is a singleton
        //use BoostLog.Instance instead of new BoostLog()
        private BoostLog()
        {
            ServerId = "";
            var source = "4-Tell Boost";
            var logMsg = "";

            try
            {
                //start logging to system event log
                source = ConfigurationManager.AppSettings.Get("LogSource") ?? "Unidentified";
                logMsg = "4-Tell Event Log started for " + source;
                _eventLog = new EventLog("4-Tell") {Source = source};

                //Read Gmail settings from web.config
                _gmailUsername = ConfigurationManager.AppSettings.Get("GmailUsername");
                _gmailPassword = ConfigurationManager.AppSettings.Get("GmailPassword");
                _gmailToAddress = ConfigurationManager.AppSettings.Get("GmailToAdress");
                ServerId = ConfigurationManager.AppSettings.Get("ServerId");
                var level = ConfigurationManager.AppSettings.Get("AdminReportLevel");
                _adminReportType = GetReportLevel(level);
                var admin = new UserContact {Name = "Admin", Email = _gmailToAddress};

                //Block logging for certain clients
            #if INCLUDE_REPLICATOR
                if (TableAccess.Instance != null)
                {
                    _logBlockList = TableAccess.Instance.LogBlockList; //ConfigurationManager.AppSettings.Get("LogBlockList");
                    if (_logBlockList != null && _logBlockList.Any())
                    {
                        logMsg += "\nLogging will be blocked for the following clients:\n"
                                        + _logBlockList.Aggregate((current, alias) => current + (alias + "\n"));
                    }
                }

                //log any replicator startup issues
                logMsg += "\nInitializing Replicator";
                _replicator = Replicator.Instance;
                if (_replicator == null)
                {
                    logMsg += "\nReplicator instance is null";
                    Thread.Sleep(100);
                    _replicator = Replicator.Instance;
                }
                if (_replicator != null)
                {

                    logMsg += "\nInitializing DataLog";
                    //log any usage log issues
                    _dataLog = DataLogProxy.Instance;
                    if (_dataLog == null)
                    {
                        logMsg += "\nDataLog instance is null";
                        Thread.Sleep(100);
                        _dataLog = DataLogProxy.Instance;
                    }
                    if (_dataLog != null)
                    {
                        if (!string.IsNullOrEmpty(_dataLog.ErrorText))
                        {
                            _eventLog.WriteEntry(_dataLog.ErrorText, EventLogEntryType.Warning);
                        }
                    }
                }
            #endif
                _eventLog.WriteEntry(logMsg, EventLogEntryType.Information);
            }
            catch (Exception ex)
            {
                var errMsg = "Initialization Error for " + source + " Log: " + ex.Message;
                if (ex.InnerException != null)
                    errMsg += "\nInner Exception: " + ex.InnerException.Message;
                if (string.IsNullOrEmpty(ex.StackTrace))
                    errMsg += "\nStack Trace:\n" + ex.StackTrace;
                if (logMsg != null)
                    errMsg += "\nLog Message = " + logMsg;
                if (_eventLog != null)
                    _eventLog.WriteEntry(errMsg, EventLogEntryType.Error);
            }
        }
        /// <summary>
        /// Apply legacy settings. These could come from SiteRules.xml or ConfigBoost.txt
        /// </summary>
        public UserContact ParseLegacySettings(XElement settings)
        {
            var attName = Input.GetValue(settings, "attribute1Name");
            if (!string.IsNullOrEmpty(attName))
                Fields.Att1Name = attName;
            attName = Input.GetValue(settings, "attribute2Name");
            if (!string.IsNullOrEmpty(attName))
                Fields.Att2Name = attName;
            var rules = Input.GetValue(settings, "rulesEnabled");
            if (string.IsNullOrEmpty(rules))
                rules = Input.GetValue(settings, "rulesType"); //older version
            if (!string.IsNullOrEmpty(rules))
            {
                rules = rules.ToLower();
                var ruleList = rules.Split(new[] {','});
                UpsellOn = ruleList.Contains("upsell");
                ResellOn = ruleList.Contains("resell");
                ExclusionsOn = ruleList.Contains("exclusions");
                FiltersOn = ruleList.Contains("filter");
                CrossCategoryOn = ruleList.Contains("crossatt1");
                AttributeRulesOn = ruleList.Contains("attributerules");
                CategoryOptimizationsOn = ruleList.Contains("catoptimize");
                PromotionsOn = ruleList.Contains("promotions");
                ReplacementsOn = ruleList.Contains("replacements");
                FeaturedCrossSellOn = ruleList.Contains("manualcrosssell");
                FeaturedUpSellOn = ruleList.Contains("manualupsell");
                FeaturedOn = ruleList.Contains("manualtopsellers") || ruleList.Contains("manualtopsell");
                FeaturedAtt1On = ruleList.Contains("manualatt1item");
            }
            int rangeToExport; //cannot use a property in an "out" variable
            if (Input.GetValue(out rangeToExport, settings, "salesMonthsToExport"))
                SalesMonthsToExport = rangeToExport;
            else if (Input.GetValue(out rangeToExport, settings, "monthsToExport")) //depricated
                SalesMonthsToExport = rangeToExport;
            else if (Input.GetValue(out rangeToExport, settings, "maxSalesDataAgeInMonths")) //name used in configboost
                SalesMonthsToExport = rangeToExport;
            if (Input.GetValue(out rangeToExport, settings, "topSellRangeInDays"))
                TopSellRangeInDays = rangeToExport;
            if (Input.GetValue(out rangeToExport, settings, "customerMonthsToExport"))
                CustomerMonthsToExport = rangeToExport;
            else if (Input.GetValue(out rangeToExport, settings, "maxCustomersDataAgeInMonths")) //name used in configboost
                CustomerMonthsToExport = rangeToExport;
            if (Input.GetValue(out rangeToExport, settings, "clickStreamWeeksToExport"))
                ClickStreamWeeksToExport = rangeToExport;
            else if (Input.GetValue(out rangeToExport, settings, "maxClickStreamDataAgeInWeeks")) //name used in configboost
                ClickStreamWeeksToExport = rangeToExport;
            int minLikelihood;
            if (Input.GetValue(out minLikelihood, settings, "minLikelihood"))
                MinLikelihood = minLikelihood;
            int minCommon;
            if (Input.GetValue(out minCommon, settings, "minCommon"))
                MinCommon = minCommon;
            var currency = Input.GetValue(settings, "currencySymbol");
            if (string.IsNullOrEmpty(currency))
                currency = Input.GetValue(settings, "currency"); //legacy name
            CurrencySymbol = string.IsNullOrEmpty(currency) ? "$" : currency;
            currency = Input.GetValue(settings, "decimalSeparator");
            DecimalSeparator = string.IsNullOrEmpty(currency) ? "." : currency;
            SimilarTopSellerRule = Input.GetValue(settings, "similarTopSellerRule");
            if (string.IsNullOrEmpty(SimilarTopSellerRule)) SimilarTopSellerRule = DefaultSimilarTopSellerRule;
            SimilarClickStreamRule = Input.GetValue(settings, "similarClickStreamRule");
            if (string.IsNullOrEmpty(SimilarClickStreamRule)) SimilarClickStreamRule = DefaultSimilarClickStreamRule;
            float factor;
            UpsellFactor = Input.GetValue(out factor, settings, "upsellFactor") ? factor : DefaultUpsellFactor;
            FilterFilename = Input.GetValue(settings, "filterFilename");
            CreateWhyItems = Input.GetValue(settings, "createWhyItems").Equals("true"); //default is false
            CreateCampaignOptimization = Input.GetValue(settings, "createCampaignOptimization").Equals("true"); //default is false

            RecTypesDisabled = new List<RecTableType>();
            var disabledTypes = Input.GetValue(settings, "RecTypesDisabled");
            if (!string.IsNullOrEmpty(disabledTypes))
            {
                RecTableType t;
                foreach (var d in disabledTypes.Split(new[] {','}))
                {
                    if (string.IsNullOrEmpty(d)
                        || !Enum.TryParse(d, true, out t)
                        || t.Equals(RecTableType.None)) continue;
                    RecTypesDisabled.Add(t);
                }
            }
            List<string> filenames;
            SalesFilenames = Input.GetValue(out filenames, settings, "salesFilenames") ? filenames : null;
            OrdersFilenames = Input.GetValue(out filenames, settings, "ordersFilenames") ? filenames : null;
            OrderDetailsFilenames = Input.GetValue(out filenames, settings, "orderDetailsFilenames") ? filenames : null;
            ClickStreamFilenames = Input.GetValue(out filenames, settings, "clickStreamFilenames") ? filenames : null;

            UserContact poc = null;
            var pocEmail = Input.GetValue(settings, "pocEmail");
            if (!string.IsNullOrEmpty(pocEmail))
            {
                var atindex = pocEmail.IndexOf('@');
                if (atindex > 0 && !Users.Any(x => x.Email.Equals(pocEmail, StringComparison.OrdinalIgnoreCase)))
                {
                    var pocName = Input.GetValue(settings, "pocName");
                    if (string.IsNullOrEmpty(pocName)) pocName = pocEmail.Substring(0, atindex);
                    //Traditionaly the clientSettings POC was the technical contact
                    poc = new UserContact {Email = pocEmail, Name = pocName};
                    Users.Add(new User
                        {
                            Name = poc.Name,
                            Email = poc.Email,
                            ContactRole = UserContactRole.Technical
                        });
                    var level = Input.GetValue(settings, "reportLevel");
                    if (!string.IsNullOrEmpty(level))
                    {
                        try
                        {
                            var report = (ReportType) Enum.Parse(typeof (ReportType), level, true);
                            if (BoostLog.Instance != null)
                                BoostLog.Instance.Subscriptions.Add(Alias, poc, report);
                        }
                        catch
                        {
                        }
                    }
                }
            }
            return poc;
        }
        protected void ParseSettings(XElement settings)
        {
            //site definition
            StoreShortUrl = CleanUpUrl(Input.GetValue(settings, "storeUrl"));
            EnableServiceCallDetailLog = Input.GetValue(settings, "enableServiceCallDetailLog").Equals("true", StringComparison.OrdinalIgnoreCase);
            var zone = Input.GetValue(settings, "siteTimeZone");
            if (!string.IsNullOrEmpty(zone))
            {
                try
                {
                    SiteTimeZone = TimeZoneInfo.FindSystemTimeZoneById(zone);
                }
                catch {}
            }

            //Security Rules
            RequireSecureBoost = Input.GetValue(settings, "requireSecureBoost").Equals("true");
            RequireSecureUpload = Input.GetValue(settings, "requireSecureUpload").Equals("true");
            UploadAddresses = null;
            var ipList = settings.Elements("approvedUploadIP");
            if (ipList.Any())
                UploadAddresses = ipList.Select(ip => ip.Value).ToList();
            AllowManualUpload = !Input.GetValue(settings, "allowManualUpload").Equals("false"); //default is true
            AllowUserExtraction = !Input.GetValue(settings, "allowUserExtraction").Equals("false"); //default is true

            //track last extraction/generation
            var extract = Input.GetValue(settings, "lastExtractionType");
            CartExtractor.ExtractType lastExtractType;
            if (Enum.TryParse(extract, true, out lastExtractType))
                LastExtractionType = lastExtractType;
            extract = Input.GetValue(settings, "lastDynamicUpdateType");
            if (Enum.TryParse(extract, true, out lastExtractType))
                LastDynamicUpdateType = lastExtractType;
            var lastDate = Input.GetValue(settings, "lastExtractionTime");
            LastExtractionTime = Input.SafeDateConvert(lastDate, DateTime.MinValue);
            lastDate = Input.GetValue(settings, "lastDynamicUpdateTime");
            LastDynamicUpdateTime = Input.SafeDateConvert(lastDate, DateTime.MinValue);
            lastDate = Input.GetValue(settings, "lastGeneratorTime");
            LastGeneratorTime = Input.SafeDateConvert(lastDate, DateTime.MinValue);
            lastDate = Input.GetValue(settings, "lastRuleChange");
            LastRuleChangeTime = Input.SafeDateConvert(lastDate, DateTime.MinValue);
            LastExtractorDuration = Input.SafeIntConvert(Input.GetValue(settings, "lastExtractorDuration"));
            if (LastExtractorDuration.Equals(0))
                LastExtractorDuration = Input.SafeIntConvert(Input.GetValue(settings, "lastExtractionDuration")); //legacy
            LastGeneratorDuration = Input.SafeIntConvert(Input.GetValue(settings, "lastGeneratorDuration"));
            var lockout = Input.SafeIntConvert(Input.GetValue(settings, "extractorLockoutMinutes"), -1);
            ExtractorLockoutMinutes = lockout > -1 ? lockout : DefaultExtractorLockoutMinutes;

            //contact info
            UserContact poc = ParseLegacySettings(settings);
            var userElement = settings.Element("users");
            if (userElement != null)
            {
                var users = userElement.Descendants("user");
                if (users.Any())
                {
                    foreach (var u in users)
                    {
                        Users.Add(new User(u));
                    }
                    if (poc == null)
                    {
                        var pocUser = Users.First(x => x.ContactRole.Equals(UserContactRole.Technical));
                        if (pocUser != null)
                            poc = new UserContact { Email = pocUser.Email, Name = pocUser.Name };
                    }
                    //else
                    //	DataLogProxy.Instance.AddSite(Alias, poc); //add client to the log
                }
            }

            #region Data Source Rules

            //Migration rulescatalogMigration
            var migration = settings.Element("catalogMigration");
            if (migration != null)
            {
                var startDate = Input.SafeDateConvert(Input.GetAttribute(migration, "startDate"), DateTime.MinValue);
                var fromField = Input.GetAttribute(migration, "mapFromField");
                var toField = Input.GetAttribute(migration, "mapToField");
                var enabled = !Input.GetAttribute(migration, "enabled").Equals("false");
                var use4TellCatalog = Input.GetAttribute(migration, "use4TellCatalog").Equals("true");
                var use4TellSales = Input.GetAttribute(migration, "use4TellSales").Equals("true");
                MigrationRules = new CatalogMigration(Alias, (int)Tier, startDate, fromField, toField, enabled, true,
                                                                                            SalesMonthsToExport, use4TellCatalog, use4TellSales);
            }

            //set cart extraction defaults
            try
            {
                CartName = Input.GetValue(settings, "cartType");
                PluginVersion = Input.SafeFloatConvert(Input.GetValue(settings, "pluginVersion"));
                CartType cartType;
                CartType = Enum.TryParse(CartName, true, out cartType) ? cartType : CartType.Other;
                var level = Input.GetValue(settings, "cartLevel");
                CartLevel = 0;
                SetCartDefaults(false, level);
            }
            catch (Exception ex)
            {
                CartType = CartType.Other;
                SetCartDefaults();
            }

            //Onboarding Credentials (not used by service but sometimes needed for onboarding)
            AdminUser = Input.GetValue(settings, "adminUser");
            AdminPassword = Input.GetValue(settings, "adminPassword");
            FtpType = Input.GetValue(settings, "ftpType");
            FtpUrl = Input.GetValue(settings, "ftpUrl");
            FtpUser = Input.GetValue(settings, "ftpUser");
            FtpPassword = Input.GetValue(settings, "ftpPassword");

            //API access
            ApiUrl = Input.GetValue(settings, "apiUrl");
            float apiVersion;
            ApiVersion = Input.GetValue(out apiVersion, settings, "apiVersion") ? apiVersion : 0F;	//default zero means no API
            ApiCountEnabled = !Input.GetValue(settings, "apiCountEnabled").Equals("false", StringComparison.OrdinalIgnoreCase);	//default true
            ApiCustomerDateRangeEnabled = !Input.GetValue(settings, "apiCustomerDateRangeEnabled").Equals("false", StringComparison.OrdinalIgnoreCase);	//default true
            ApiSalesDateRangeEnabled = !Input.GetValue(settings, "apiSalesDateRangeEnabled").Equals("false", StringComparison.OrdinalIgnoreCase);	//default true
            ApiHeaderIsOnlyOnFirstRow = Input.GetValue(settings, "apiHeaderIsOnlyOnFirstRow").Equals("true", StringComparison.OrdinalIgnoreCase);	//default false
            ApiRowEnd = Input.GetCsvStringList(settings, "apiRowEnd");
            ApiTrimChars = Input.GetCsvCharList(settings, "apiTrimChars");
            ApiMinimumCatalogSize = Input.SafeIntConvert(Input.GetValue(settings, "apiMinimumCatalogSize"), 0);
            ApiForceAllRowRanges = Input.SafeIntConvert(Input.GetValue(settings, "apiForceAllRowRanges"), 0);
            if (ApiForceAllRowRanges < 1)
                    ApiForceAllRowRanges = Input.SafeIntConvert(Input.GetValue(settings, "apiForceRowRange"), 0); //depricated
            ApiForceCatalogRowRange = Input.SafeIntConvert(Input.GetValue(settings, "apiForceCatalogRowRange"), 0);
            ApiForceCategoryRowRange = Input.SafeIntConvert(Input.GetValue(settings, "apiForceCategoryRowRange"), 0);
            ApiForceSalesRowRange = Input.SafeIntConvert(Input.GetValue(settings, "apiForceSalesRowRange"), 0);
            ApiForceCustomerRowRange = Input.SafeIntConvert(Input.GetValue(settings, "apiForceCustomerRowRange"), 0);
            ApiForceInventoryRowRange = Input.SafeIntConvert(Input.GetValue(settings, "apiForceInventoryRowRange"), 0);
            ApiAllowExtraRows = Input.GetValue(settings, "apiAllowExtraRows").Equals("true", StringComparison.OrdinalIgnoreCase);
            ApiMaxDaysPerRequest = Input.SafeIntConvert(Input.GetValue(settings, "apiMaxDaysPerRequest"), 0);
            ApiUserName = Input.GetValue(settings, "apiUserName");
            ApiKey = Input.GetValue(settings, "apiKey");
            ApiSecret = Input.GetValue(settings, "apiSecret");
            ApiAliasParam = Input.GetValue(settings, "apiAliasParam");
            ApiUserParam = Input.GetValue(settings, "apiUserParam");
            ApiKeyParam = Input.GetValue(settings, "apiKeyParam");
            ApiFieldParam = Input.GetValue(settings, "apiFieldParam");
            ApiIdRangeParam = Input.GetValue(settings, "apiIdRangeParam");
            ApiRowRangeParam = Input.GetValue(settings, "apiRowRangeParam");
            ApiDateRangeParam = Input.GetValue(settings, "apiDateRangeParam");
            ApiYearParam = Input.GetValue(settings, "apiYearParam");
            ApiMonthParam = Input.GetValue(settings, "apiMonthParam");
            ApiModeParam = Input.GetValue(settings, "apiModeParam");
            ApiResponseFormat = Input.GetValue(settings, "apiResponseFormat");
            ApiAcceptHeader = Input.GetValue(settings, "apiAcceptHeader");
            ApiExtraHeaders = Input.SafeIntConvert(Input.GetValue(settings, "apiExtraHeaders"));
            var additionalQueries = settings.Element("apiAddQueries");
            if (additionalQueries != null)
            {
                var queries = additionalQueries.Descendants("addQuery");
                if (queries.Any())
                {
                    ApiAddQueries = new Dictionary<DataGroup, NameValueCollection>();
                    foreach (var q in queries)
                    {
                        //parse query details
                        var queryGroup = Input.GetAttribute(q, "group");
                        if (string.IsNullOrEmpty(queryGroup)) continue;
                        DataGroup dataGroup;
                        if (!Enum.TryParse(queryGroup, true, out dataGroup)) continue;
                        var name = Input.GetAttribute(q, "name");
                        if (string.IsNullOrEmpty(name)) continue;
                        var value = Input.GetAttribute(q, "value");
                        if (string.IsNullOrEmpty(value)) continue;

                        NameValueCollection queryList;
                        if (!ApiAddQueries.TryGetValue(dataGroup, out queryList))
                        {
                            ApiAddQueries.Add(dataGroup, new NameValueCollection {{name, value}});
                        }
                        else ApiAddQueries[dataGroup].Add(name, value);
                    }
                }
            }
            var charMapXml = settings.Element("titleCharMap");
            TitleCharMap = GetCharMapPairs(charMapXml, Alias);
            WebClientConfig = new CartWebClientConfig(settings);

            //cart extraction settings
            CombinedFeedUrl = Input.GetValue(settings, "combinedFeedUrl");
            if (string.IsNullOrEmpty(CombinedFeedUrl))
                CombinedFeedUrl = Input.GetValue(settings, "combinedFeed"); //old name
            CatalogFeedUrl = Input.GetValue(settings, "catalogFeedUrl");
            if (string.IsNullOrEmpty(CatalogFeedUrl))
                CatalogFeedUrl = Input.GetValue(settings, "catalogFeed"); //old name
            SalesFeedUrl = Input.GetValue(settings, "salesFeedUrl");
            if (string.IsNullOrEmpty(SalesFeedUrl))
                SalesFeedUrl = Input.GetValue(settings, "salesFeed"); //old name
            CustomerFeedUrl = Input.GetValue(settings, "customerFeedUrl");
            Att1NameFeedUrl = Input.GetValue(settings, "att1NameFeedUrl");
            if (string.IsNullOrEmpty(Att1NameFeedUrl))
                Att1NameFeedUrl = Input.GetValue(settings, "att1NameFeed"); //old name
            Att2NameFeedUrl = Input.GetValue(settings, "att2NameFeedUrl");
            if (string.IsNullOrEmpty(Att2NameFeedUrl))
                Att2NameFeedUrl = Input.GetValue(settings, "att2NameFeed"); //old name
            DepartmentNameFeedUrl = Input.GetValue(settings, "departmentNameFeedUrl");
            InventoryFeedUrl = Input.GetValue(settings, "inventoryFeedUrl");

            //Access Rules
            var accessCreds = settings.Element("accessCredentials");
            if (accessCreds != null)
                AccessCredentials = new AuthCredentials(accessCreds);
            var extractorCreds = settings.Element("extractorCredentials");
            if (extractorCreds != null)
                ExtractorCredentials = new AuthCredentials(extractorCreds);
            else if (AccessCredentials != null) //if no extractor creds provided, make them match the access creds
                ExtractorCredentials = new AuthCredentials(AccessCredentials);
            var loginUrl = Input.GetValue(settings, "extractorLoginUrl");
            if (loginUrl != null)
                ExtractorLoginUrl = loginUrl;
            var loginCreds = settings.Element("extractorLoginCredentials");
            if (loginCreds != null)
                ExtractorLoginCredentials = new AuthCredentials(loginCreds);

            //Extractor Flags	-- only override defaults if a value is set in siterules

            //general (timeframes are set in legacy settings)
            var flag = Input.GetValue(settings, "unescapeFeedData");
            if (!string.IsNullOrEmpty(flag))
                UnescapeFeedData = flag.Equals("true", StringComparison.OrdinalIgnoreCase);
            flag = Input.GetValue(settings, "reduceXmlFeed");
            if (!string.IsNullOrEmpty(flag))
                ReduceXmlFeed = flag.Equals("true", StringComparison.OrdinalIgnoreCase);
            flag = Input.GetValue(settings, "omitExtraFields");
            if (!string.IsNullOrEmpty(flag))
                OmitExtraFields = flag.Equals("true", StringComparison.OrdinalIgnoreCase);
            UseLargeCatalogHandling = Input.GetValue(settings, "useLargeCatalogHandling").Equals("true", StringComparison.OrdinalIgnoreCase);

            //sales
            flag = Input.GetValue(settings, "extractSalesUpdate");
            if (!string.IsNullOrEmpty(flag))
                ExtractSalesUpdate = flag.Equals("true", StringComparison.OrdinalIgnoreCase);
            flag = Input.GetValue(settings, "extractSalesFull");
            if (!string.IsNullOrEmpty(flag))
                ExtractSalesFull = !flag.Equals("false", StringComparison.OrdinalIgnoreCase); //default true
            flag = Input.GetValue(settings, "extractSalesFromXmlFile");
            if (!string.IsNullOrEmpty(flag))
                ExtractSalesFromXmlFile = flag.Equals("true", StringComparison.OrdinalIgnoreCase);
            flag = Input.GetValue(settings, "orderDateReversed");
            if (!string.IsNullOrEmpty(flag))
                OrderDateReversed = flag.Equals("true", StringComparison.OrdinalIgnoreCase);

            //customers
            flag = Input.GetValue(settings, "extractCustomerData");
            if (!string.IsNullOrEmpty(flag))
                ExtractCustomerData = flag.Equals("true", StringComparison.OrdinalIgnoreCase);
            flag = Input.GetValue(settings, "requireEmailOptIn");
            if (!string.IsNullOrEmpty(flag))
                RequireEmailOptIn = flag.Equals("true", StringComparison.OrdinalIgnoreCase);
            flag = Input.GetValue(settings, "trackShopperActivity");
            if (!string.IsNullOrEmpty(flag))
                TrackShopperActivity = flag.Equals("true", StringComparison.OrdinalIgnoreCase);
            PersonaMappingFields = Input.GetValue(settings, "personaMappingFields");

            //catalog
            flag = Input.GetValue(settings, "invalidatePricesOnExtract");
            if (!string.IsNullOrEmpty(flag))
                InvalidatePricesOnExtract = flag.Equals("true", StringComparison.OrdinalIgnoreCase);
            flag = Input.GetValue(settings, "invalidatePricesOnExtractComplete");
            if (!string.IsNullOrEmpty(flag))
                InvalidatePricesOnExtractComplete = flag.Equals("true", StringComparison.OrdinalIgnoreCase);
            flag = Input.GetValue(settings, "extractCatalogFromXmlFile");
            if (!string.IsNullOrEmpty(flag))
                ExtractCatalogFromXmlFile = flag.Equals("true", StringComparison.OrdinalIgnoreCase);
            flag = Input.GetValue(settings, "extractAtt2Names");
            if (string.IsNullOrEmpty(flag))
                flag = Input.GetValue(settings, "exportAtt2Names"); //legacy name
            if (!string.IsNullOrEmpty(flag))
                ExtractAtt2Names = flag.Equals("true", StringComparison.OrdinalIgnoreCase);
            flag = Input.GetValue(settings, "allowLowerCatalogCount");
            if (!string.IsNullOrEmpty(flag))
                AllowLowerCatalogCount = flag.Equals("true", StringComparison.OrdinalIgnoreCase);
            flag = Input.GetValue(settings, "allowLowerSalesCount");
            if (!string.IsNullOrEmpty(flag))
                AllowLowerSalesCount = flag.Equals("true", StringComparison.OrdinalIgnoreCase);
            flag = Input.GetValue(settings, "allowLowerCustomerCount");
            if (!string.IsNullOrEmpty(flag))
                AllowLowerCustomerCount = flag.Equals("true", StringComparison.OrdinalIgnoreCase);
            flag = Input.GetValue(settings, "mapStockToVisibility");
            if (!string.IsNullOrEmpty(flag))
                MapStockToVisibility = flag.Equals("true", StringComparison.OrdinalIgnoreCase);
            flag = Input.GetValue(settings, "reverseVisibleFlag");
            if (!string.IsNullOrEmpty(flag))
                ReverseVisibleFlag = flag.Equals("true", StringComparison.OrdinalIgnoreCase);
            flag = Input.GetValue(settings, "ignoreStockUseFlag");
            if (!string.IsNullOrEmpty(flag))
                IgnoreStockUseFlag = flag.Equals("true", StringComparison.OrdinalIgnoreCase);
            flag = Input.GetValue(settings, "ignoreStockInPriceRange");
            if (!string.IsNullOrEmpty(flag))
                IgnoreStockInPriceRange = flag.Equals("true", StringComparison.OrdinalIgnoreCase);
            flag = Input.GetValue(settings, "includeChildrenInCatalog");
            if (!string.IsNullOrEmpty(flag))
                IncludeChildrenInCatalog = flag.Equals("true", StringComparison.OrdinalIgnoreCase);
            flag = Input.GetValue(settings, "useAverageChildRating");
            if (!string.IsNullOrEmpty(flag))
                UseAverageChildRating = flag.Equals("true", StringComparison.OrdinalIgnoreCase);
            HiddenSalePriceText = Input.GetValue(settings, "hiddenSalePriceText");

            //categories
            MapCategoriesToFilters = Input.GetValue(settings, "mapCategoriesToFilters")
                                                                        .Equals("true", StringComparison.OrdinalIgnoreCase);
            IncludeCategoryParents = Input.GetValue(settings, "includeCategoryParents")
                                                                 .Equals("true", StringComparison.OrdinalIgnoreCase);
            flag = Input.GetValue(settings, "exportDepartmentNames");
            if (!string.IsNullOrEmpty(flag))
                ExportDepartmentNames = flag.Equals("true", StringComparison.OrdinalIgnoreCase);
            flag = Input.GetValue(settings, "useDepartmentsAsCategories");
            if (!string.IsNullOrEmpty(flag))
                UseDepartmentsAsCategories = flag.Equals("true", StringComparison.OrdinalIgnoreCase);
            var catSep = Input.GetValue(settings, "categorySeparator");
            if (!string.IsNullOrEmpty(catSep))
            {
                char charTest;
                if (Input.TryConvert(catSep, out charTest))
                    CategorySeparator = charTest.ToString();
                else
                    CategorySeparator = catSep;
            }

            //images
            AllowMissingPhotos = false;
            var amp = settings.Element("allowMissingPhotos");
            if (amp != null)
            {
                if (amp.Value != null && amp.Value.Equals("true"))
                    AllowMissingPhotos = true;
                else
                    AllowMissingPhotos = Input.GetAttribute(amp, "enabled").Equals("true");
            }
            var imageThreshold = Input.SafeIntConvert(Input.GetValue(settings, "missingImageThreshold"), -1);
            if (imageThreshold > -1) MissingImageThreshold = imageThreshold;
            flag = Input.GetValue(settings, "extrapolateThumbnailPath");
            if (!string.IsNullOrEmpty(flag))
                ExtrapolateThumbnailPath = flag.Equals("true");
            flag = Input.GetValue(settings, "scrapeCategoryThumbnails");
            if (string.IsNullOrEmpty(flag))
                flag = Input.GetValue(settings, "useCacheThumb"); //depricated
            if (!string.IsNullOrEmpty(flag))
                ScrapeCategoryThumbnails = !flag.Equals("false"); //default true
            flag = Input.GetValue(settings, "forceCategoryTreeScrape");
            if (!string.IsNullOrEmpty(flag))
                ForceCategoryTreeScrape = flag.Equals("true");
            flag = Input.GetValue(settings, "imageLinkBaseUrl");
            if (string.IsNullOrEmpty(flag))
                flag = Input.GetValue(settings, "photoBaseUrl"); //legacy name
            if (!string.IsNullOrEmpty(flag))
                ImageLinkBaseUrl = flag;
            flag = Input.GetValue(settings, "imageLinkFormat"); //a string.Format parameter that the product id gets plugged into
            if (!string.IsNullOrEmpty(flag))
            {
                if (flag.IndexOf("{0}") >= 0)
                    ImageLinkFormat = flag;
                else if (string.IsNullOrEmpty(ImageLinkBaseUrl))	//missing locator for the id so use it as a baseUrl instead
                        ImageLinkBaseUrl = flag;
            }
            if (!string.IsNullOrEmpty(ImageLinkBaseUrl))
            {
                if (!ImageLinkBaseUrl.StartsWith("/") && !ImageLinkBaseUrl.StartsWith("http"))
                    ImageLinkBaseUrl = "/" + ImageLinkBaseUrl; //add initial slash
                if (ImageLinkBaseUrl.EndsWith("/"))
                    ImageLinkBaseUrl = ImageLinkBaseUrl.Substring(0, ImageLinkBaseUrl.Length - 1); //remove final slash
            }
            flag = Input.GetValue(settings, "pageLinkFormat"); //a string.Format parameter that the product id gets plugged into
            if (!string.IsNullOrEmpty(flag) && flag.Contains("{0}"))
                    PageLinkFormat = flag;
            ProductNodeSelector = Input.GetValue(settings, "productNodeSelector");
            ImageUrlSelector = Input.GetValue(settings, "imageUrlSelector");
            ImageUrlPrefix = Input.GetValue(settings, "imageUrlPrefix");
            ImageUrlSuffix = Input.GetValue(settings, "imageUrlSuffix");
            PidSelector = Input.GetValue(settings, "pidSelector");
            PidPrefix = Input.GetValue(settings, "pidPrefix");
            PidSuffix = Input.GetValue(settings, "pidSuffix");
            CommentParseKey = Input.GetValue(settings, "commentParseKey");
            if (string.IsNullOrEmpty(ProductNodeSelector))
                ProductNodeSelector = Input.GetValue(settings, "imageNodeSelector"); //depricated
            if (string.IsNullOrEmpty(ImageUrlPrefix))
                ImageUrlPrefix = Input.GetValue(settings, "imageSrcSelector"); //depricated

            //First check CartRules for defaults
            var cartRules = ReadCartRules(CartType);
            Fields.InitializeFields(cartRules, true);
            Fields.InitializeFields(settings, false);

            //conditional rules
            ExclusionRules = new List<Condition>();
            var exConditions = settings.Element("exclusionConditions");
            if (exConditions != null)
            {
                foreach (var ec in exConditions.Elements("condition"))
                {
                    var name = Input.GetAttribute(ec, "name");
                    var comparison = Input.GetAttribute(ec, "comparison");
                    var value = Input.GetAttribute(ec, "value");
                    var fieldName = Input.GetAttribute(ec, "fieldName");
                    var conditionType = Input.GetAttribute(ec, "type");
                    //var resultField = FieldsIncludeTablePrefix ? StripTablePrefix(fieldName) : fieldName;
                    try
                    {
                        ExclusionRules.Add(new Condition(name, comparison, value, fieldName)); //, resultField));
                    }
                    catch (Exception ex)
                    {
                        if (BoostLog.Instance != null)
                            BoostLog.Instance.WriteEntry(EventLogEntryType.Error, "Error creating exclusion rule", ex, Alias);
                    }
                }
            }
            var exSet = settings.Element("exclusionSet");
            if (exSet != null)
            {
                ExclusionSet = new LogicSet(Alias, exSet);
            }

            FilterParsingRules = null;
            var filterParsing = settings.Element("filterParsingRules");
            if (filterParsing != null)
            {
                FilterParsingRules = new List<ParseGroup>();
                var parseGroups = filterParsing.Elements("parseGroup");
                if (parseGroups != null)
                {
                    var tempVal = "";
                    foreach (var g in parseGroups)
                    {
                        var newGroup = new ParseGroup
                                                                {
                                                                    Delimiter = Input.GetAttribute(g, "delimiter")
                                                                };

                        var parseRules = g.Elements("parseRule");
                        if (parseRules == null) continue;
                        newGroup.ParseRules = new List<ParseRule>();
                        foreach (var pr in parseRules)
                        {
                            newGroup.ParseRules.Add(new ParseRule
                                                                            {
                                                                                FromField = Input.GetAttribute(pr, "fromField"),
                                                                                ToField = Input.GetAttribute(pr, "toField"),
                                                                                RegexMatch = Input.GetAttribute(pr, "regexMatch"),
                                                                                RegexGroup = Input.SafeIntConvert(Input.GetAttribute(pr, "regexGroup")),
                                                                                Expand = Input.GetAttribute(pr, "expand").Equals("true"),
                                                                                Modulo = Input.SafeIntConvert(Input.GetAttribute(pr, "modulo")),
                                                                                Delimiter = Input.GetAttribute(pr, "delimiter"),
                                                                                Format = Input.GetAttribute(pr, "format")
                                                                            });
                        }
                        FilterParsingRules.Add(newGroup);
                    }
                }
            }

            FilterRules = new List<Condition>();
            var filterConditions = settings.Element("filterConditions");
            if (filterConditions != null)
            {
                foreach (var f in filterConditions.Elements("condition"))
                {
                    var name = Input.GetAttribute(f, "name");
                    var comparison = Input.GetAttribute(f, "comparison");
                    var value = Input.GetAttribute(f, "value");
                    var fieldName = Input.GetAttribute(f, "fieldName");
                    //var resultField = FieldsIncludeTablePrefix ? StripTablePrefix(fieldName) : fieldName;
                    try
                    {
                        FilterRules.Add(new Condition(name, comparison, value, fieldName)); //, resultField));
                    }
                    catch (Exception ex)
                    {
                        if (BoostLog.Instance != null)
                            BoostLog.Instance.WriteEntry(EventLogEntryType.Error, "Error creating filter rule", ex, Alias);
                    }
                }
            }
            UniversalFilterName = Input.GetValue(settings, "universalFilterName");
            if (UniversalFilterName.Length < 1)
                UniversalFilterName = "Universal";
            FilterTopSellers = Input.GetValue(settings, "filterTopSellers").Equals("true", StringComparison.CurrentCultureIgnoreCase);

            ReplacementRules = new List<ReplacementCondition>();
            var repConditions = settings.Element("replacementConditions");
            if (repConditions != null)
            {
                foreach (var rep in repConditions.Elements("condition"))
                {
                    var name = Input.GetAttribute(rep, "name");
                    var type = Input.GetAttribute(rep, "type");
                    var oldName = Input.GetAttribute(rep, "oldFieldName");
                    var newName = Input.GetAttribute(rep, "newFieldName");
                    var oldResultField = oldName; //FieldsIncludeTablePrefix ? StripTablePrefix(oldName) : oldName;
                    var newResultField = newName; //FieldsIncludeTablePrefix ? StripTablePrefix(newName) : newName;
                    ReplacementRules.Add(new ReplacementCondition(name, type, oldName, newName, oldResultField, newResultField));
                }
            }

            var catConditions = settings.Element("categoryConditions");
            if (catConditions != null)
            {
                foreach (var cat in catConditions.Elements("condition"))
                {
                    var groupId = Input.GetAttribute(cat, "groupId");
                    var type = Input.GetAttribute(cat, "type");
                    var value = Input.GetAttribute(cat, "value");
                    CategoryRules.AddCat(type, value, groupId);
                }
            }

            //Featured selections
            var featuredConditions = settings.Element("featuredConditions") ??
                                                             settings.Element("manualTopSellConditions"); //depricated
            if (featuredConditions != null)
            {
                FeaturedRules = new List<FeaturedRecCondition>();
                foreach (var cat in featuredConditions.Elements("condition"))
                {
                    var queryField = Input.GetAttribute(cat, "fieldName");
                    var resultField = queryField; //FieldsIncludeTablePrefix ? StripTablePrefix(queryField) : queryField;
                    var include = Input.GetAttribute(cat, "type").Equals("include", StringComparison.OrdinalIgnoreCase);
                    var enabled = !Input.GetAttribute(cat, "enabled").Equals("false", StringComparison.OrdinalIgnoreCase);
                    FeaturedRules.Add(new FeaturedRecCondition(queryField, resultField, include, enabled));
                }
            }

            var featuredCrossSellConditions = settings.Element("featuredCrossSellConditions") ??
                                                                                settings.Element("manualCrossSellConditions");  //depricated
            if (featuredCrossSellConditions != null)
            {
                FeaturedCrossSellRules = new List<FeaturedRecCondition>();
                foreach (var cat in featuredCrossSellConditions.Elements("condition"))
                {
                    var queryField = Input.GetAttribute(cat, "fieldName");
                    var resultField = queryField; //FieldsIncludeTablePrefix ? StripTablePrefix(queryField) : queryField;
                    var include = Input.GetAttribute(cat, "type").Equals("include", StringComparison.OrdinalIgnoreCase);
                    var enabled = !Input.GetAttribute(cat, "enabled").Equals("false", StringComparison.OrdinalIgnoreCase);
                    FeaturedCrossSellRules.Add(new FeaturedRecCondition(queryField, resultField, include, enabled));
                }
            }

            var featuredUpSellConditions = settings.Element("featuredUpSellConditions") ??
                                                                         settings.Element("manualUpSellConditions");  //depricated
            if (featuredUpSellConditions != null)
            {
                FeaturedUpSellRules = new List<FeaturedRecCondition>();
                foreach (var cat in featuredUpSellConditions.Elements("condition"))
                {
                    var queryField = Input.GetAttribute(cat, "fieldName");
                    var resultField = queryField; //FieldsIncludeTablePrefix ? StripTablePrefix(queryField) : queryField;
                    var include = Input.GetAttribute(cat, "type").Equals("include", StringComparison.OrdinalIgnoreCase);
                    var enabled = !Input.GetAttribute(cat, "enabled").Equals("false", StringComparison.OrdinalIgnoreCase);
                    FeaturedUpSellRules.Add(new FeaturedRecCondition(queryField, resultField, include, enabled));
                }
            }

            //timers
            var upTimers = settings.Elements("updateTimer");
            if (!upTimers.Any())
                upTimers = settings.Elements("uploadTimer"); //depricated
            if (upTimers.Any())
            {
                ExtractorSchedules = new List<ExtractorSchedule>();
                foreach (var ut in upTimers)
                {
                    ExtractorSchedules.Add(new ExtractorSchedule(ut));
                }
            }

            //Exclusion Stats
            var exclusionStats = settings.Elements("exclusionStats");
            if (exclusionStats.Any())
            {
                var stats = exclusionStats.Elements("stat");
                if (stats != null && stats.Any())
                {
                    ExclusionStats = new Dictionary<string, int>();
                    foreach (var s in stats)
                    {
                        var key = Input.GetAttribute(s, "name");
                        var value = Input.SafeIntConvert(Input.GetAttribute(s, "value"));
                        ExclusionStats.Add(key, value);
                    }
                }
            }

            #endregion
        }