protected void Page_PreRender(object sender, EventArgs e)
    {
        // Check that the control is included in CMSPage (otherwise an exception is thrown on the Design tab)
        var page = Page as CMSPage;

        if (page == null || ContactGroup == null)
        {
            return;
        }

        // Disable refresh when status is ready as performance optimization
        timRefresh.Enabled = ContactGroup.ContactGroupStatus == ContactGroupStatusEnum.Rebuilding;

        if (ContactGroup.ContactGroupStatus == ContactGroupStatusEnum.Rebuilding)
        {
            lblRatio.Visible = false;
            lblCount.Visible = false;
            return;
        }

        int numberOfContacts = ContactGroupMemberInfoProvider.GetNumberOfContactsInGroup(ContactGroup.ContactGroupID);

        // Display number of contacts
        lblCount.InnerText = String.Format(GetString("om.contactgroup.numberofcontacts"), numberOfContacts);

        // Display ratio of the number of contacts
        int totalContactCount = ContactInfoProvider.GetContacts().Count;

        double ratio = (totalContactCount == 0) ? 0 : (double)numberOfContacts / totalContactCount * 100;

        lblRatio.InnerText = String.Format(GetString("om.contactgroup.numberofcontacts.ratio"), ratio);
    }
Пример #2
0
    /// <summary>
    /// Gets the automation state and move contact to previous step. Called when the "Move to previous step" button is pressed.
    /// Expects the CreateAutomationState method to be run first.
    /// </summary>
    private bool MoveContactToPreviousStep()
    {
        // Get dataset of contacts
        string where = "ContactLastName LIKE N'My New Contact%'";
        int topN = 1;
        InfoDataSet <ContactInfo> contacts = ContactInfoProvider.GetContacts(where, null, topN, null);

        // Get the process
        WorkflowInfo process = WorkflowInfoProvider.GetWorkflowInfo("MyNewProcess", WorkflowTypeEnum.Automation);

        if (!DataHelper.DataSourceIsEmpty(contacts) && (process != null))
        {
            // Get the contact from dataset
            ContactInfo contact = contacts.First <ContactInfo>();

            // Get the instance of automation manager
            AutomationManager manager = AutomationManager.GetInstance(CurrentUser);

            // Get the process state
            AutomationStateInfo state = contact.Processes.FirstItem as AutomationStateInfo;

            if (state != null)
            {
                // Move contact to next step
                manager.MoveToPreviousStep(contact, state, "Move to previous step");

                return(true);
            }
        }

        return(false);
    }
Пример #3
0
 private void DeleteOldContacts()
 {
     ContactInfoProvider.GetContacts()
     .WhereStartsWith("ContactFirstName", mContactFirstNamePrefix)
     .ToList()
     .ForEach(ContactInfoProvider.DeleteContactInfo);
 }
Пример #4
0
    /// <summary>
    /// Creates automation state. Called when the "Start process" button is pressed.
    /// Expects the CreateProcess, CreateProcessStep and CreateTemporaryObjects method to be run first.
    /// </summary>
    private bool CreateAutomationState()
    {
        // Get dataset of contacts
        string where = "ContactLastName LIKE N'My New Contact%'";
        int topN     = 1;
        var contacts = ContactInfoProvider.GetContacts().Where(where).TopN(topN);

        // Get the process
        WorkflowInfo process = WorkflowInfoProvider.GetWorkflowInfo("MyNewProcess", WorkflowTypeEnum.Automation);

        if (!DataHelper.DataSourceIsEmpty(contacts) && (process != null))
        {
            // Get the contact from dataset
            ContactInfo contact = contacts.First <ContactInfo>();

            // Get the instance of automation manager
            AutomationManager manager = AutomationManager.GetInstance(CurrentUser);

            // Start the process
            manager.StartProcess(contact, process.WorkflowID);

            return(true);
        }

        return(false);
    }
Пример #5
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Check that the control is included in CMSPage (otherwise an exception is thrown on the Design tab)
        var page = Page as CMSPage;

        if (page == null)
        {
            return;
        }

        var persona = UIContext.EditedObjectParent as PersonaInfo;

        if (persona == null)
        {
            return;
        }

        // Display number of contacts in persona
        int personaContactCount = PersonasFactory.GetPersonaService().GetContactsForPersona(persona).Count;

        lblCount.InnerText = String.Format(GetString("personas.ui.contactcount"), personaContactCount);

        // Display ratio of the number of contacts in persona to the number of all contacts
        int totalContactCount = ContactInfoProvider.GetContacts().Count;

        double ratio = (totalContactCount == 0) ? 0 : (double)personaContactCount / totalContactCount * 100;

        lblRatio.InnerText = String.Format(GetString("personas.ui.contactratio"), ratio);
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        // Check that the control is included in CMSPage (otherwise an exception is thrown on the Design tab)
        var page = Page as CMSPage;

        if (page == null)
        {
            return;
        }

        int personaID = QueryHelper.GetInteger("personaid", 0);

        if (personaID > 0)
        {
            PersonaInfo persona = PersonaInfoProvider.GetPersonaInfoById(personaID);
            if (persona != null)
            {
                // Display number of contacts in persona
                int personaContactCount = PersonasFactory.GetPersonaService().GetContactsForPersona(persona).Count;
                lblCount.InnerText = String.Format(GetString("personas.ui.contactcount"), personaContactCount);

                // Display ratio of the number of contacts in persona to the number of all contacts
                int totalContactCount = ContactInfoProvider.GetContacts()
                                        .OnSite(SiteContext.CurrentSiteID)
                                        .WhereNull("ContactMergedWithContactID")
                                        .Count;

                double ratio = (totalContactCount == 0) ? 0 : (double)personaContactCount / totalContactCount * 100;
                lblRatio.InnerText = String.Format(GetString("personas.ui.contactratio"), ratio);
            }
        }
    }
Пример #7
0
    /// <summary>
    /// Returns object query of automation states for my pending contacts which can be used as datasource for unigrid.
    /// </summary>
    /// <param name="user">User for whom pending contacts are shown</param>
    /// <param name="contactsWhereCondition">Where condition for filtering contacts</param>
    private ObjectQuery <AutomationStateInfo> GetPendingContacts(UserInfo user, string contactsWhereCondition)
    {
        // Get complete where condition for pending steps
        var condition = WorkflowStepInfoProvider.GetAutomationPendingStepsWhereCondition(user, SiteContext.CurrentSiteID);

        // Get automation steps specified by condition with permission control
        var automationWorkflowSteps = WorkflowStepInfoProvider.GetWorkflowSteps()
                                      .Where(condition)
                                      .Column("StepID")
                                      .WhereEquals("StepWorkflowType", (int)WorkflowTypeEnum.Automation);

        // Get all pending contacts from automation state where status is Pending and current user is the owner
        var allPendingContacts = AutomationStateInfoProvider.GetAutomationStates()
                                 .WhereIn("StateStepID", automationWorkflowSteps)
                                 .WhereEquals("StateStatus", (int)ProcessStatusEnum.Pending)
                                 .WhereEquals("StateObjectType", ContactInfo.OBJECT_TYPE);

        var contactIDs = ContactInfoProvider.GetContacts()
                         .Column("ContactID")
                         .Where(contactsWhereCondition);

        if (ShowOnlyMyPendingContacts)
        {
            contactIDs.WhereEquals("ContactOwnerUserID", user.UserID);
        }

        return(allPendingContacts.WhereIn("StateObjectID", contactIDs.AsMaterializedList("ContactID")));
    }
Пример #8
0
    /// <summary>
    /// Gets Where condition for filtering by the state. When using separated database, materializes the nested query on the other DB.
    /// </summary>
    private string GetStateCondition(TextSimpleFilter filter)
    {
        string originalQuery = filter.WhereCondition;

        if (String.IsNullOrEmpty(originalQuery))
        {
            return(string.Empty);
        }

        // Query with ContactInfo context has to be used in order to be able to determine DB context of the query (otherwise the materialization would not perform).
        var query = ContactInfoProvider.GetContacts()
                    .WhereIn("ContactStateID", StateInfoProvider
                             .GetStates()
                             .Where(originalQuery)
                             .Column(StateInfo.TYPEINFO.IDColumn)
                             );

        if (filter.FilterOperator == WhereBuilder.NOT_LIKE || filter.FilterOperator == WhereBuilder.NOT_EQUAL)
        {
            query = query.Or(new WhereCondition().WhereNull("ContactStateID"));
        }

        query.EnsureParameters();
        return(query.Parameters.Expand(query.WhereCondition));
    }
Пример #9
0
    /// <summary>
    /// Gets the automation state and move contact to specific step. Called when the "Move to specific step" button is pressed.
    /// Expects the CreateAutomationState method to be run first.
    /// </summary>
    private bool MoveContactToSpecificStep()
    {
        // Get dataset of contacts
        string where = "ContactLastName LIKE N'My New Contact%'";
        int topN     = 1;
        var contacts = ContactInfoProvider.GetContacts().Where(where).TopN(topN);

        // Get the process
        WorkflowInfo process = WorkflowInfoProvider.GetWorkflowInfo("MyNewProcess", WorkflowTypeEnum.Automation);

        if (!DataHelper.DataSourceIsEmpty(contacts) && (process != null))
        {
            // Get the contact from dataset
            ContactInfo contact = contacts.First <ContactInfo>();

            // Get the instance of automation manager
            AutomationManager manager = AutomationManager.GetInstance(CurrentUser);

            // Get the automation state
            AutomationStateInfo state = contact.Processes.FirstItem as AutomationStateInfo;

            if (state != null)
            {
                // Get the finished step
                WorkflowStepInfo finishedStep = manager.GetFinishedStep(contact, state);

                // Move contact to specific step
                manager.MoveToSpecificStep(contact, state, finishedStep, "Move to specific step");

                return(true);
            }
        }

        return(false);
    }
Пример #10
0
        public void Generate(GenerationOptions options)
        {
            try
            {
                if (options.GenerateContactStatuses)
                {
                    if (ContactStatusInfoProvider.GetContactStatuses().OnSite(mSiteId).Any())
                    {
                        Information("Contact statuses already exists");
                    }
                    else
                    {
                        new SampleContactStatusesGenerator(mSiteId).Generate();
                        Information("Contact statuses generated");
                    }
                }
                if (options.ContactsCount > 0)
                {
                    IPersonalDataGenerator personalDataGenerator = options.ContactsWithRealNames ?
                                                                   new RealPersonalDataGenerator() :
                                                                   (IPersonalDataGenerator) new StupidPersonalDataGenerator();
                    SampleContactsGenerator generator = new SampleContactsGenerator(personalDataGenerator, mSiteId);
                    generator.Generate(options.ContactsCount);
                    Information(options.ContactsCount + " contacts generated");
                }
                if (options.GeneratePersonas)
                {
                    ISamplePersonasGenerator personaGenerator = options.ContactsWithRealNames ?
                                                                new RealPersonasGenerator() :
                                                                (ISamplePersonasGenerator) new StupidPersonasGenerator();
                    personaGenerator.GeneratePersonas(mSiteId);
                    Information("Sample personas generated");
                }
                if (options.ScoresCount > 0)
                {
                    new SampleScoresGenerator().GenerateScores(options.ScoresCount, mSiteId);
                    Information(options.ScoresCount + " scores generated");
                }
                if (options.ActivitiesForEachExistingContactCount > 0)
                {
                    var contacts = ContactInfoProvider.GetContacts().OnSite(mSiteId);

                    var documents = DocumentHelper.GetDocuments()
                                    .PublishedVersion()
                                    .OnSite(mSiteId);

                    int activitiesGenerated = new SampleActivitiesGenerator().GenerateActivitiesForContacts(contacts, options.ActivitiesForEachExistingContactCount, documents.ToList());

                    Information(activitiesGenerated + " activities generated");
                }
            }
            catch (Exception e)
            {
                Error(e.Message);
            }
        }
Пример #11
0
    /// <summary>
    /// Delete contacts on SQL server.
    /// </summary>
    private void BatchDeleteOnSql()
    {
        while (!DataHelper.DataSourceIsEmpty(ds))
        {
            ContactInfoProvider.DeleteContactInfos(WhereCondition, 200);
            ds = ContactInfoProvider.GetContacts(WhereCondition, null, 1, "ContactID");
        }

        // Return to the list page with info label displayed
        ltlScript.Text += ScriptHelper.GetScript(ReturnScriptDeleteAsync);
    }
Пример #12
0
    protected void btnOk_Click(object sender, EventArgs e)
    {
        What   what   = (What)ValidationHelper.GetInteger(drpWhat.SelectedValue, 0);
        Action action = (Action)ValidationHelper.GetInteger(drpAction.SelectedValue, 0);

        // Check permissions for specified action
        CheckActionPermissions(action);

        // Set constraint for contact relations only
        var where = new WhereCondition()
                    .WhereEquals("ContactGroupMemberType", 0)
                    .WhereEquals("ContactGroupMemberContactGroupID", cgi.ContactGroupID);

        switch (what)
        {
        case What.All:
            var contactIds = ContactInfoProvider.GetContacts()
                             .Where(gridElem.WhereCondition)
                             .Where(gridElem.WhereClause)
                             .AsIDQuery();
            where.WhereIn("ContactGroupMemberRelatedID", contactIds);
            break;

        case What.Selected:
            where.WhereIn("ContactGroupMemberRelatedID", gridElem.SelectedItems);
            break;
        }

        switch (action)
        {
        case Action.Remove:
            RemoveContacts(what, where.ToString(true));
            break;

        case Action.ChangeStatus:
            ChangeStatus(what);
            break;

        case Action.StartNewProcess:
            StartNewProcess(what, where.ToString(true));
            break;

        default:
            return;
        }

        // Reload unigrid
        gridElem.ClearSelectedItems();
        gridElem.ReloadData();
        pnlUpdate.Update();
    }
Пример #13
0
 /// <summary>
 /// Delete items one by one.
 /// </summary>
 private void DeleteItems()
 {
     while (!DataHelper.DataSourceIsEmpty(ds))
     {
         // Delete the contacts
         foreach (DataRow dr in ds.Tables[0].Rows)
         {
             var ci = new ContactInfo(dr);
             AddLog((ci.ContactLastName + " " + ci.ContactFirstName).Trim());
             ContactHelper.Delete(ci, chkChildren.Checked, chkMoveRelations.Checked);
         }
         ds = ContactInfoProvider.GetContacts(WhereCondition, "ContactLastName", 500, null);
     }
 }
Пример #14
0
            public void Subscribe_Contact_OnlyOnceIsSubscribed()
            {
                var email   = "a-guid-" + Guid.NewGuid() + "@domain.com";
                var contact = GetContact(email);

                // Subscribe contact twice
                mNewsletterSubscriptionService.Subscribe(contact, mNewsletter, mNewsletterSubscriptionSettings);
                var result      = mNewsletterSubscriptionService.Subscribe(contact, mNewsletter, mNewsletterSubscriptionSettings);
                var subscribers = SubscriberNewsletterInfoProvider.GetSubscriberNewsletters().TypedResult;
                var contacts    = ContactInfoProvider.GetContacts();

                CMSAssert.All(
                    () => Assert.IsFalse(result, "No new subscription is expected."),
                    () => Assert.AreEqual(1, subscribers.Count(), "One subscription only should be present.")
                    );
            }
Пример #15
0
    /// <summary>
    /// Delete items one by one.
    /// </summary>
    private void DeleteItems()
    {
        while (!DataHelper.DataSourceIsEmpty(ds))
        {
            // Delete the contacts
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                var ci = new ContactInfo(dr);
                AddLog(HTMLHelper.HTMLEncode(ci.ContactLastName + " " + ci.ContactFirstName).Trim());
                ContactInfoProvider.DeleteContactInfo(ci);
            }

            ds = ContactInfoProvider.GetContacts()
                 .TopN(500)
                 .Where(WhereCondition)
                 .OrderBy("ContactLastName");
        }
    }
Пример #16
0
            public void Subscribe_NewContact_ContactIsStoredToDBAndSubscribed()
            {
                var email   = "a-guid-" + Guid.NewGuid() + "@domain.com";
                var contact = new ContactInfo()
                {
                    ContactEmail = email,
                };

                var result = mNewsletterSubscriptionService.Subscribe(contact, mNewsletter, mNewsletterSubscriptionSettings);

                var expectedSubscriber = SubscriberInfoProvider.GetSubscriberByEmail(email, mSite.SiteID);
                var subscribedContact  = ContactInfoProvider.GetContacts().WhereEquals("ContactEmail", email);

                CMSAssert.All(
                    () => Assert.IsTrue(result, "New subscription is expected."),
                    () => Assert.NotNull(subscribedContact, $"No contact for email '{email}' was created."),
                    () => Assert.NotNull(expectedSubscriber, $"No subscriber for email '{email}' was created.")
                    );
            }
Пример #17
0
    /// <summary>
    /// Creates temporary contact management - contact. Called when the "Create temporary objects" button is pressed.
    /// Expects the CreateTemporaryObjects method to be run first.
    /// </summary>
    private bool DeleteTemporaryObjects()
    {
        // Get dataset of contacts
        string where = "ContactLastName LIKE N'My New Contact%'";
        var contacts = ContactInfoProvider.GetContacts().Where(where);

        if (!DataHelper.DataSourceIsEmpty(contacts))
        {
            // Loop through the individual items
            foreach (ContactInfo contact in contacts)
            {
                // Delete the contact
                ContactInfoProvider.DeleteContactInfo(contact);
            }

            return(true);
        }

        return(false);
    }
Пример #18
0
    private void btnSplit_Click(object sender, EventArgs e)
    {
        if (ContactHelper.AuthorizedModifyContact(Contact.ContactSiteID, true))
        {
            if (gridElem.SelectedItems.Count > 0)
            {
                var contacts = ContactInfoProvider.GetContacts().WhereIn("ContactID", gridElem.SelectedItems.Select(c => c.ToInteger(0)).ToList());

                ContactHelper.SplitContacts(Contact, contacts.ToList(), chkCopyMissingFields.Checked, chkCopyActivities.Checked, chkRemoveAccounts.Checked);
                gridElem.ReloadData();
                gridElem.ClearSelectedItems();
                ShowConfirmation(GetString("om.contact.splitting"));
                pnlUpdate.Update();
            }
            else
            {
                ShowError(GetString("om.contact.selectcontactssplit"));
            }
        }
    }
Пример #19
0
    /// <summary>
    /// Remove contact from process. Called when the "Remove contact from process" button is pressed.
    /// Expects the CreateAutomationState method to be run first.
    /// </summary>
    private bool RemoveContactFromProcess()
    {
        // Get dataset of contacts
        string where = "ContactLastName LIKE N'My New Contact%'";
        int topN     = 1;
        var contacts = ContactInfoProvider.GetContacts().Where(where).TopN(topN);

        // Get the process
        WorkflowInfo process = WorkflowInfoProvider.GetWorkflowInfo("MyNewProcess", WorkflowTypeEnum.Automation);

        if (DataHelper.DataSourceIsEmpty(contacts) || (process == null))
        {
            return(false);
        }

        // Get the contact from dataset
        ContactInfo contact = contacts.First <ContactInfo>();

        // Get the instance of automation manager
        AutomationManager manager = AutomationManager.GetInstance(CurrentUser);

        // Get the states
        var states = AutomationStateInfoProvider.GetAutomationStates()
                     .WhereEquals("StateWorkflowID", process.WorkflowID)
                     .WhereEquals("StateObjectID", contact.ContactID)
                     .WhereEquals("StateObjectType", PredefinedObjectType.CONTACT);

        if (states.Any())
        {
            // Loop through the individual items
            foreach (AutomationStateInfo state in states)
            {
                // Remove contact from process
                manager.RemoveProcess(contact, state);
            }

            return(true);
        }

        return(false);
    }
        /// <summary>
        /// Generates contacts for customers. When database already contains contacts for given customers, new contatact is not created
        /// </summary>
        public IList <ContactInfo> Generate()
        {
            IList <ContactInfo> contacts;
            int numberOfContacts = ContactInfoProvider.GetContacts().Count;

            if (numberOfContacts < 50)
            {
                numberOfContacts = contactNames.Length;
                contacts         = new List <ContactInfo>();
                for (int i = 0; i < numberOfContacts; i++)
                {
                    contacts.Add(CreateContact(contactNames[i]));
                }
            }
            else
            {
                contacts = ContactInfoProvider.GetContacts().ToList();
            }

            return(contacts);
        }
Пример #21
0
    /// <summary>
    /// Delete items one by one.
    /// </summary>
    private void DeleteItems()
    {
        var connectionString = new SqlConnectionStringBuilder(ConnectionHelper.GetConnection().DataConnection.ConnectionString);

        connectionString.ConnectTimeout = SQL_TIMEOUT;

        while (!DataHelper.DataSourceIsEmpty(ds))
        {
            using (new CMSConnectionScope(connectionString.ToString(), true))
            {
                // Delete the contacts
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    var ci = new ContactInfo(dr);
                    AddLog((ci.ContactLastName + " " + ci.ContactFirstName).Trim());
                    ContactHelper.Delete(ci, chkChildren.Checked, chkMoveRelations.Checked);
                }
            }
            ds = ContactInfoProvider.GetContacts(WhereCondition, "ContactLastName", 500, null);
        }
    }
Пример #22
0
    /// <summary>
    /// Remove contact from process. Called when the "Remove contact from process" button is pressed.
    /// Expects the CreateAutomationState method to be run first.
    /// </summary>
    private bool RemoveContactFromProcess()
    {
        // Get dataset of contacts
        string where = "ContactLastName LIKE N'My New Contact%'";
        int topN = 1;
        InfoDataSet <ContactInfo> contacts = ContactInfoProvider.GetContacts(where, null, topN, null);

        // Get the process
        WorkflowInfo process = WorkflowInfoProvider.GetWorkflowInfo("MyNewProcess", WorkflowTypeEnum.Automation);

        if (!DataHelper.DataSourceIsEmpty(contacts) && (process != null))
        {
            // Get the contact from dataset
            ContactInfo contact = contacts.First <ContactInfo>();

            // Get the instance of automation manager
            AutomationManager manager = AutomationManager.GetInstance(CurrentUser);

            // Prepare the parameters
            where = "StateWorkflowID = " + process.WorkflowID + " AND StateObjectID = " + contact.ContactID + " AND StateObjectType = '" + PredefinedObjectType.CONTACT + "'";

            // Get the states
            InfoDataSet <AutomationStateInfo> states = AutomationStateInfoProvider.GetStates(where, null);

            if (!DataHelper.DataSourceIsEmpty(states))
            {
                // Loop through the individual items
                foreach (AutomationStateInfo state in states)
                {
                    // Remove contact from process
                    manager.RemoveProcess(contact, state);
                }

                return(true);
            }
        }

        return(false);
    }
Пример #23
0
    private void StartNewProcess(What what, string where)
    {
        try
        {
            string error     = String.Empty;
            int    processId = ValidationHelper.GetInteger(hdnIdentifier.Value, 0);

            switch (what)
            {
            case What.All:
                // Get selected IDs based on where condition
                var contactIdsQuery = ContactGroupMemberInfoProvider.GetRelationships().Where(where).Column("ContactGroupMemberRelatedID");
                var contactsQuery   = ContactInfoProvider.GetContacts().WhereIn("ContactId", contactIdsQuery);
                error = ExecuteProcess(processId, contactsQuery);
                break;

            case What.Selected:
                var contactIds = gridElem.SelectedItems;
                var query      = ContactInfoProvider.GetContacts().WhereIn("ContactId", contactIds);
                error = ExecuteProcess(processId, query);
                break;
            }

            if (String.IsNullOrEmpty(error))
            {
                string confirmation = GetString(what == What.All ? "ma.process.started" : "ma.process.startedselected");
                ShowConfirmation(confirmation);
            }
            else
            {
                ShowError(GetString("ma.process.error"), error, null);
            }
        }
        catch (Exception ex)
        {
            LogAndShowError("Automation", "STARTPROCESS", ex);
        }
    }
Пример #24
0
    /// <summary>
    /// Mass operation button "OK" click.
    /// </summary>
    protected void btnOk_Click(object sender, EventArgs e)
    {
        // Get where condition depending on mass action selection
        string where = null;

        What what = (What)ValidationHelper.GetInteger(drpWhat.SelectedValue, 0);

        switch (what)
        {
        // All items
        case What.All:
            where = SqlHelper.AddWhereCondition(gridElem.WhereCondition, gridElem.WhereClause);
            break;

        // Selected items
        case What.Selected:
            where = SqlHelper.GetWhereCondition <int>("ContactID", gridElem.SelectedItems, false);
            break;
        }

        Action action = (Action)ValidationHelper.GetInteger(drpAction.SelectedItem.Value, 0);

        switch (action)
        {
        // Action 'Change status'
        case Action.ChangeStatus:
            // Get selected status ID from hidden field
            int statusId = ValidationHelper.GetInteger(hdnIdentifier.Value, -1);
            // If status ID is 0, the status will be removed
            if (statusId >= 0)
            {
                ContactInfoProvider.UpdateContactStatus(statusId, where);
                ShowConfirmation(GetString("om.contact.massaction.statuschanged"));
            }
            break;

        // Action 'Add to contact group'
        case Action.AddToGroup:
            // Get contact group ID from hidden field
            int groupId = ValidationHelper.GetInteger(hdnIdentifier.Value, 0);
            if (groupId > 0)
            {
                var contactGroup = ContactGroupInfoProvider.GetContactGroupInfo(groupId);

                if (contactGroup == null)
                {
                    RedirectToAccessDenied(GetString("general.invalidparameters"));
                    return;
                }

                if (contactGroup.ContactGroupSiteID != CurrentSite.SiteID)
                {
                    RedirectToAccessDenied(GetString("general.invalidparameters"));
                    return;
                }

                IEnumerable <string> contactIds = null;

                switch (what)
                {
                // All items
                case What.All:
                    // Get selected IDs based on where condition
                    DataSet contacts = ContactInfoProvider.GetContacts().Where(where).Column("ContactID");
                    if (!DataHelper.DataSourceIsEmpty(contacts))
                    {
                        // Get array list with IDs
                        contactIds = DataHelper.GetUniqueValues(contacts.Tables[0], "ContactID", true);
                    }
                    break;

                // Selected items
                case What.Selected:
                    // Get selected IDs from unigrid
                    contactIds = gridElem.SelectedItems;
                    break;
                }

                if (contactIds != null)
                {
                    // Add each selected contact to the contact group, skip contacts that are already members of the group
                    foreach (string item in contactIds)
                    {
                        int contactId = item.ToInteger(0);

                        if (contactId > 0)
                        {
                            ContactGroupMemberInfoProvider.SetContactGroupMemberInfo(groupId, contactId, ContactGroupMemberTypeEnum.Contact, MemberAddedHowEnum.Manual);
                        }
                    }
                    // Show result message with contact group's display name
                    ShowConfirmation(String.Format(GetString("om.contact.massaction.addedtogroup"), ResHelper.LocalizeString(contactGroup.ContactGroupDisplayName)));
                }
            }
            break;

        // Merge click
        case Action.Merge:
            DataSet selectedContacts = ContactHelper.GetContactListInfos(null, where, null, -1, null);
            if (!DataHelper.DataSourceIsEmpty(selectedContacts))
            {
                // Get selected contact ID from hidden field
                int contactID = ValidationHelper.GetInteger(hdnIdentifier.Value, -1);
                // If contact ID is 0 then new contact must be created
                if (contactID == 0)
                {
                    int siteID;
                    if (filter.DisplaySiteSelector || filter.DisplayGlobalOrSiteSelector)
                    {
                        siteID = filter.SelectedSiteID;
                    }
                    else
                    {
                        siteID = SiteID;
                    }

                    SetDialogParameters(selectedContacts, ContactHelper.GetNewContact(ContactHelper.MERGED, true, siteID));
                }
                // Selected contact to be merged into
                else if (contactID > 0)
                {
                    SetDialogParameters(selectedContacts, ContactInfoProvider.GetContactInfo(contactID));
                }
                OpenWindow();
            }

            break;

        default:
            return;
        }

        // Reload unigrid
        gridElem.ResetSelection();
        gridElem.ReloadData();
        pnlUpdate.Update();
    }
Пример #25
0
        private IEnumerable <KeyValuePair <string, string> > GetMetricData()
        {
            string stringData = null;
            IEnumerable <KeyValuePair <string, string> > tupleData = null;

            // Gather data for each row, return special message if data is null
            switch (MetricCodeName)
            {
            // Categories
            case MetricDataEnum.support_metrics:
            case MetricDataEnum.support_metrics_system:
            case MetricDataEnum.support_metrics_environment:
            case MetricDataEnum.support_metrics_counters:
            case MetricDataEnum.support_metrics_ecommerce:
            case MetricDataEnum.support_metrics_tasks:
            case MetricDataEnum.support_metrics_eventlog:
                return(null);

                #region System

            case MetricDataEnum.support_metrics_system_version:
                stringData = CMSVersion.GetVersion(true, true, true, true);
                break;

            case MetricDataEnum.support_metrics_system_appname:
                stringData = SettingsHelper.AppSettings["CMSApplicationName"];
                break;

            case MetricDataEnum.support_metrics_system_instancename:
                stringData = SystemContext.InstanceName;
                break;

            case MetricDataEnum.support_metrics_system_physicalpath:
                stringData = SystemContext.WebApplicationPhysicalPath;
                break;

            case MetricDataEnum.support_metrics_system_apppath:
                stringData = SystemContext.ApplicationPath;
                break;

            case MetricDataEnum.support_metrics_system_uiculture:
                stringData = LocalizationContext.CurrentUICulture.CultureName;
                break;

            case MetricDataEnum.support_metrics_system_installtype:
                stringData = SystemContext.IsWebApplicationProject ? "Web App" : "Web site";
                break;

            case MetricDataEnum.support_metrics_system_portaltemplatepage:
                stringData = URLHelper.PortalTemplatePage;
                break;

            case MetricDataEnum.support_metrics_system_timesinceapprestart:
                stringData = (DateTime.Now - CMSApplication.ApplicationStart).ToString(@"dd\:hh\:mm\:ss");
                break;

            case MetricDataEnum.support_metrics_system_discoveredassemblies:
                tupleData = AssemblyDiscoveryHelper.GetAssemblies(true).Select((a, i) => GetKeyValuePair(i, a.FullName));
                break;

            case MetricDataEnum.support_metrics_system_targetframework:
                HttpRuntimeSection httpRuntime = ConfigurationManager.GetSection("system.web/httpRuntime") as HttpRuntimeSection;
                stringData = httpRuntime.TargetFramework;
                break;

            case MetricDataEnum.support_metrics_system_authmode:
                AuthenticationSection Authentication = ConfigurationManager.GetSection("system.web/authentication") as AuthenticationSection;
                stringData = Authentication?.Mode.ToString();
                break;

            case MetricDataEnum.support_metrics_system_sessionmode:
                SessionStateSection SessionState = ConfigurationManager.GetSection("system.web/sessionState") as SessionStateSection;
                stringData = SessionState?.Mode.ToString();
                break;

            case MetricDataEnum.support_metrics_system_debugmode:
                CompilationSection Compilation = ConfigurationManager.GetSection("system.web/compilation") as CompilationSection;
                stringData = Compilation?.Debug.ToString();
                break;

            case MetricDataEnum.support_metrics_system_runallmanagedmodules:
                var xmlDoc = new System.Xml.XmlDocument();
                xmlDoc.Load(URLHelper.GetPhysicalPath("~/Web.config"));
                stringData = xmlDoc.SelectSingleNode("/configuration/system.webServer/modules").Attributes["runAllManagedModulesForAllRequests"]?.Value;
                break;

                #endregion System

                #region Environment

            case MetricDataEnum.support_metrics_environment_trustlevel:

                AspNetHostingPermissionLevel trustLevel = AspNetHostingPermissionLevel.None;

                if (!SystemContext.IsWebSite)
                {
                    trustLevel = AspNetHostingPermissionLevel.Unrestricted;
                }

                // Check the trust level by evaluation of levels
                foreach (AspNetHostingPermissionLevel permissionLevel in new[] {
                    AspNetHostingPermissionLevel.Unrestricted,
                    AspNetHostingPermissionLevel.High,
                    AspNetHostingPermissionLevel.Medium,
                    AspNetHostingPermissionLevel.Low,
                    AspNetHostingPermissionLevel.Minimal
                })
                {
                    try
                    {
                        new AspNetHostingPermission(permissionLevel).Demand();
                    }
                    catch (SecurityException)
                    {
                        continue;
                    }

                    trustLevel = permissionLevel;
                    break;
                }

                stringData = trustLevel.ToString();
                break;

            case MetricDataEnum.support_metrics_environment_iisversion:
                stringData = MetricServerVariables["SERVER_SOFTWARE"];
                break;

            case MetricDataEnum.support_metrics_environment_https:
                stringData = MetricServerVariables["HTTPS"];
                break;

            case MetricDataEnum.support_metrics_environment_windowsversion:
                using (RegistryKey versionKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion"))
                {
                    var productName  = versionKey?.GetValue("ProductName");
                    var currentBuild = versionKey?.GetValue("CurrentBuild");
                    var releaseId    = versionKey?.GetValue("ReleaseId");

                    stringData = String.Format("{0}, build {1}, release {2}", productName.ToString(), currentBuild.ToString(), releaseId.ToString());
                }
                break;

            case MetricDataEnum.support_metrics_environment_netversion:
                using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\"))
                {
                    var keyValue = ndpKey?.GetValue("Release");
                    if (keyValue != null)
                    {
                        var releaseKey = (int)keyValue;
                        if (releaseKey >= 461808)
                        {
                            stringData = "4.7.2 or later";
                        }
                        else
                        if (releaseKey >= 461308)
                        {
                            stringData = "4.7.1";
                        }
                        else
                        if (releaseKey >= 460798)
                        {
                            stringData = "4.7";
                        }
                        else
                        if (releaseKey >= 394802)
                        {
                            stringData = "4.6.2";
                        }
                        else
                        if (releaseKey >= 394254)
                        {
                            stringData = "4.6.1";
                        }
                        else
                        if (releaseKey >= 393295)
                        {
                            stringData = "4.6";
                        }
                        else
                        if (releaseKey >= 379893)
                        {
                            stringData = "4.5.2";
                        }
                        else
                        if (releaseKey >= 378675)
                        {
                            stringData = "4.5.1";
                        }
                        else
                        if (releaseKey >= 378389)
                        {
                            stringData = "4.5";
                        }
                    }
                }
                break;

            case MetricDataEnum.support_metrics_environment_sqlserverversion:
                var dtm = new TableManager(null);
                stringData = dtm.DatabaseServerVersion;
                break;

            case MetricDataEnum.support_metrics_environment_azure:
                var azureStats = new Dictionary <string, string>(4)
                {
                    { "Is a Cloud Service", (SettingsHelper.AppSettings["CMSAzureProject"] == "true").ToString("false") },
                    { "Is file system on Azure", (SettingsHelper.AppSettings["CMSExternalStorageName"] == "azure").ToString("false") },
                    { "Azure storage account", SettingsHelper.AppSettings["CMSAzureAccountName"] ?? String.Empty },
                    { "Azure CDN endpoint", SettingsHelper.AppSettings["CMSAzureCDNEndpoint"] ?? String.Empty }
                };

                tupleData = azureStats.Select(s => GetKeyValuePair(s.Key, s.Value));
                break;

            case MetricDataEnum.support_metrics_environment_amazon:
                var amazonStats = new Dictionary <string, string>(3)
                {
                    { "Is file system on Amazon", (SettingsHelper.AppSettings["CMSExternalStorageName"] == "amazon").ToString() },
                    { "Amazon bucket name", SettingsHelper.AppSettings["CMSAmazonBucketName"] ?? String.Empty },
                    { "Amazon public access", SettingsHelper.AppSettings["CMSAmazonPublicAccess"] ?? String.Empty },
                };

                tupleData = amazonStats.Select(s => GetKeyValuePair(s.Key, s.Value));
                break;

            case MetricDataEnum.support_metrics_environment_services:
                tupleData = ServiceManager.GetServices().Select(s => GetKeyValuePair(s.ServiceName, s.Status));
                break;

                #endregion Environment

                #region Counters

            case MetricDataEnum.support_metrics_counters_webfarmservers:
                stringData = CoreServices.WebFarm.GetEnabledServerNames().Count().ToString();
                break;

            case MetricDataEnum.support_metrics_counters_stagingservers:
                stringData = ServerInfoProvider.GetServers().GetCount().ToString();
                break;

            case MetricDataEnum.support_metrics_counters_pagemostchildren:
                CMS.DocumentEngine.TreeProvider tree = new CMS.DocumentEngine.TreeProvider();

                var pageWithMostChildren = tree.SelectNodes().OnCurrentSite().Published()
                                           .ToDictionary(n => n, n => n.Children.Count)
                                           .Aggregate((l, r) => l.Value > r.Value ? l : r);

                tupleData = new[] { GetKeyValuePair(URLHelper.GetAbsoluteUrl("~" + pageWithMostChildren.Key.NodeAliasPath), pageWithMostChildren.Value) };
                break;

            case MetricDataEnum.support_metrics_counters_modules:
                stringData = ResourceInfoProvider.GetResources().GetCount().ToString();
                break;

            case MetricDataEnum.support_metrics_counters_medialibraries:
                stringData = MediaLibraryInfoProvider.GetMediaLibraries().WhereNull("LibraryGroupID").GetCount().ToString();
                break;

            case MetricDataEnum.support_metrics_counters_activities:
                stringData = ActivityInfoProvider.GetActivities().GetCount().ToString();
                break;

            case MetricDataEnum.support_metrics_counters_contacts:
                stringData = ContactInfoProvider.GetContacts().GetCount().ToString();
                break;

            case MetricDataEnum.support_metrics_counters_contactgroups:
                stringData = ContactGroupInfoProvider.GetContactGroups().GetCount().ToString();
                break;

            case MetricDataEnum.support_metrics_counters_omrules:
                stringData = RuleInfoProvider.GetRules().GetCount().ToString();
                break;

            case MetricDataEnum.support_metrics_counters_products:
                stringData = SKUInfoProvider.GetSKUs(SiteContext.CurrentSiteID).WhereNull("SKUOptionCategoryID").GetCount().ToString();
                break;

                #endregion Counters

                #region Tasks

            case MetricDataEnum.support_metrics_tasks_webfarm:
                stringData = WebFarmTaskInfoProvider.GetWebFarmTasks()
                             .WhereLessThan("TaskCreated", DateTime.Now.AddDays(-1))
                             .GetCount().ToString();
                break;

            case MetricDataEnum.support_metrics_tasks_staging:
                stringData = StagingTaskInfoProvider.GetTasks()
                             .WhereLessThan("TaskTime", DateTime.Now.AddDays(-1))
                             .GetCount().ToString();
                break;

            case MetricDataEnum.support_metrics_tasks_integration:
                stringData = IntegrationTaskInfoProvider.GetIntegrationTasks()
                             .WhereLessThan("TaskTime", DateTime.Now.AddDays(-1))
                             .GetCount().ToString();
                break;

            case MetricDataEnum.support_metrics_tasks_scheduled:
                stringData = TaskInfoProvider.GetTasks()
                             .WhereTrue("TaskDeleteAfterLastRun")
                             .WhereLessThan("TaskNextRunTime", DateTime.Now.AddDays(-1))
                             .GetCount().ToString();
                break;

            case MetricDataEnum.support_metrics_tasks_search:
                stringData = SearchTaskInfoProvider.GetSearchTasks()
                             .WhereLessThan("SearchTaskCreated", DateTime.Now.AddDays(-1))
                             .GetCount().ToString();
                break;

            case MetricDataEnum.support_metrics_tasks_email:
                stringData = EmailInfoProvider.GetEmailCount("EmailStatus = 1 AND EmailLastSendResult IS NOT NULL").ToString();
                break;

                #endregion Tasks

                #region Event log

            case MetricDataEnum.support_metrics_eventlog_macroerrors:
                var macroErrors = EventLogProvider.GetEvents()
                                  .WhereEquals("Source", "MacroResolver")
                                  .WhereGreaterThan("EventTime", DateTime.Now.Subtract(TimeSpan.FromDays(7)))
                                  .OrderByDescending("EventTime")
                                  .TopN(10);

                tupleData = macroErrors.Select(e =>
                                               GetKeyValuePair(String.Format("{0} from {1} at {2} in {3}", e.EventCode, e.Source, e.EventTime, e.EventMachineName),
                                                               e.EventDescription.Length > CUTOFF ? e.EventDescription.Substring(0, CUTOFF) : e.EventDescription)
                                               );
                break;

            case MetricDataEnum.support_metrics_eventlog_stagingerrors:
                var stagingErrors = EventLogProvider.GetEvents()
                                    .WhereEquals("Source", "staging")
                                    .WhereIn("EventType", new[] { "E", "W" })
                                    .WhereGreaterThan("EventTime", DateTime.Now.Subtract(TimeSpan.FromDays(7)))
                                    .OrderByDescending("EventTime")
                                    .TopN(10);

                tupleData = stagingErrors.Select(e =>
                                                 GetKeyValuePair(String.Format("{0} from {1} at {2} in {3}", e.EventCode, e.Source, e.EventTime, e.EventMachineName),
                                                                 e.EventDescription.Length > CUTOFF ? e.EventDescription.Substring(0, CUTOFF) : e.EventDescription)
                                                 );
                break;

            case MetricDataEnum.support_metrics_eventlog_searcherrors:
                var searchErrors = EventLogProvider.GetEvents()
                                   .WhereEquals("Source", "search")
                                   .WhereIn("EventType", new[] { "E", "W" })
                                   .WhereGreaterThan("EventTime", DateTime.Now.Subtract(TimeSpan.FromDays(7)))
                                   .OrderByDescending("EventTime")
                                   .TopN(10);

                tupleData = searchErrors.Select(e =>
                                                GetKeyValuePair(String.Format("{0} from {1} at {2} in {3}", e.EventCode, e.Source, e.EventTime, e.EventMachineName),
                                                                e.EventDescription.Length > CUTOFF ? e.EventDescription.Substring(0, CUTOFF) : e.EventDescription)
                                                );
                break;

            case MetricDataEnum.support_metrics_eventlog_contenterrors:
                var contentErrors = EventLogProvider.GetEvents()
                                    .WhereEquals("Source", "content")
                                    .WhereIn("EventType", new[] { "E", "W" })
                                    .WhereGreaterThan("EventTime", DateTime.Now.Subtract(TimeSpan.FromDays(7)))
                                    .OrderByDescending("EventTime")
                                    .TopN(10);

                tupleData = contentErrors.Select(e =>
                                                 GetKeyValuePair(String.Format("{0} from {1} at {2} in {3}", e.EventCode, e.Source, e.EventTime, e.EventMachineName),
                                                                 e.EventDescription.Length > CUTOFF ? e.EventDescription.Substring(0, CUTOFF) : e.EventDescription)
                                                 );
                break;

            case MetricDataEnum.support_metrics_eventlog_exceptions:
                var exceptions = EventLogProvider.GetEvents()
                                 .WhereEquals("EventCode", "exception")
                                 .WhereGreaterThan("EventTime", DateTime.Now.Subtract(TimeSpan.FromDays(7)))
                                 .OrderByDescending("EventTime")
                                 .TopN(10);

                tupleData = exceptions.Select(e =>
                                              GetKeyValuePair(String.Format("{0} from {1} at {2} in {3}", e.EventCode, e.Source, e.EventTime, e.EventMachineName),
                                                              e.EventDescription.Length > CUTOFF ? e.EventDescription.Substring(0, CUTOFF) : e.EventDescription)
                                              );
                break;

            case MetricDataEnum.support_metrics_eventlog_upgrade:

                EventLogInfo upgrade = EventLogProvider.GetEvents().WhereLike("Source", "upgrade%").FirstOrDefault();
                var          version = upgrade?.Source.Split(' ')[2];

                if (!String.IsNullOrEmpty(version))
                {
                    var parameters = new QueryDataParameters
                    {
                        { "@versionnumber", version }
                    };

                    var events = ConnectionHelper.ExecuteQuery("SupportHelper.CustomMetric.checkupgrade", parameters);

                    tupleData = (from DataRow row in events.Tables[0]?.Rows select row)
                                .Select(r => new EventLogInfo(r)).Select(e =>
                                                                         GetKeyValuePair(String.Format("{0} from {1} at {2} in {3}", e.EventCode, e.Source, e.EventTime, e.EventMachineName),
                                                                                         e.EventDescription.Length > CUTOFF ? e.EventDescription.Substring(0, CUTOFF) : e.EventDescription)
                                                                         );
                }
                break;

                #endregion Event log
            }

            if (tupleData?.Count() > 0)
            {
                return(tupleData);
            }

            if (stringData != null)
            {
                return(new[] { GetKeyValuePair(0, stringData) });
            }

            return(new[] { GetKeyValuePair(0, ResHelper.GetStringFormat("support.metrics.invalid", MetricDisplayName, MetricCodeName)) });
        }
 private void DeleteOldContacts()
 {
     ContactInfoProvider.GetContacts().WhereEndsWith("ContactEmail", _emailAddressPostfix).ToList()
     .ForEach(ContactInfoProvider.DeleteContactInfo);
 }
Пример #27
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Check hash validity
        if (QueryHelper.ValidateHash("hash"))
        {
            // Initialize events
            ctlAsync.OnFinished   += ctlAsync_OnFinished;
            ctlAsync.OnError      += ctlAsync_OnError;
            ctlAsync.OnRequestLog += ctlAsync_OnRequestLog;
            ctlAsync.OnCancel     += ctlAsync_OnCancel;

            issitemanager = ValidationHelper.GetBoolean(Parameters["issitemanager"], false);

            if (!RequestHelper.IsCallback())
            {
                // Setup page title text and image
                PageTitle.TitleText = GetString("om.contact.deletetitle");
                btnCancel.Attributes.Add("onclick", ctlAsync.GetCancelScript(true) + "return false;");
                titleElemAsync.TitleText = GetString("om.contact.deleting");
                // Set visibility of panels
                pnlContent.Visible = true;
                pnlLog.Visible     = false;

                // Get names of deleted contacts
                ds = ContactInfoProvider.GetContacts()
                     .TopN(500)
                     .Where(WhereCondition)
                     .OrderBy("ContactLastName");

                if (!DataHelper.DataSourceIsEmpty(ds))
                {
                    DataRowCollection rows = ds.Tables[0].Rows;

                    // Data set contains only one item...
                    if (rows.Count == 1)
                    {
                        // Get full contact name and use it in the title
                        string fullName = GetFullName(rows[0]);
                        if (!string.IsNullOrEmpty(fullName))
                        {
                            PageTitle.TitleText += " \"" + HTMLHelper.HTMLEncode(fullName) + "\"";
                        }
                        contactSiteId = ValidationHelper.GetInteger(DataHelper.GetDataRowValue(rows[0], "ContactSiteID"), 0);
                    }
                    else if (rows.Count > 1)
                    {
                        // Modify title and question for multiple items
                        PageTitle.TitleText         = GetString("om.contact.deletetitlemultiple");
                        headQuestion.ResourceString = "om.contact.deletemultiplequestion";
                        // Display list with names of deleted items
                        pnlContactList.Visible = true;

                        string        name    = null;
                        StringBuilder builder = new StringBuilder();

                        // Display top 500 records
                        for (int i = 0; i < (rows.Count); i++)
                        {
                            builder.Append("<div>");
                            name = GetFullName(rows[i]);
                            if (!string.IsNullOrEmpty(name))
                            {
                                builder.Append(HTMLHelper.HTMLEncode(name));
                            }
                            else
                            {
                                builder.Append("N/A");
                            }
                            builder.Append("</div>");
                        }
                        // Display three dots after last record
                        if (rows.Count >= 500)
                        {
                            builder.Append("...");
                        }

                        lblContacts.Text = builder.ToString();
                        contactSiteId    = SiteID;
                    }
                }
                else
                {
                    // Hide everything
                    pnlContent.Visible = false;
                }
            }
        }
        else
        {
            pnlDelete.Visible = false;
            ShowError(GetString("dialogs.badhashtext"));
        }
    }
Пример #28
0
    /// <summary>
    /// Mass operation button "OK" click.
    /// </summary>
    protected void btnOk_Click(object sender, EventArgs e)
    {
        string resultMessage = string.Empty;

        // Get where condition depending on mass action selection
        string where = null;

        What what = (What)ValidationHelper.GetInteger(drpWhat.SelectedValue, 0);

        switch (what)
        {
        // All items
        case What.All:
            where = gridElem.WhereCondition;
            break;

        // Selected items
        case What.Selected:
            where = SqlHelperClass.GetWhereCondition <int>("ContactID", (string[])gridElem.SelectedItems.ToArray(typeof(string)), false);
            break;
        }

        Action action = (Action)ValidationHelper.GetInteger(drpAction.SelectedItem.Value, 0);

        switch (action)
        {
        // Action 'Change status'
        case Action.ChangeStatus:
            // Get selected status ID from hidden field
            int statusId = ValidationHelper.GetInteger(hdnIdentificator.Value, -1);
            // If status ID is 0, the status will be removed
            if (statusId >= 0)
            {
                ContactInfoProvider.UpdateContactStatus(statusId, where);
                resultMessage = GetString("om.contact.massaction.statuschanged");
            }
            break;

        // Action 'Add to contact group'
        case Action.AddToGroup:
            // Get contact group ID from hidden field
            int groupId = ValidationHelper.GetInteger(hdnIdentificator.Value, 0);
            if (groupId > 0)
            {
                ArrayList contactIds = null;
                switch (what)
                {
                // All items
                case What.All:
                    // Get selected IDs based on where condition
                    DataSet contacts = ContactInfoProvider.GetContacts(where, null, 0, "ContactID");
                    if (!DataHelper.DataSourceIsEmpty(contacts))
                    {
                        // Get array list with IDs
                        contactIds = DataHelper.GetUniqueValues(contacts.Tables[0], "ContactID", true);
                    }
                    break;

                // Selected items
                case What.Selected:
                    // Get selected IDs from unigrid
                    contactIds = gridElem.SelectedItems;
                    break;
                }

                if (contactIds != null)
                {
                    int contactId = 0;
                    // Add each selected contact to the contact group, skip contacts that are already members of the group
                    foreach (string item in contactIds)
                    {
                        contactId = ValidationHelper.GetInteger(item, 0);
                        if (contactId > 0)
                        {
                            ContactGroupMemberInfoProvider.SetContactGroupMemberInfo(groupId, contactId, ContactGroupMemberTypeEnum.Contact, MemberAddedHowEnum.Manual);
                        }
                    }
                    // Get contact group to show result message with its display name
                    ContactGroupInfo group = ContactGroupInfoProvider.GetContactGroupInfo(groupId);
                    if (group != null)
                    {
                        resultMessage = String.Format(GetString("om.contact.massaction.addedtogroup"), group.ContactGroupDisplayName);
                    }
                }
            }
            break;

        // Merge click
        case Action.Merge:
            DataSet selectedContacts = ContactHelper.GetContactListInfos(null, where, null, -1, null);
            if (!DataHelper.DataSourceIsEmpty(selectedContacts))
            {
                // Get selected contact ID from hidden field
                int contactID = ValidationHelper.GetInteger(hdnIdentificator.Value, -1);
                // If contact ID is 0 then new contact must be created
                if (contactID == 0)
                {
                    int siteID;
                    if (filter.DisplaySiteSelector || filter.DisplayGlobalOrSiteSelector)
                    {
                        siteID = filter.SelectedSiteID;
                    }
                    else
                    {
                        siteID = SiteID;
                    }

                    SetDialogParameters(selectedContacts, ContactHelper.GetNewContact(ContactHelper.MERGED, true, siteID));
                }
                // Selected contact to be merged into
                else if (contactID > 0)
                {
                    SetDialogParameters(selectedContacts, ContactInfoProvider.GetContactInfo(contactID));
                }
                OpenWindow();
            }

            break;

        default:
            return;
        }

        if (!string.IsNullOrEmpty(resultMessage))
        {
            lblInfo.Text    = resultMessage;
            lblInfo.Visible = true;
        }

        // Reload unigrid
        gridElem.ClearSelectedItems();
        gridElem.ReloadData();
        pnlUpdate.Update();
    }