Example #1
0
        public void ActivateMainWindow <T>(T dataContext)
        {
            IView view = new ContactsView();

            view.DataContext = dataContext;
            view.Show();
        }
Example #2
0
        private void ShowHideContactsView(Entity entity)
        {
            var contactsProvider = ViewModel as IContactsEntityProvider;

            if (entity != null && contactsProvider != null)
            {
                _contactsView = View.Subviews.OfType <ContactsView>().FirstOrDefault();
                if (_contactsView == null)
                {
                    InitializeContactsView(contactsProvider);

                    View.Add(_contactsView);
                    UIView.Animate(
                        UIConstants.AnimationDuration,
                        () => _contactsView.Alpha = 1);
                }

                _contactsView.Entity = entity;
            }
            else if (_contactsView != null)
            {
                UIView.Animate(
                    UIConstants.AnimationDuration,
                    () => _contactsView.Alpha = 0,
                    _contactsView.RemoveFromSuperview);

                DisposeContactsView();
            }
        }
        public static string GetContactsViewItem(RestCommand command, int userID)
        {
            ContactsViewItem contactsViewItem = ContactsView.GetContactsViewItem(command.LoginUser, userID);

            if (contactsViewItem.OrganizationID != command.Organization.OrganizationID)
            {
                throw new RestException(HttpStatusCode.Unauthorized);
            }
            return(contactsViewItem.GetXml("ContactsViewItem", true));
        }
        protected override void LoadData()
        {
            ContactsView contacts = new ContactsView(_loginUser);

            contacts.LoadForIndexing(_organizationID, _maxCount, _isRebuilding);
            foreach (ContactsViewItem contact in contacts)
            {
                _itemIDList.Add(contact.UserID);
            }
        }
Example #5
0
        private void InitializeContactsView(IContactsEntityProvider contactsProvider)
        {
            _contactsView = ContactsView.Create();

            SetDialogViewFullscreenFrame(_contactsView);

            _contactsView.CloseCommand             = contactsProvider.HideContactsCommand;
            _contactsView.CallPhoneCommand         = contactsProvider.CallPhoneCommand;
            _contactsView.ComposeEmailCommand      = contactsProvider.ComposeEmailCommand;
            _contactsView.ShowHideModalViewCommand = contactsProvider.ShowHideModalViewCommand;
        }
Example #6
0
 public MainWindowViewModel()//View First!
 {
     ShowAllContacts = new SimplerCommand
     {
         Action = () =>
         {
             var view = new ContactsView();
             view.DataContext = new ContactsViewModel(WorkUnitProvider);
             view.Show();
         }
     };
 }
Example #7
0
 private void DisposeContactsView()
 {
     if (_contactsView != null)
     {
         _contactsView.CloseCommand             = null;
         _contactsView.CallPhoneCommand         = null;
         _contactsView.ComposeEmailCommand      = null;
         _contactsView.ShowHideModalViewCommand = null;
         _contactsView.Dispose();
         _contactsView = null;
     }
 }
Example #8
0
 protected override void OnViewLoaded(object view)
 {
     cv = (ContactsView) view;
     base.OnViewLoaded(view);
     AppState.Imb.ClientChanged                -= Imb_ClientChanged;
     AppState.Imb.ClientChanged                += Imb_ClientChanged;
     AppState.Imb.Groups.CollectionChanged     -= Groups_CollectionChanged;
     AppState.Imb.Groups.CollectionChanged     += Groups_CollectionChanged;
     AppState.Imb.AllClients.CollectionChanged -= Clients_CollectionChanged;
     AppState.Imb.AllClients.CollectionChanged += Clients_CollectionChanged;
     AppState.Imb.PropertyChanged              -= Imb_PropertyChanged;
     AppState.Imb.PropertyChanged              += Imb_PropertyChanged;
     UpdateClients();
 }
Example #9
0
        public static void Contacts(string[] expression = null)
        {
            List <Contact> contacts      = Model.GetContacts(expression);
            int            contactNumber = ContactsView.Show(contacts);

            if (contactNumber > 0)
            {
                DetailContactController.DetailContact(contacts.ElementAt(contactNumber - 1));
            }
            else
            {
                MainMenuController.Menu();
            }
        }
        public static string GetContactsView(RestCommand command)
        {
            ContactsView contactsView = new ContactsView(command.LoginUser);

            contactsView.LoadByOrganizationID(command.Organization.OrganizationID);

            if (command.Format == RestFormat.XML)
            {
                return(contactsView.GetXml("ContactsView", "ContactsViewItem", true, command.Filters));
            }
            else
            {
                throw new RestException(HttpStatusCode.BadRequest, "Invalid data format");
            }
        }
Example #11
0
        public static string GetItems(RestCommand command, int organizationID, bool orderByDateCreated = false)
        {
            if (Organizations.GetOrganization(command.LoginUser, organizationID).ParentID != command.Organization.OrganizationID)
            {
                throw new RestException(HttpStatusCode.Unauthorized);
            }
            ContactsView items = new ContactsView(command.LoginUser);

            if (orderByDateCreated)
            {
                items.LoadByOrganizationID(organizationID, "DateCreated DESC");
            }
            else
            {
                items.LoadByOrganizationID(organizationID);
            }
            return(items.GetXml("Contacts", "Contact", true, command.Filters));
        }
Example #12
0
        public static string DeleteContact(RestCommand command, int id)
        {
            ContactsViewItem user = ContactsView.GetContactsViewItem(command.LoginUser, id);

            if (user == null)
            {
                throw new RestException(HttpStatusCode.BadRequest);
            }
            Organization organization = Organizations.GetOrganization(command.LoginUser, user.OrganizationID);

            if (organization.ParentID != command.Organization.OrganizationID)
            {
                throw new RestException(HttpStatusCode.Unauthorized);
            }
            string result = user.GetXml("Contact", true);

            Users.MarkUserDeleted(command.LoginUser, id);
            return(result);
        }
Example #13
0
        public static string GetTicketContacts(RestCommand command, int ticketIDOrNumber, bool orderByDateCreated = false)
        {
            TicketsViewItem ticket = TicketsView.GetTicketsViewItemByIdOrNumber(command.LoginUser, ticketIDOrNumber);

            if (ticket == null || ticket.OrganizationID != command.Organization.OrganizationID)
            {
                throw new RestException(HttpStatusCode.Unauthorized);
            }
            ContactsView contacts = new ContactsView(command.LoginUser);

            if (orderByDateCreated)
            {
                contacts.LoadByTicketID(ticket.TicketID, "ut.DateCreated DESC");
            }
            else
            {
                contacts.LoadByTicketID(ticket.TicketID);
            }
            return(contacts.GetXml("Contacts", "Contact", true, command.Filters));
        }
Example #14
0
        public static string GetItems(RestCommand command, bool orderByDateCreated = false, int?limitNumber = null, bool isCustomer = false)
        {
            ContactsView items     = new ContactsView(command.LoginUser);
            string       xmlString = string.Empty;

            try
            {
                if (orderByDateCreated)
                {
                    //This seems to be Zapier only
                    items.LoadByParentOrganizationID(command.Organization.OrganizationID, command.Filters, null, null, "DateCreated DESC", limitNumber, isCustomer);
                }
                else
                {
                    items.LoadByParentOrganizationID(command.Organization.OrganizationID, command.Filters, command.PageNumber, command.PageSize, isCustomer: isCustomer);
                }

                //SQL filtering was done already, there's no need for .NET filtering thus the empty collection for the last parameter
                xmlString = items.GetXml("Contacts", "Contact", true, new System.Collections.Specialized.NameValueCollection(), command.IsPaging);
            }
            catch (Exception ex)
            {
                //if something fails use the old method. This one does not have paging.
                //Something went wrong with the sql filtering and an exception was thrown and caught, .NET filtering will need to be done
                items = new ContactsView(command.LoginUser);

                if (orderByDateCreated)
                {
                    items.LoadByParentOrganizationID(command.Organization.OrganizationID, "DateCreated DESC", limitNumber);
                }
                else
                {
                    items.LoadByParentOrganizationID(command.Organization.OrganizationID);
                }

                xmlString = items.GetXml("Contacts", "Contact", true, command.Filters);
                ExceptionLogs.LogException(command.LoginUser, ex, "API", "RestContacts. GetItems(). SQL filtering generation failed, fell into old method.");
            }

            return(xmlString);
        }
Example #15
0
        public static string RemoveTicketContact(RestCommand command, int ticketIDOrNumber, int contactID)
        {
            TicketsViewItem ticket = TicketsView.GetTicketsViewItemByIdOrNumber(command.LoginUser, ticketIDOrNumber);

            if (ticket == null || ticket.OrganizationID != command.Organization.OrganizationID)
            {
                throw new RestException(HttpStatusCode.Unauthorized);
            }
            User         user         = Users.GetUser(command.LoginUser, contactID);
            Organization organization = Organizations.GetOrganization(command.LoginUser, user.OrganizationID);

            if (organization == null || organization.ParentID != command.Organization.OrganizationID)
            {
                throw new RestException(HttpStatusCode.Unauthorized);
            }

            Tickets tickets = new Tickets(command.LoginUser);

            tickets.RemoveContact(user.UserID, ticket.TicketID);
            return(ContactsView.GetContactsViewItem(command.LoginUser, user.UserID).GetXml("Contact", true));
        }
Example #16
0
        public static Panel createContact(User user, int PanelWidht, contactClick click)
        {
            ContactsView ConView = new ContactsView(PanelWidht);

            Button ava = new Button();

            ava.Text   = "";
            ava.Width  = ConView.ImageWidth;
            ava.Height = ConView.ImageHeight;
            ava.Left   = ConView.ImageLeft;
            ava.Top    = ConView.ImageTop;
            ava.Region = ConView.ImageRegion;
            ava.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
            ava.BackgroundImage       = View.getAvatar(user.avatarNumber);
            ava.Click += new EventHandler(click);

            Label name = new Label();

            name.Font   = new Font(name.Font.Name, 8.0f, name.Font.Style);
            name.Text   = user.Name + "#" + user.HostName;
            name.Left   = 2 * ConView.ImageLeft + ava.Width;
            name.Top    = ConView.LabelTop;
            name.Height = ConView.LabelHeight;
            name.Click += new EventHandler(click);

            Panel con = new Panel();

            con.Top    = View.lastHeightContacts;
            con.Width  = (int)(0.9 * PanelWidht);
            con.Text   = "";
            con.Height = Math.Max(ConView.ImageHeight + 2 * ConView.ImageTop, ConView.LabelHeight + 2 * ConView.LabelTop);
            con.Controls.Add(ava);
            con.Controls.Add(name);
            con.BorderStyle = BorderStyle.None;
            con.Click      += new EventHandler(click);

            View.lastHeightContacts += con.Height;
            return(con);
        }
Example #17
0
        private void OpenContactView(bool isSelectionMode)
        {
            if (_contactsView == null)
            {
                _logger.Info("show contacts view");
                _contactsView = Container.Resolve <ContactsView>();
                _contactsView.Show();

                var viewmodel = (ContactsViewModel)_contactsView.DataContext;
                viewmodel.IsSelectionMode = isSelectionMode;
            }
            else
            {
                _logger.Warn("contacts view already open");
                _logger.Info("push view in foreground");

                var viewmodel = (ContactsViewModel)_contactsView.DataContext;
                viewmodel.IsSelectionMode = isSelectionMode;

                _contactsView.Focus();
            }
        }
        private void ProcessReminder(Reminder reminder)
        {
            Logs.WriteLine();
            Logs.WriteEvent("***********************************************************************************");
            Logs.WriteEvent("Processing Reminder  ReminderID: " + reminder.ReminderID.ToString());
            Logs.WriteData(reminder.Row);
            Logs.WriteLine();
            Logs.WriteEvent("***********************************************************************************");

            MailMessage   message;
            UsersViewItem user = UsersView.GetUsersViewItem(LoginUser, (int)reminder.UserID);

            if (user == null)
            {
                return;
            }
            string description = "";

            switch (reminder.RefType)
            {
            case ReferenceType.Organizations:
                OrganizationsViewItem org = OrganizationsView.GetOrganizationsViewItem(LoginUser, reminder.RefID);
                if (org == null)
                {
                    return;
                }
                message = EmailTemplates.GetReminderCustomerEmail(LoginUser, reminder, user, org);

                description = String.Format("Reminder sent to {0} for Organization {1}", message.To.ToString(), org.Name);
                Logs.WriteEvent(description);
                ActionLogs.AddActionLog(LoginUser, ActionLogType.Insert, reminder.RefType, reminder.RefID, description);
                ActionLogs.AddActionLog(LoginUser, ActionLogType.Insert, ReferenceType.Organizations, org.OrganizationID, description);
                break;

            case ReferenceType.Tickets:
                TicketsViewItem ticket = TicketsView.GetTicketsViewItem(LoginUser, reminder.RefID);
                if (ticket == null)
                {
                    return;
                }
                message = EmailTemplates.GetReminderTicketEmail(LoginUser, reminder, user, ticket);
                EmailTemplates.ReplaceEmailRecipientParameters(LoginUser, message, Tickets.GetTicket(LoginUser, ticket.TicketID), reminder.UserID);     //vv

                TeamSupport.Data.Action action = (new Actions(LoginUser)).AddNewAction();
                action.ActionTypeID       = null;
                action.Name               = "Reminder";
                action.ActionSource       = "Reminder";
                action.SystemActionTypeID = SystemActionType.Reminder;
                action.Description        = String.Format("<p>The following is a reminder for {0} {1}:</p><p>&nbsp;</p><p>{2}</p>", user.FirstName, user.LastName, reminder.Description);
                action.IsVisibleOnPortal  = false;
                action.IsKnowledgeBase    = false;
                action.TicketID           = ticket.TicketID;
                action.Collection.Save();

                description = String.Format("Reminder sent to {0} for Ticket {1}", message.To.ToString(), ticket.TicketNumber.ToString());
                Logs.WriteEvent(description);
                ActionLogs.AddActionLog(LoginUser, ActionLogType.Insert, reminder.RefType, reminder.RefID, description);
                ActionLogs.AddActionLog(LoginUser, ActionLogType.Insert, ReferenceType.Tickets, ticket.TicketID, description);
                break;

            case ReferenceType.Contacts:
                ContactsViewItem contact = ContactsView.GetContactsViewItem(LoginUser, reminder.RefID);
                if (contact == null)
                {
                    return;
                }
                message     = EmailTemplates.GetReminderContactEmail(LoginUser, reminder, user, contact);
                description = String.Format("Reminder sent to {0} for Contact {1}", message.To.ToString(), contact.FirstName + " " + contact.LastName);
                Logs.WriteEvent(description);
                ActionLogs.AddActionLog(LoginUser, ActionLogType.Insert, reminder.RefType, reminder.RefID, description);
                ActionLogs.AddActionLog(LoginUser, ActionLogType.Insert, ReferenceType.Users, contact.UserID, description);
                break;

            case ReferenceType.Tasks:
                TasksViewItem task = TasksView.GetTasksViewItem(LoginUser, reminder.RefID);
                if (task == null || task.IsComplete)
                {
                    reminder.IsDismissed = true;
                    reminder.Collection.Save();
                    return;
                }
                message     = EmailTemplates.GetReminderTaskEmail(LoginUser, reminder, user, task);
                description = String.Format("Reminder sent to {0} for Task {1}", message.To.ToString(), task.Name);
                Logs.WriteEvent("ver. 05162017: " + description);
                ActionLogs.AddActionLog(LoginUser, ActionLogType.Insert, ReferenceType.Tasks, task.TaskID, description);
                ActionLogs.AddActionLog(LoginUser, ActionLogType.Insert, ReferenceType.Users, (int)reminder.UserID, description);

                TaskAssociations taskAssociations = new TaskAssociations(LoginUser);
                taskAssociations.LoadByTaskIDOnly(task.TaskID);

                foreach (TaskAssociation taskAssociation in taskAssociations)
                {
                    if (taskAssociation.RefType == (int)ReferenceType.Tickets)
                    {
                        TeamSupport.Data.Action taskAction = (new Actions(LoginUser)).AddNewAction();
                        taskAction.ActionTypeID       = null;
                        taskAction.Name               = "Reminder";
                        taskAction.ActionSource       = "Reminder";
                        taskAction.SystemActionTypeID = SystemActionType.Reminder;
                        taskAction.Description        = String.Format("<p>The following is a reminder for {0} {1}:</p><p>&nbsp;</p><p>{2}</p>", user.FirstName, user.LastName, reminder.Description);
                        taskAction.IsVisibleOnPortal  = false;
                        taskAction.IsKnowledgeBase    = false;
                        taskAction.TicketID           = taskAssociation.RefID;
                        try
                        {
                            taskAction.Collection.Save();
                        }
                        catch (Exception ex)
                        {
                            Logs.WriteEvent("Ex Reminder Action.Save: " + ex.StackTrace);
                        }
                    }
                }
                break;

            default:
                message = null;
                break;
            }

            if (message == null)
            {
                return;
            }

            reminder.HasEmailSent = true;
            reminder.Collection.Save();

            if (Emails.IsEmailDisabled(LoginUser, user.UserID, "Reminders"))
            {
                Logs.WriteEvent("Message skipped due to disabled user setting.");
            }
            else
            {
                MailAddress address = new MailAddress(user.Email, user.FirstName + " " + user.LastName);
                Logs.WriteEvent("Mail Address: " + address.ToString());
                message.To.Add(address);
                EmailTemplates.ReplaceMailAddressParameters(message);
                Emails.AddEmail(LoginUser, reminder.OrganizationID, null, message.Subject, message);
                Logs.WriteEvent("Message queued");
            }
        }
Example #19
0
 private void OnContactsViewClosedMsg(ContactsViewClosedMsg msg)
 {
     _logger.Info("set contacts view to null");
     _contactsView = null;
 }
Example #20
0
        public static string UpdateContact(RestCommand command, int id)
        {
            User user    = Users.GetUser(command.LoginUser, id);
            User oldUser = Users.GetUser(command.LoginUser, id);

            if (user == null)
            {
                throw new RestException(HttpStatusCode.BadRequest);
            }
            Organization organization = Organizations.GetOrganization(command.LoginUser, user.OrganizationID);

            if (organization.ParentID != command.Organization.OrganizationID)
            {
                throw new RestException(HttpStatusCode.Unauthorized);
            }

            bool allowOrganizationIdUpdate = true;

            user.ReadFromXml(command.Data, false, allowOrganizationIdUpdate);

            if (user.CryptedPassword != oldUser.CryptedPassword)
            {
                user.CryptedPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(user.CryptedPassword, "MD5");
            }

            bool isChangingOrganizationId = oldUser.OrganizationID != user.OrganizationID;

            if (isChangingOrganizationId)
            {
                Organization newOrganization = Organizations.GetOrganization(command.LoginUser, user.OrganizationID);
                if (newOrganization.ParentID != command.Organization.OrganizationID)
                {
                    throw new RestException(HttpStatusCode.Unauthorized);
                }

                //Let's follow the same reflexes as the UI (..\webapp\app_code\customerservice.cs SetContactCompany())
                Tickets t = new Tickets(command.LoginUser);
                t.LoadByContact(id);

                foreach (Ticket tix in t)
                {
                    tix.Collection.RemoveContact(id, tix.TicketID);
                }

                user.PortalAutoReg = false;

                user.Collection.Save();

                foreach (Ticket tix in t)
                {
                    tix.Collection.AddContact(id, tix.TicketID);
                }

                EmailPosts ep = new EmailPosts(command.LoginUser);
                ep.LoadByRecentUserID(id);
                ep.DeleteAll();
                ep.Save();
            }
            else
            {
                user.Collection.Save();
            }


            user.UpdateCustomFieldsFromXml(command.Data);
            return(ContactsView.GetContactsViewItem(command.LoginUser, user.UserID).GetXml("Contact", true));
        }
Example #21
0
        private void mi_Contacts_Click(object sender, RoutedEventArgs e)
        {
            ContactsView v = new ContactsView();

            v.ShowDialog();
        }
Example #22
0
 protected override void OnViewAttached(object view, object context)
 {
     base.OnViewAttached(view, context);
     myView = (view as ContactsView);
     refreshBinding();
 }
Example #23
0
        public static string CreateContact(RestCommand command, int?organizationID)
        {
            Addresses addresses = new Addresses(command.LoginUser);
            Address   address   = addresses.AddNewAddress();

            PhoneNumbers phoneNumbers = new PhoneNumbers(command.LoginUser);
            PhoneNumber  phoneNumber  = phoneNumbers.AddNewPhoneNumber();

            Users users = new Users(command.LoginUser);
            User  user  = users.AddNewUser();

            user.IsActive = true;
            user.FullReadFromXml(command.Data, true, ref phoneNumber, ref address);
            if (organizationID == null && user.OrganizationID == 0)
            {
                if (!String.IsNullOrEmpty(user.Email) && user.Email.Contains("@"))
                {
                    Organizations matchDomainCompany = new Organizations(command.LoginUser);
                    matchDomainCompany.LoadFirstDomainMatch(command.LoginUser.OrganizationID, user.Email.Substring(user.Email.LastIndexOf("@") + 1));
                    if (!matchDomainCompany.IsEmpty)
                    {
                        user.OrganizationID = matchDomainCompany[0].OrganizationID;
                    }
                }

                if (user.OrganizationID == 0)
                {
                    user.OrganizationID = Organizations.GetUnknownCompanyID(command.LoginUser);
                }
            }
            else if (organizationID != null)
            {
                user.OrganizationID = (int)organizationID;
            }
            user.ActivatedOn       = DateTime.UtcNow;
            user.LastLogin         = DateTime.UtcNow;
            user.LastActivity      = DateTime.UtcNow.AddHours(-1);
            user.IsPasswordExpired = true;
            user.NeedsIndexing     = true;

            if (!string.IsNullOrEmpty(user.CryptedPassword))
            {
                user.CryptedPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(user.CryptedPassword, "MD5");
            }

            user.Collection.Save();
            user.UpdateCustomFieldsFromXml(command.Data);

            if (!String.IsNullOrEmpty(phoneNumber.Number) || !String.IsNullOrEmpty(phoneNumber.Extension))
            {
                phoneNumber.RefType = ReferenceType.Users;
                phoneNumber.RefID   = user.UserID;
                phoneNumbers.Save();
            }

            if (!String.IsNullOrEmpty(address.Description) ||
                !String.IsNullOrEmpty(address.Addr1) ||
                !String.IsNullOrEmpty(address.Addr2) ||
                !String.IsNullOrEmpty(address.Addr3) ||
                !String.IsNullOrEmpty(address.City) ||
                !String.IsNullOrEmpty(address.Country) ||
                !String.IsNullOrEmpty(address.Description) ||
                !String.IsNullOrEmpty(address.State) ||
                !String.IsNullOrEmpty(address.Zip))
            {
                address.RefType = ReferenceType.Users;
                address.RefID   = user.UserID;
                addresses.Save();
            }

            return(ContactsView.GetContactsViewItem(command.LoginUser, user.UserID).GetXml("Contact", true));
        }
        protected override void GetNextRecord()
        {
            ContactsViewItem contact = ContactsView.GetContactsViewItem(_loginUser, _itemIDList[_rowIndex]);

            _lastItemID = contact.UserID;
            UpdatedItems.Add((int)_lastItemID);

            List <CustomerSearchPhone> phones = new List <CustomerSearchPhone>();
            StringBuilder builder             = new StringBuilder();

            if (!string.IsNullOrWhiteSpace(contact.Email))
            {
                builder.AppendLine(Regex.Replace(contact.Email, "[,.]+", ""));
            }
            PhoneNumbers phoneNumbers = new PhoneNumbers(_loginUser);

            phoneNumbers.LoadByID(contact.UserID, ReferenceType.Users);
            foreach (PhoneNumber number in phoneNumbers)
            {
                phones.Add(new CustomerSearchPhone(number));
                builder.AppendLine(Regex.Replace(number.Number, "[^0-9]", ""));
            }

            Addresses addresses = new Addresses(_loginUser);

            addresses.LoadByID(contact.UserID, ReferenceType.Users);
            foreach (Address address in addresses)
            {
                builder.AppendLine(address.Description
                                   + " " + address.Addr1
                                   + " " + address.Addr2
                                   + " " + address.Addr3
                                   + " " + address.City
                                   + " " + address.State
                                   + " " + address.Zip
                                   + " " + address.Country);
            }

            EmailAddresses emailAddresses = new EmailAddresses(_loginUser);

            emailAddresses.LoadByRefID(contact.UserID, ReferenceType.Users);
            foreach (EmailAddress emailAddress in emailAddresses)
            {
                builder.AppendLine(Regex.Replace(emailAddress.Email, "[,.]+", ""));
            }

            _docFields.Clear();
            AddDocField("UserID", contact.UserID);
            AddDocField("OrganizationID", contact.OrganizationID);
            AddDocField("Organization", contact.Organization);
            AddDocField("Email", contact.Email);
            AddDocField("IsActive", contact.IsActive);

            if (string.IsNullOrWhiteSpace(contact.FirstName))
            {
                AddDocField("Name", contact.LastName);
                DocDisplayName = string.IsNullOrWhiteSpace(contact.FirstName) ? "" : contact.FirstName.Trim();
            }
            else
            {
                AddDocField("Name", contact.FirstName + " " + contact.LastName);
                DocDisplayName = contact.LastName.Trim() + (string.IsNullOrWhiteSpace(contact.FirstName) ? "" : ", " + contact.FirstName.Trim());
            }

            builder.AppendLine(Regex.Replace(DocDisplayName, "[^a-zA-Z0-9 -]", ""));
            builder.AppendLine(Regex.Replace(contact.Organization, "[^a-zA-Z0-9 -]", ""));

            DocText = builder.ToString();

            CustomerSearchContact contactItem = new CustomerSearchContact(contact);

            contactItem.phones = phones.ToArray();
            TicketsView tickets = new TicketsView(_loginUser);

            contactItem.openTicketCount = tickets.GetUserTicketCount(contact.UserID, 0);

            AddDocField("**JSON", JsonConvert.SerializeObject(contactItem));

            CustomValues customValues = new CustomValues(_loginUser);

            customValues.LoadByReferenceType(_organizationID, ReferenceType.Contacts, contact.UserID);

            foreach (CustomValue value in customValues)
            {
                object o = value.Row["CustomValue"];
                string s = o == null || o == DBNull.Value ? "" : o.ToString();
                AddDocField(value.Row["Name"].ToString(), s);
            }

            DocFields       = _docFields.ToString();
            DocIsFile       = false;
            DocName         = contact.UserID.ToString();
            DocCreatedDate  = (DateTime)contact.Row["DateCreated"];
            DocModifiedDate = (DateTime)contact.Row["DateModified"];
        }
        private void ProcessCustomerInsights()
        {
            try
            {
                Logs.WriteEvent("********************** Starting Customer Insights Processor ***********************");
                Logs.WriteEvent(string.Format("Current Api Calls: Contact ({0}) Company ({1})", _currentContactApiCalls, _currentCompanyApiCalls));

                bool skipCompanyUpdates = (_currentCompanyApiCalls >= _maxCompanyApiCalls) || _noMoreRemainingCompanyCalls;
                bool skipContactUpdates = (_currentContactApiCalls >= _maxContactApiCalls) || _noMoreRemainingContactCalls;

                Organizations companies = new Organizations(LoginUser);
                companies.LoadByCustomerInsightsNewOrModifiedByDate(_lastProcessed.AddMinutes(-10), _waitBeforeNewUpdate);
                Logs.WriteEvent(string.Format("{0} companies recently updated or added since {1} were found on organizations with CustomerInsights active.", companies.Count, _lastProcessed.ToString()));

                if (!skipCompanyUpdates)
                {
                    foreach (Organization company in companies)
                    {
                        if (_currentCompanyApiCalls < _maxCompanyApiCalls)
                        {
                            SyncOrganizationInformation(company);
                        }
                        else
                        {
                            skipCompanyUpdates = true;
                            break;
                        }
                    }
                }

                ContactsView contacts = new ContactsView(LoginUser);
                contacts.LoadByCustomerInsightsNewOrModifiedByDate(_lastProcessed.AddMinutes(-10), _waitBeforeNewUpdate);
                Logs.WriteEvent(string.Format("{0} contacts recently updated or added since {1} were found on organizations with CustomerInsights active.", contacts.Count, _lastProcessed.ToString()));

                if (!skipContactUpdates)
                {
                    foreach (ContactsViewItem contact in contacts)
                    {
                        if (_currentContactApiCalls < _maxContactApiCalls)
                        {
                            SyncContactInformation(contact);
                        }
                        else
                        {
                            skipContactUpdates = true;
                            break;
                        }
                    }
                }

                if (!skipCompanyUpdates)
                {
                    Organizations companiesTotalTickets = new Organizations(LoginUser);
                    companiesTotalTickets.LoadByCustomerInsightsByCompanyTotalTickets(_waitBeforeNewUpdate, (int)_maxToProcessByTicketCount);
                    Logs.WriteEvent(string.Format("{0} companies on organizations with CustomerInsights active based on ticket count.", companiesTotalTickets.Count));

                    foreach (Organization company in companiesTotalTickets)
                    {
                        if (!companies.Where(p => p.OrganizationID == company.OrganizationID).Any())
                        {
                            if (_currentCompanyApiCalls < _maxCompanyApiCalls)
                            {
                                SyncOrganizationInformation(company);
                            }
                            else
                            {
                                skipCompanyUpdates = true;
                                break;
                            }
                        }
                    }
                }

                if (!skipContactUpdates)
                {
                    ContactsView contactsTotalTickets = new ContactsView(LoginUser);
                    contactsTotalTickets.LoadByCustomerInsightsByContactTotalTickets(_waitBeforeNewUpdate, (int)_maxToProcessByTicketCount);
                    Logs.WriteEvent(string.Format("{0} contacts on organizations with CustomerInsights active based on ticket count.", contactsTotalTickets.Count));

                    foreach (ContactsViewItem contact in contactsTotalTickets)
                    {
                        if (!contacts.Where(p => p.UserID == contact.UserID).Any())
                        {
                            if (_currentContactApiCalls < _maxContactApiCalls)
                            {
                                SyncContactInformation(contact);
                            }
                            else
                            {
                                skipContactUpdates = true;
                                break;
                            }
                        }
                    }
                }

                if (skipCompanyUpdates)
                {
                    Logs.WriteEventFormat("Maximum Company api calls {0} have been reached for this month.", _maxCompanyApiCalls);
                }

                if (skipContactUpdates)
                {
                    Logs.WriteEventFormat("Maximum Contact api calls {0} have been reached for this month.", _maxContactApiCalls);
                }
            }
            catch (Exception ex)
            {
                Logs.WriteException(ex);
            }

            Logs.WriteEvent("********************** Customer Insights Processor Finished **********************");
        }
 protected override Control CreateContentView()
 {
     return(_view ?? (_view = new ContactsView(ViewModel)));
 }