using System; using System.Collections; using System.Linq; using System.Web.UI; using System.Web.UI.WebControls; using CMS.DataCom; using CMS.EventLog; using CMS.ExtendedControls.ActionsConfig; using CMS.GlobalHelper; using CMS.OnlineMarketing; using CMS.SettingsProvider; using CMS.UIControls; using CMS.CMSHelper; using System.Net; using System.Web; /// /// Provides UI elements to display and edit CMS contact and possibly update it from the specified Data.com contact. /// [EditedObject(OnlineMarketingObjectType.CONTACT, "contactId")] public partial class CMSModules_ContactManagement_Pages_Tools_Contact_Tab_DataCom : CMSDataComPage, ICallbackEventHandler { #region "Variables" /// /// New instance of credential provider. /// private readonly ICredentialProvider credentialProvider = new UserCredentialProvider(CMSContext.CurrentUser); #endregion #region "Properties" /// /// Gets or sets the Data.com contact to display side-by-side with the CMS contact. /// public Contact Contact { get { return ViewState["DataComContact"] as Contact; } set { ViewState["DataComContact"] = value; } } /// /// Gets or sets the suggested Data.com contact filter when the Data.com search didn't return an exact match. /// public ContactFilter Filter { get; set; } /// /// Gets the site identifier of the edited contact. /// public int ContactSiteID { get { return ContactHelper.ObjectSiteID(EditedObject); } } /// /// Gets the unique identifier to pass the parameters on to the Data.com contact selection dialog window. /// private string ParametersIdentifier { get { string identifier = ViewState["PID"] as string; if (identifier == null) { identifier = Guid.NewGuid().ToString("N"); ViewState["PID"] = identifier; } return identifier; } } /// /// Gets the unique identifier to pass the parameters on to the Data.com Buy contact dialog window. /// private string BuyParametersIdentifier { get { string identifier = ViewState["BuyPID"] as string; if (identifier == null) { identifier = Guid.NewGuid().ToString("N"); ViewState["BuyPID"] = identifier; } return identifier; } } /// /// Returns redirect url to login page. /// private string LoginPageUrl { get { var url = "~/CMSModules/ContactManagement/Pages/Tools/DataCom/Login.aspx"; url = URLHelper.AddParameterToUrl(url, "returnurl", HttpUtility.UrlEncode(URLHelper.CurrentURL)); return url; } } #endregion #region "Life cycle methods" protected override void OnInit(EventArgs e) { base.OnInit(e); ContactInfo contact = EditedObject as ContactInfo; AuthorizeReadRequest(contact); ScriptHelper.RegisterDialogScript(Page); } protected void Page_Load(object sender, EventArgs e) { // Do not check login if it's a CallBack - search button was pressed (see CreateSearchActionClientScript method) if (!RequestHelper.IsCallback()) { bool validCredential = false; try { validCredential = CheckCredential(); } catch (Exception ex) { HandleException(ex); return; } if (!validCredential) { URLHelper.Redirect(LoginPageUrl); } } try { if (!String.IsNullOrEmpty(ContactHiddenField.Value)) { JsonSerializer serializer = new JsonSerializer(); Contact freshContact = serializer.Unserialize(ContactHiddenField.Value); if (Contact == null) { ContactForm.MergeHint = true; } else { if (Contact.ContactId != freshContact.ContactId) { ContactForm.MergeHint = true; } else if (String.IsNullOrEmpty(Contact.Phone) && String.IsNullOrEmpty(Contact.Email) && (!String.IsNullOrEmpty(freshContact.Phone) || !String.IsNullOrEmpty(freshContact.Email))) { ContactForm.MergeHint = true; ContactForm.MergeHintAttributes = new string[] { "Phone", "Email" }; } } Contact = freshContact; } ContactInfo contactInfo = EditedObject as ContactInfo; ContactIdentity identity = DataComHelper.CreateContactIdentity(contactInfo); Filter = identity.CreateFilter(); // Do not search for contact if it's a CallBack - search button was pressed (see CreateSearchActionClientScript method) if (Contact == null && !RequestHelper.IsCallback()) { DataComClient client = DataComHelper.CreateClient(); IContactProvider provider = DataComHelper.CreateContactProvider(client, credentialProvider.GetCredential()); ContactFinder finder = DataComHelper.CreateContactFinder(provider); Contact match = finder.Find(identity); if (match != null) { ShowInformation(GetString("datacom.contactmatch")); Contact = match; ContactForm.MergeHint = true; } else { ShowInformation(GetString("datacom.nocontactmatch")); } } InitializeHeaderActions(); InitializeDataComForm(); } catch (Exception exception) { HandleException(exception); } } protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); if (Contact == null) { ContactFormPanel.CssClass = "Hidden"; HeaderAction action = HeaderActions.ActionsList.SingleOrDefault(x => x.CommandName == "save"); if (action != null) { action.Visible = false; } } } protected void HeaderActions_ActionPerformed(object sender, CommandEventArgs e) { switch (e.CommandName.ToLowerInvariant()) { case "save": ContactInfo contact = EditedObject as ContactInfo; AuthorizeModifyRequest(contact); try { if (ContactForm.Validate() && ContactForm.Store()) { ContactForm.Merge(); BaseInfo data = ContactForm.Data as BaseInfo; data.Generalized.SetObject(); Filter = null; ShowChangesSaved(); } } catch (Exception exception) { HandleException(exception); } break; case "logout": credentialProvider.SetCredential(new NetworkCredential()); URLHelper.Redirect(LoginPageUrl); break; } } #endregion #region "Private methods" /// /// Initializes the form with the required dependencies and the specified CMS contact. /// protected void InitializeDataComForm() { IDataComConfiguration configuration = DataComHelper.GetConfiguration(ContactSiteID); ContactInfo contactInfo = EditedObject as ContactInfo; ContactForm.ParametersIdentifier = BuyParametersIdentifier; ContactForm.FormInformation = DataComHelper.GetContactFormInfo(); ContactForm.EntityInfo = DataComHelper.GetContactEntityInfo(); ContactForm.EntityMapping = configuration.GetContactMapping(); ContactForm.EntityAttributeMapperFactory = DataComHelper.GetContactAttributeMapperFactory(); ContactForm.Entity = Contact; ContactForm.EntityAttributeFormatter = DataComHelper.GetEntityAttributeFormatter(); ContactForm.BuyContactEnabled = (credentialProvider.GetCredential() != null); ContactForm.DefaultFieldLayout = CMS.FormControls.FieldLayoutEnum.ThreeColumns; ContactForm.DefaultFormLayout = CMS.FormEngine.FormLayoutEnum.Standard; ContactForm.Restore(contactInfo); } /// /// Adds actions to the page header. /// protected void InitializeHeaderActions() { AddHeaderActions(new HeaderAction { ControlType = HeaderActionTypeEnum.LinkButton, Text = GetString("general.apply"), ImageUrl = GetImageUrl("CMSModules/CMS_Content/EditMenu/save.png"), CommandName = "save", RegisterShortcutScript = true }); AddHeaderActions(new HeaderAction { ControlType = HeaderActionTypeEnum.LinkButton, Text = GetString("general.search"), ImageUrl = GetImageUrl("CMSModules/CMS_ContactManagement/search.png"), OnClientClick = CreateSearchActionClientScript() }); AddHeaderActions(new HeaderAction { Text = string.Format(GetString("datacom.logout"), credentialProvider.GetCredential().UserName), GenerateSeparatorBeforeAction = true, ImageUrl = GetImageUrl("CMSModules/CMS_PortalEngine/OnSiteEdit/signout.png"), CommandName = "logout", OnClientClick = "return confirm('" + GetString("datacom.automation.confirmlogout") + "')" }); HeaderActions.ActionPerformed += HeaderActions_ActionPerformed; } /// /// Creates a client script to open the dialog window to select a Data.com contact, and returns it. /// /// A client script to open the dialog window to select a Data.com contact. protected string CreateSearchActionClientScript() { string baseUrl = URLHelper.ResolveUrl("~/CMSModules/ContactManagement/Pages/Tools/DataCom/SelectContact.aspx?ContactID=" + ((ContactInfo)EditedObject).ContactID + "&SiteID=" + CMSContext.CurrentSiteID); string url = String.Format("{0}&pid={1}", baseUrl, ParametersIdentifier); string script = String.Format("function DataCom_SelectContact (arg, context) {{ modalDialog('{0}', 'SelectContact', '1000', '700', null); return false; }}", URLHelper.AddParameterToUrl(url, "hash", QueryHelper.GetHash(url))); ScriptHelper.RegisterClientScriptBlock(this, GetType(), "DataCom_SelectContact", script, true); return String.Format("{0}; return false;", Page.ClientScript.GetCallbackEventReference(this, null, "DataCom_SelectContact", null)); } /// /// Displays an error message and logs the specified exception to the event log. /// /// The exception to handle. private void HandleException(Exception exception) { ErrorSummary.Report(exception); EventLogProvider.LogException("Data.com Connector", "ContactPage", exception); } /// /// Checks whether is user has provided credential to DataCom or not. If not, user is redirected to login page. /// /// Might be thrown when error occurs in communicating with Data.com private bool CheckCredential() { var credential = credentialProvider.GetCredential(); var client = DataComHelper.CreateClient(); return (credential != null && client.UserIsValid(credential)); } #endregion #region ICallbackEventHandler Members string ICallbackEventHandler.GetCallbackResult() { return null; } void ICallbackEventHandler.RaiseCallbackEvent(string eventArgument) { JsonSerializer serializer = new JsonSerializer(); Hashtable parameters = new Hashtable(); if (Filter != null) { parameters["Filter"] = serializer.Serialize(Filter); } parameters["SiteID"] = ContactSiteID; WindowHelper.Add(ParametersIdentifier, parameters); } #endregion }