protected void Page_Load(object sender, EventArgs e) { btnClose.Text = GetString("General.Close"); bool noCompare = ValidationHelper.GetBoolean(QueryHelper.GetString("nocompare", string.Empty), false); // Initialize view version control viewVersion.NoComparison = noCompare; int versionId = ValidationHelper.GetInteger(QueryHelper.GetString("versionhistoryid", string.Empty), 0); viewVersion.VersionCompareID = ValidationHelper.GetInteger(QueryHelper.GetString("comparehistoryid", string.Empty), 0); // Get version to initialize title ObjectVersionHistoryInfo version = ObjectVersionHistoryInfoProvider.GetVersionHistoryInfo(versionId); if (version != null) { string objectType = version.VersionObjectType; string objType = GetString("ObjectType." + objectType.Replace(".", "_")); string title = String.Format(GetString("objectversioning.viewversion.title"), objType, HTMLHelper.HTMLEncode(ResHelper.LocalizeString(version.VersionObjectDisplayName))); // Set title - do not display context help when comparison not available string helpTopic = noCompare ? null : "objectversioning_viewversion"; this.SetTitle("CMSModules/CMS_ObjectVersioning/viewversion.png", title, helpTopic, "Object versioning - View version"); viewVersion.Version = version; // Exclude site binding table data GeneralizedInfo infoObj = TranslationHelper.GetReadOnlyObject(objectType); viewVersion.ExcludedTableNames = CMSObjectHelper.GetTableName(infoObj.TypeInfo.SiteBindingObject); } // Set what data should be displayed bool showAll = ValidationHelper.GetBoolean(QueryHelper.GetBoolean("showall", false), false); viewVersion.ObjectDataOnly = !showAll; }
public override bool LoadData(ActivityInfo ai) { if ((ai == null) || !ModuleManager.IsModuleLoaded(ModuleName.MESSAGEBOARD)) { return(false); } switch (ai.ActivityType) { case PredefinedActivityType.MESSAGE_BOARD_COMMENT: case PredefinedActivityType.SUBSCRIPTION_MESSAGE_BOARD: break; default: return(false); } int nodeId = ai.ActivityNodeID; lblDocIDVal.Text = GetLinkForDocument(nodeId, ai.ActivityCulture); if (ai.ActivityType == PredefinedActivityType.MESSAGE_BOARD_COMMENT) { plcComment.Visible = true; GeneralizedInfo iinfo = ModuleCommands.MessageBoardGetBoardMessageInfo(ai.ActivityItemDetailID); if (iinfo != null) { txtComment.Text = ValidationHelper.GetString(iinfo.GetValue("MessageText"), null); } } return(true); }
protected void Page_Init(object sender, EventArgs e) { // Setup the control relElem.ObjectID = QueryHelper.GetInteger("objectid", 0); relElem.ObjectType = QueryHelper.GetString("objecttype", ""); GeneralizedInfo obj = relElem.Object; if (obj != null) { // Set the master page title Title = String.Format(GetString("ObjectRelationships.Title"), GetString("objecttype." + obj.ObjectType.Replace(".", "_").Replace("#", "_")), HTMLHelper.HTMLEncode(obj.ObjectDisplayName)); PageTitle.TitleText = Title; CurrentMaster.PanelContent.RemoveCssClass("dialog-content"); CurrentMaster.MessagesPlaceHolder.OffsetX = 8; CurrentMaster.MessagesPlaceHolder.OffsetY = 8; btnAnother.Click += (s, ea) => relElem.Save(); var master = CurrentMaster as ICMSModalMasterPage; if (master != null) { master.Save += (s, ea) => relElem.SaveAndClose(); master.ShowSaveAndCloseButton(); // The button shouldn't have save&close label, because it doesn't seem like it closes - it redirects to a listing of all relationships master.SetSaveResourceString("general.save"); } } }
/// <summary> /// Suitable for implementation of synchronous outcoming object processing. Identifiers of object are in their original state. /// </summary> /// <param name="infoObj">Object to process</param> /// <param name="taskType">Type of task</param> /// <param name="siteName">Name of site</param> /// <param name="errorMessage">Possible error message</param> /// <returns>Processing result</returns> public override IntegrationProcessResultEnum ProcessInternalTaskSync(GeneralizedInfo infoObj, TaskTypeEnum taskType, string siteName, out string errorMessage) { // Synchronous processing of objects (meaning processing is executed in the context of CMS right away) // (task is not being logged and processed afterwards in separate thread as in ProcessInternalTaskAsync method) errorMessage = null; return(IntegrationProcessResultEnum.OK); }
public override bool LoadData(ActivityInfo ai) { if ((ai == null) || !ModuleEntry.IsModuleLoaded(ModuleEntry.NEWSLETTER) || (ai.ActivityType != PredefinedActivityType.NEWSLETTER_CLICKTHROUGH)) { return(false); } // Get newsletter name int nesletterId = ai.ActivityItemID; GeneralizedInfo iinfo = ModuleCommands.NewsletterGetNewsletterInfo(nesletterId); if (iinfo != null) { string subject = ValidationHelper.GetString(iinfo.GetValue("NewsletterDisplayName"), null); ucDetails.AddRow("om.activitydetails.newsletter", subject); } // Get issue subject int issueId = ai.ActivityItemDetailID; iinfo = ModuleCommands.NewsletterGetNewsletterIssueInfo(issueId); if (iinfo != null) { string subject = ValidationHelper.GetString(iinfo.GetValue("IssueSubject"), null); ucDetails.AddRow("om.activitydetails.newsletterissue", MacroResolver.RemoveSecurityParameters(subject, true, null)); } string targetLink = ai.ActivityURL; ucDetails.AddRow("om.activitydetails.newstargetlink", GetLink(targetLink, targetLink), false); return(ucDetails.IsDataLoaded); }
/// <summary> /// Ensure user friendly file name /// </summary> /// <param name="infoObj">Object to be exported</param> /// <param name="backup">Indicates if export is treated as backup</param> private string GetExportFileName(GeneralizedInfo infoObj, bool backup) { string fileName = null; // Get file name accrding to accesible object properties if (infoObj.TypeInfo.CodeNameColumn != TypeInfo.COLUMN_NAME_UNKNOWN) { fileName = infoObj.ObjectCodeName; } else if (infoObj.TypeInfo.DisplayNameColumn != TypeInfo.COLUMN_NAME_UNKNOWN) { fileName = ValidationHelper.GetCodeName(infoObj.ObjectDisplayName); } else { fileName = ValidationHelper.GetCodeName(infoObj.ObjectGUID.ToString()); } fileName = fileName.Replace(".", "_") + "_" + DateTime.Now.ToString("yyyyMMdd") + "_" + DateTime.Now.ToString("HHmm") + ".zip"; fileName = ValidationHelper.GetSafeFileName(fileName); // Backup use short file name, in other cases use long file name with object type if (!backup) { string objectType = infoObj.TypeInfo.Inherited ? infoObj.TypeInfo.OriginalObjectType : infoObj.ObjectType; fileName = objectType.Replace(".", "_") + "_" + fileName; } return(fileName); }
/// <summary> /// Initialize filter controls. /// </summary> private void SetupControl() { if (Parameters == null) { return; } if (Parameters["ObjectType"] != null) { // Get current object currentObject = ModuleManager.GetObject(ValidationHelper.GetString(Parameters["ObjectType"], String.Empty)); // Check if object is not null and has parent object if ((currentObject != null) && !String.IsNullOrEmpty(currentObject.ParentObjectType)) { lblParent.ResourceString = "objecttype." + currentObject.ParentObjectType.Replace(".", "_"); // Set parent object selector properties parentSelector.ObjectType = currentObject.ParentObjectType; parentSelector.DropDownSingleSelect.AutoPostBack = true; parentSelector.OnSelectionChanged += parentSelector_OnSelectionChanged; } else { plcParentObject.Visible = false; } } if (Parameters["CurrentSiteOnly"] != null) { siteSelector.Value = SiteContext.CurrentSiteID; plcSite.Visible = !ValidationHelper.GetBoolean(Parameters["CurrentSiteOnly"], false); } }
public override bool LoadData(ActivityInfo ai) { if ((ai == null) || !ModuleEntry.IsModuleLoaded(ModuleEntry.NEWSLETTER) || (ai.ActivityType != PredefinedActivityType.NEWSLETTER_OPEN)) { return(false); } // Get newsletter name int nesletterId = ai.ActivityItemID; GeneralizedInfo iinfo = ModuleCommands.NewsletterGetNewsletterInfo(nesletterId); if (iinfo != null) { string subject = ValidationHelper.GetString(iinfo.GetValue("NewsletterDisplayName"), null); ucDetails.AddRow("om.activitydetails.newsletter", subject); } // Get issue subject int issueId = ai.ActivityItemDetailID; iinfo = ModuleCommands.NewsletterGetNewsletterIssueInfo(issueId); if (iinfo != null) { string subject = ValidationHelper.GetString(iinfo.GetValue("IssueSubject"), null); ucDetails.AddRow("om.activitydetails.newsletterissue", subject); } return(ucDetails.IsDataLoaded); }
public override bool LoadData(ActivityInfo ai) { if ((ai == null) || !ModuleEntry.IsModuleLoaded(ModuleEntry.ECOMMERCE)) { return(false); ; } switch (ai.ActivityType) { case PredefinedActivityType.PRODUCT_ADDED_TO_WISHLIST: case PredefinedActivityType.PRODUCT_ADDED_TO_SHOPPINGCART: case PredefinedActivityType.PRODUCT_REMOVED_FROM_SHOPPINGCART: break; default: return(false); } GeneralizedInfo iinfo = ModuleCommands.ECommerceGetSKUInfo(ai.ActivityItemID); if (iinfo != null) { string productName = ValidationHelper.GetString(iinfo.GetValue("SKUName"), null); ucDetails.AddRow("om.activitydetails.product", productName); if (ai.ActivityType != PredefinedActivityType.PRODUCT_ADDED_TO_WISHLIST) { ucDetails.AddRow("om.activitydetails.productunits", ai.ActivityValue); } } return(ucDetails.IsDataLoaded); }
/// <summary> /// Gets score for specified contacts. /// </summary> private DataSet GetScore(DataSet ds) { ds.Tables[0].Columns.Add("Score"); StringBuilder contacts = new StringBuilder(); foreach (DataRow dr in ds.Tables[0].Rows) { int contactID = ValidationHelper.GetInteger(dr["SessionContactID"], 0); if (contactID > 0) { contacts.Append(contactID + ","); } } string contactList = contacts.ToString(); if (!String.IsNullOrEmpty(contactList)) { contactList = contactList.Substring(0, contactList.Length - 1); GeneralizedInfo contactScore = CMSObjectHelper.GetReadOnlyObject("om.contactscorelist"); DataSet result = contactScore.GetData(null, String.Format("ContactID IN ({0}) AND ScoreID = {1}", contactList, filter.SelectedScore), null, -1, "ContactID,ScoreValue", false); if (!DataHelper.DataSourceIsEmpty(result)) { foreach (DataRow dr in result.Tables[0].Rows) { DataRow[] row = ds.Tables[0].Select("SessionContactID =" + dr["ContactID"]); row[0]["Score"] = dr["ScoreValue"]; } } } return(ds); }
public override bool LoadData(ActivityInfo ai) { if ((ai == null) || !ModuleManager.IsModuleLoaded(ModuleName.POLLS) || (ai.ActivityType != PredefinedActivityType.POLL_VOTING)) { return(false); } GeneralizedInfo ipollinfo = ModuleCommands.PollsGetPollInfo(ai.ActivityItemID); if (ipollinfo != null) { string pollQuestion = ValidationHelper.GetString(ipollinfo.GetValue("PollQuestion"), null); ucDetails.AddRow("om.activitydetails.pollquestion", pollQuestion); } if (ai.ActivityValue != null) { string[] answerIDs = ai.ActivityValue.Split(new char[] { ActivityLogProvider.POLL_ANSWER_SEPARATOR }, StringSplitOptions.RemoveEmptyEntries); StringBuilder answers = new StringBuilder(); foreach (string id in answerIDs) { GeneralizedInfo iansinfo = ModuleCommands.PollsGetPollAnswerInfo(ValidationHelper.GetInteger(id, 0)); if (iansinfo != null) { answers.Append(HTMLHelper.HTMLEncode(ValidationHelper.GetString(iansinfo.GetValue("AnswerText"), null))); answers.Append("<br />"); } } ucDetails.AddRow("om.activitydetails.pollanswer", answers.ToString(), false); } return(ucDetails.IsDataLoaded); }
public override bool LoadData(ActivityInfo ai) { if ((ai == null) || !ModuleEntry.IsModuleLoaded(ModuleEntry.FORUMS)) { return(false); } switch (ai.ActivityType) { case PredefinedActivityType.FORUM_POST: case PredefinedActivityType.SUBSCRIPTION_FORUM_POST: break; default: return(false); } int nodeId = ai.ActivityNodeID; lblDocIDVal.Text = GetLinkForDocument(nodeId, ai.ActivityCulture); if (ai.ActivityType == PredefinedActivityType.FORUM_POST) { GeneralizedInfo iinfo = ModuleCommands.ForumsGetForumPostInfo(ai.ActivityItemDetailID); if (iinfo != null) { plcComment.Visible = true; lblPostSubjectVal.Text = HTMLHelper.HTMLEncode(ValidationHelper.GetString(iinfo.GetValue("PostSubject"), null)); txtPost.Text = ValidationHelper.GetString(iinfo.GetValue("PostText"), null); } } return(true); }
public override bool LoadData(ActivityInfo ai) { if ((ai == null) || !ModuleManager.IsModuleLoaded(ModuleName.ECOMMERCE)) { return(false); } switch (ai.ActivityType) { case PredefinedActivityType.PRODUCT_ADDED_TO_WISHLIST: case PredefinedActivityType.PRODUCT_ADDED_TO_SHOPPINGCART: case PredefinedActivityType.PRODUCT_REMOVED_FROM_SHOPPINGCART: break; default: return(false); } GeneralizedInfo sku = BaseAbstractInfoProvider.GetInfoById(PredefinedObjectType.SKU, ai.ActivityItemID); if (sku != null) { string productName = ValidationHelper.GetString(sku.GetValue("SKUName"), null); ucDetails.AddRow("om.activitydetails.product", productName); if (ai.ActivityType != PredefinedActivityType.PRODUCT_ADDED_TO_WISHLIST) { ucDetails.AddRow("om.activitydetails.productunits", ai.ActivityValue); } } return(ucDetails.IsDataLoaded); }
/// <summary> /// Updates contact's address. /// </summary> /// <param name="addressInfo">Billing address</param> private void MapContactAddress(IAddress addressInfo) { try { if ((addressInfo == null) || !SettingsKeyInfoProvider.GetBoolValue(SiteContext.CurrentSiteName + ".CMSEnableOnlineMarketing")) { return; } GeneralizedInfo contactInfo = BaseAbstractInfoProvider.GetInfoById(PredefinedObjectType.CONTACT, ContactID); // Check that current contact has not yet filled in address if ((contactInfo != null) && String.IsNullOrEmpty(ValidationHelper.GetString(contactInfo.GetValue("ContactAddress1"), ""))) { Func <int, int?> getIntIfValid = i => i > 0 ? i : (int?)null; contactInfo.SetValue("ContactAddress1", addressInfo.AddressLine1); contactInfo.SetValue("ContactAddress2", addressInfo.AddressLine2); contactInfo.SetValue("ContactCity", addressInfo.AddressCity); contactInfo.SetValue("ContactZIP", addressInfo.AddressZip); contactInfo.SetValue("ContactMobilePhone", addressInfo.AddressPhone); contactInfo.SetValue("ContactCountryID", getIntIfValid(addressInfo.AddressCountryID)); contactInfo.SetValue("ContactStateID", getIntIfValid(addressInfo.AddressStateID)); contactInfo.SetObject(); } } catch (Exception ex) { // Exception could happen when max length of contact parameters is exceeded EventLogProvider.LogException("ShoppingCartOrderAddresses.MapContactAddress", "UPDATECONTACT", ex); } }
/// <summary> /// Ensure user friendly file name /// </summary> /// <param name="infoObj">Object to be exported</param> /// <param name="backup">Indicates if export is treated as backup</param> private static string GetExportFileName(GeneralizedInfo infoObj, bool backup) { string prefix; // Get file name according to accessible object properties var ti = infoObj.TypeInfo; if (ti.CodeNameColumn != ObjectTypeInfo.COLUMN_NAME_UNKNOWN) { prefix = infoObj.ObjectCodeName; } else { string identifier = (ti.DisplayNameColumn != ObjectTypeInfo.COLUMN_NAME_UNKNOWN) ? infoObj.ObjectDisplayName : infoObj.ObjectGUID.ToString(); prefix = ValidationHelper.GetCodeName(identifier); } // Backup use short file name, in other cases use long file name with object type if (!backup) { string objectType = ti.IsListingObjectTypeInfo ? ti.OriginalObjectType : ti.ObjectType; prefix = objectType + "_" + prefix; } return(ImportExportHelper.GenerateExportFileName(prefix.Replace(".", "_"))); }
private static GeneralizedInfo SingleObjectSelection(int objectID, BaseInfo infoObj) { //object level filtering to lower levels GeneralizedInfo exportObj = infoObj.GetObject(objectID); return(exportObj); }
/// <summary> /// Returns binding column names for binding object type. /// 1. Try to search ParentObjectType (there should be first binding column name). /// 2. Search for site ID column. In site bindings you will find column name for site. /// 3. If one of the columns is still not found, search all object's dependencies. /// </summary> public Tuple <String, String> GetBindingColumnNames() { String objCol = String.Empty, targetCol = String.Empty; GeneralizedInfo providerInfo = objProvider.Generalized; var providerTypeInfo = providerInfo.TypeInfo; var objTypeInfo = obj.TypeInfo; var targetTypeInfo = objTarget.TypeInfo; // 1. ParentObjectType if (providerInfo.ParentObjectType.EqualsCSafe(objTypeInfo.ObjectType, true)) { objCol = providerTypeInfo.ParentIDColumn; } else if (providerInfo.ParentObjectType.EqualsCSafe(targetTypeInfo.ObjectType, true)) { targetCol = providerTypeInfo.ParentIDColumn; } // 2. Site bindings if (providerTypeInfo.SiteIDColumn != ObjectTypeInfo.COLUMN_NAME_UNKNOWN) { if (String.IsNullOrEmpty(objCol) && objTypeInfo.ObjectType.EqualsCSafe(ModuleName.SITE, true)) { objCol = providerTypeInfo.SiteIDColumn; } if (String.IsNullOrEmpty(targetCol) && targetTypeInfo.ObjectType.EqualsCSafe(ModuleName.SITE, true)) { targetCol = providerTypeInfo.SiteIDColumn; } } // 3. Object's dependencies if (!String.IsNullOrEmpty(targetCol) || !String.IsNullOrEmpty(objCol)) { // Check all object's dependencies if (providerTypeInfo.DependsOn != null) { foreach (ObjectDependency od in providerTypeInfo.DependsOn) { if (od.DependencyObjectType.EqualsCSafe(objTypeInfo.ObjectType, true)) { objCol = od.DependencyColumn; } if (od.DependencyObjectType.EqualsCSafe(targetTypeInfo.ObjectType, true)) { targetCol = od.DependencyColumn; } } } } return(new Tuple <String, String>(objCol, targetCol)); }
/// <summary> /// Reload data. /// </summary> public override void ReloadData() { requestedGroupId = ValidationHelper.GetInteger(ContextMenu.Parameter, 0); DataTable table = new DataTable(); table.Columns.Add("ActionIcon"); table.Columns.Add("ActionDisplayName"); table.Columns.Add("ActionScript"); // Add only if community is present if (CommunityPresent) { // Get resource strings prefix string resourcePrefix = ContextMenu.ResourcePrefix; // View group profile string profileUrl = ""; // Get group profile URL GeneralizedInfo infoObj = ModuleCommands.CommunityGetGroupInfo(requestedGroupId); if (infoObj != null) { profileUrl = ResolveUrl(CMSContext.GetUrl(ModuleCommands.CommunityGetGroupProfilePath(infoObj.ObjectCodeName, CMSContext.CurrentSiteName))); } table.Rows.Add(new object[] { "groupprofile.png", ResHelper.GetString(resourcePrefix + ".viewgroup|group.viewgroup"), "window.location.replace('" + profileUrl + "');" }); if (!currentUser.IsGroupMember(requestedGroupId)) { table.Rows.Add(new object[] { "jointhegroup.png", ResHelper.GetString(resourcePrefix + ".joingroup|group.joingroup"), !currentUser.IsPublic() ? "ContextJoinTheGroup(GetContextMenuParameter('" + ContextMenu.MenuID + "'))" : "ContextRedirectToSignInUrl()" }); } else { table.Rows.Add(new object[] { "leavethegroup.png", ResHelper.GetString(resourcePrefix + ".leavegroup|group.leavegroup"), !currentUser.IsPublic() ? "ContextLeaveTheGroup(GetContextMenuParameter('" + ContextMenu.MenuID + "'))" : "ContextRedirectToSignInUrl()" }); } if (infoObj != null) { // Display Manage the group link if user is logged as group administrator and user is visiting a group page if (currentUser.IsGroupAdministrator(requestedGroupId) || currentUser.IsGlobalAdministrator) { string managementUrl = ResolveUrl(TreePathUtils.GetUrl(ModuleCommands.CommunityGetGroupManagementPath(infoObj.ObjectCodeName, CMSContext.CurrentSiteName))); table.Rows.Add(new object[] { "managegroup.png", ResHelper.GetString(resourcePrefix + ".managegroup|group.managegroup"), !currentUser.IsPublic() ? " window.location.replace('" + managementUrl + "');" : "ContextRedirectToSignInUrl()" }); } } } // Add count column DataColumn countColumn = new DataColumn(); countColumn.ColumnName = "Count"; countColumn.DefaultValue = table.Rows.Count; table.Columns.Add(countColumn); repItem.DataSource = table; repItem.DataBind(); }
// Get orderby expression private static string GetOrderByExpression(GeneralizedInfo info) { if (info.DisplayNameColumn != ObjectTypeInfo.COLUMN_NAME_UNKNOWN) { return(info.DisplayNameColumn); } return(info.CodeNameColumn); }
/// <summary> /// Loads variables and objects. /// </summary> private void LoadControls() { // Load objects if (!String.IsNullOrEmpty(objectType)) { iObjectType = ModuleManager.GetReadOnlyObject(objectType); if (iObjectType == null) { throw new Exception("[UniSelector.SelectionDialog]: Object type '" + objectType + "' not found."); } if (returnColumnName == null) { returnColumnName = iObjectType.IDColumn; } } mSearchColumns = GetSearchColumns(); // Display default name filter only if search columns are specified if (useDefaultNameFilter && (!String.IsNullOrEmpty(mSearchColumns) || !String.IsNullOrEmpty(additionalSearchColumns) || (displayNameFormat == UniSelector.USER_DISPLAY_FORMAT))) { lblSearch.ResourceString = resourcePrefix + ".entersearch|general.entersearch"; btnSearch.ResourceString = "general.search"; pnlSearch.Visible = true; if (!URLHelper.IsPostback()) { ScriptHelper.RegisterStartupScript(this, typeof(string), "Focus", ScriptHelper.GetScript("try{document.getElementById('" + txtSearch.ClientID + "').focus();}catch(err){}")); } } if (!URLHelper.IsPostback()) { uniGrid.Pager.DefaultPageSize = itemsPerPage; } uniGrid.GridName = dialogGridName; uniGrid.GridView.EnableViewState = false; // Show the OK button if needed switch (selectionMode) { case SelectionModeEnum.Multiple: case SelectionModeEnum.MultipleTextBox: case SelectionModeEnum.MultipleButton: { pnlAll.Visible = true; lnkSelectAll.Text = GetString("UniSelector.SelectAll"); lnkDeselectAll.Text = GetString("UniSelector.DeselectAll"); } break; } }
/// <summary> /// Get info from PersistentEditedObject and reload data /// </summary> private void ReloadDataAfrterRollback() { // Load rollbacked info GeneralizedInfo gi = PersistentEditedObject as GeneralizedInfo; if (gi != null) { tableInfo = gi.MainObject as ReportTableInfo; } LoadData(); }
/// <summary> /// Setup controls /// </summary> private void SetupControls() { if (!RequestHelper.IsPostBack()) { LoadDropDown(); chkDisplayAllData.Checked = !ObjectDataOnly; } drpCompareTo.SelectedIndexChanged += drpCompareTo_SelectedIndexChanged; if (!NoComparison) { ObjectDataOnly = !chkDisplayAllData.Checked; } SyncHelper sh = SyncHelper.GetInstance(); sh.OperationType = OperationTypeEnum.Versioning; // Get object version DataSet DataSet dsObject = sh.GetDataSet(Version.VersionXML, TaskTypeEnum.UpdateObject, Version.VersionObjectType); DataSet dsCompare = null; // Get object compare version DataSet if (VersionCompare != null) { dsCompare = sh.GetDataSet(VersionCompare.VersionXML, TaskTypeEnum.UpdateObject, VersionCompare.VersionObjectType); } // Filter out data if necessary if (ObjectDataOnly) { // Get object data table name GeneralizedInfo obj = CMSObjectHelper.GetReadOnlyObject(Version.VersionObjectType); string objectTable = CMSObjectHelper.GetTableName(obj); dsObject = CreateTableDataSet(dsObject, objectTable, obj); dsCompare = CreateTableDataSet(dsCompare, objectTable, obj); } // Switch version data to ensure lower version is on the left side if ((Version != null) && (VersionCompare != null) && (VersionCompare.VersionID < Version.VersionID)) { viewDataSet.DataSet = dsCompare; viewDataSet.CompareDataSet = dsObject; } else { viewDataSet.DataSet = dsObject; viewDataSet.CompareDataSet = dsCompare; } }
/// <summary> /// Processes given object according to task type. /// It is expected that you use TranslateColumnsToExternal method before you process the task. /// The TranslateColumnsToExternal needs GetExternalObjectID and GetExternalDocumentID to be implemented. /// It traverses the given object and tries to translate foreign keys to match external (your) application. /// </summary> /// <param name="infoObj">Info object to process</param> /// <param name="translations">Translation helper object containing translations for given object</param> /// <param name="taskType">Type of task</param> /// <param name="dataType">Type of data</param> /// <param name="siteName">Name of site</param> /// <param name="errorMessage">Possible error message</param> /// <returns>Result of processing</returns> public override IntegrationProcessResultEnum ProcessInternalTaskAsync(GeneralizedInfo infoObj, TranslationHelper translations, TaskTypeEnum taskType, TaskDataTypeEnum dataType, string siteName, out string errorMessage) { try { // If object is of 'user' type // You can also use following condition: (((BaseInfo)infoObj) is CMS.SiteProvider.UserInfo) if (infoObj.ObjectType == PredefinedObjectType.USER) { bool log = false; // Create simple message string message = "User with username '" + infoObj.ObjectCodeName + "' has been"; switch (taskType) { case TaskTypeEnum.CreateObject: log = true; message += " created."; break; case TaskTypeEnum.UpdateObject: log = true; message += " updated."; break; case TaskTypeEnum.DeleteObject: log = true; message += " deleted."; break; } if (log) { EventLogProvider eventLog = new EventLogProvider(); // Log the message eventLog.LogEvent(EventLogProvider.EVENT_TYPE_INFORMATION, DateTime.Now, ConnectorName, taskType.ToString(), 0, null, 0, null, null, message, 0, null); } } errorMessage = null; return(IntegrationProcessResultEnum.OK); } catch (Exception ex) { errorMessage = ex.Message; return(IntegrationProcessResultEnum.Error); } finally { // Clear translations cached during TranslateColumnsToExternal which internally calls GetExternalObjectID, GetExternalDocumentID // This call is optional but recommended in the case where eg. collision of code names can occur ClearInternalTranslations(); } }
/// <summary> /// Returns group ID according to group name. /// </summary> protected int GetGroupID() { if (!string.IsNullOrEmpty(this.GroupName)) { // Get group object GeneralizedInfo group = ModuleCommands.CommunityGetGroupInfoByName(this.GroupName, this.SiteName); if (group != null) { // Get ID column value return(ValidationHelper.GetInteger(group.GetValue(group.IDColumn), 0)); } } return(0); }
/// <summary> /// Overridden SetValue - because of MyAccount webpart. /// </summary> /// <param name="propertyName">Name of the property to set</param> /// <param name="value">Value to set</param> public override void SetValue(string propertyName, object value) { base.SetValue(propertyName, value); switch (propertyName.ToLowerCSafe()) { case "customer": GeneralizedInfo gi = value as GeneralizedInfo; if (gi != null) { Customer = gi.MainObject as CustomerInfo; } break; } }
/// <summary> /// Checks whether the user is authorized to delete SKU bound to given node. /// </summary> /// <param name="node">Node to be checked</param> protected bool IsUserAuthorizedToModifySKU(TreeNode node) { bool authorized = false; if ((node != null) && (node.HasSKU)) { GeneralizedInfo product = ModuleCommands.ECommerceGetSKUInfo(node.NodeSKUID); if (product != null) { authorized = product.MainObject.CheckPermissions(PermissionsEnum.Delete, node.NodeSiteName, currentUser); } } return(authorized); }
private void Form_OnAfterSave(object sender, EventArgs e) { bool bindObjects = ValidationHelper.GetBoolean(Value, false); if ((bindObjects || !Form.IsInsertMode) && Visible) { GeneralizedInfo obj = (BaseInfo)Form.Data; if (obj != null) { try { BaseInfo bindingObj = ModuleManager.GetObject(Form.ResolveMacros(ObjectType)); int targetObjectID = ValidationHelper.GetInteger(Form.ResolveMacros(TargetObjectID), 0); var idColumn = obj.TypeInfo.IDColumn; if ((bindingObj != null) && (bindingObj.ColumnNames.Count >= 2) && (bindingObj.ContainsColumn(idColumn)) && (targetObjectID > 0)) { // Select proper column for target object string targetObjectColumn = (bindingObj.ColumnNames.IndexOf(idColumn) == 0) ? bindingObj.ColumnNames[1] : bindingObj.ColumnNames[0]; bindingObj.SetValue(idColumn, obj.ObjectID); bindingObj.SetValue(targetObjectColumn, targetObjectID); if (bindObjects) { // Bind objects bindingObj.Insert(); } else { // Remove binding bindingObj.Delete(); } } else { EventLogProvider.LogEvent(EventType.ERROR, "ObjectBinding", "BindObject", "Object " + obj.ObjectDisplayName + " cannot be bound."); } } catch (Exception ex) { EventLogProvider.LogException("ObjectBinding", "BindObject", ex); } } } }
/// <summary> /// Create new DataSet from table with specified table name /// </summary> /// <param name="sourceDs">Source DataSet</param> /// <param name="tableName">Main table name</param> /// <param name="obj">Object which data contains DataSet</param> /// <returns>Result DataSet</returns> private DataSet CreateTableDataSet(DataSet sourceDs, string tableName, GeneralizedInfo obj) { if (!DataHelper.DataSourceIsEmpty(sourceDs)) { DataTable dt = sourceDs.Tables[tableName]; DataSet dsResult = new DataSet(); if (!DataHelper.DataSourceIsEmpty(dt)) { dsResult.Tables.Add(dt.Copy()); return(dsResult); } } return(null); }
/// <summary> /// Initializes control properties. /// </summary> protected void SetupControl() { if (StopProcessing) { // Do nothing } else { srcPosts.SiteName = SiteName; srcPosts.ForumName = ForumName; srcPosts.WhereCondition = WhereCondition; srcPosts.OrderBy = OrderBy; srcPosts.TopN = SelectTopN; srcPosts.FilterName = ValidationHelper.GetString(GetValue("WebPartControlID"), ID); srcPosts.SourceFilterName = FilterName; srcPosts.CacheItemName = CacheItemName; srcPosts.CacheDependencies = CacheDependencies; srcPosts.CacheMinutes = CacheMinutes; srcPosts.SelectOnlyApproved = SelectOnlyApproved; srcPosts.CheckPermissions = CheckPermissions; srcPosts.SelectedColumns = Columns; srcPosts.ShowGroupPosts = ShowGroupPosts && String.IsNullOrEmpty(ForumName); // Set data source groupid according to group name if (!String.IsNullOrEmpty(GroupName)) { if (GroupName == PredefinedObjectType.COMMUNITY_CURRENT_GROUP) { srcPosts.GroupID = ModuleCommands.CommunityGetCurrentGroupID(); } else { GeneralizedInfo gi = ModuleCommands.CommunityGetGroupInfoByName(GroupName, SiteName); if (gi != null) { srcPosts.GroupID = ValidationHelper.GetInteger(gi.GetValue("GroupID"), 0); } else { srcPosts.StopProcessing = true; } } } } }
// Get orderby expression private string GetOrderByExpression(GeneralizedInfo info) { switch (info.TypeInfo.ObjectType) { case PageTemplateInfo.OBJECT_TYPE: return("PageTemplateIsReusable DESC," + info.DisplayNameColumn); default: { if (info.DisplayNameColumn != ObjectTypeInfo.COLUMN_NAME_UNKNOWN) { return(info.DisplayNameColumn); } return(codeNameColumnName); } } }
protected void Page_Load(object sender, EventArgs e) { backup = QueryHelper.GetBoolean("backup", false); // Check permissions if (backup) { if (!CMSContext.CurrentUser.IsAuthorizedPerResource("cms.globalpermissions", "BackupObjects", CMSContext.CurrentSiteName)) { RedirectToCMSDeskAccessDenied("cms.globalpermissions", "BackupObjects"); } } else if (!CMSContext.CurrentUser.IsAuthorizedPerResource("cms.globalpermissions", "ExportObjects", CMSContext.CurrentSiteName)) { RedirectToCMSDeskAccessDenied("cms.globalpermissions", "ExportObjects"); } // Register script for pendingCallbacks repair ScriptHelper.FixPendingCallbacks(Page); // Async control events binding ucAsyncControl.OnFinished += ucAsyncControl_OnFinished; ucAsyncControl.OnError += ucAsyncControl_OnError; if (!IsCallback) { try { // Delete temporary files ExportProvider.DeleteTemporaryFiles(); } catch (Exception ex) { DisplayError(ex); } if (backup) { SetTitle("CMSModules/CMS_ImportExport/backupobject.png", GetString("BackupObject.Title"), null, null); } else { SetTitle("CMSModules/CMS_ImportExport/exportobject.png", GetString("ExportObject.Title"), null, null); } // Display BETA warning lblBeta.Visible = CMSContext.IsBetaVersion(); lblBeta.Text = string.Format(GetString("export.BETAwarning"), CMSContext.GetFriendlySystemVersion(false)); // Get data from parameters objectId = ValidationHelper.GetInteger(Request.QueryString["objectId"], 0); objectType = ValidationHelper.GetString(Request.QueryString["objectType"], ""); // Get the object infoObj = CMSObjectHelper.GetReadOnlyObject(objectType); if (infoObj == null) { plcExportDetails.Visible = false; lblIntro.Text = GetString("ExportObject.ObjectTypeNotFound"); lblIntro.CssClass = "ErrorLabel"; return; } // Get exported object exportObj = infoObj.GetObject(objectId); if (exportObj == null) { plcExportDetails.Visible = false; lblIntro.Text = GetString("ExportObject.ObjectNotFound"); lblIntro.CssClass = "ErrorLabel"; btnOk.Visible = false; return; } // Store display name exportObjectDisplayName = HTMLHelper.HTMLEncode(exportObj.ObjectDisplayName); if (backup) { lblIntro.Text = string.Format(GetString("BackupObject.Intro"), ResHelper.LocalizeString(exportObjectDisplayName)); } else { lblIntro.Text = string.Format(GetString("ExportObject.Intro"), ResHelper.LocalizeString(exportObjectDisplayName)); } btnOk.Click += btnOk_Click; if (!RequestHelper.IsPostBack()) { lblIntro.Visible = true; lblFileName.Visible = true; txtFileName.Text = GetExportFileName(exportObj, backup); if (backup) { btnOk.Text = GetString("General.backup"); } else { btnOk.Text = GetString("General.export"); } btnCancel.Text = GetString("General.Close"); } string path = null; if (backup) { path = ImportExportHelper.GetObjectBackupFolder(exportObj); targetFolder = Server.MapPath(path); targetUrl = ResolveUrl(path) + "/" + txtFileName.Text; } else { targetFolder = ImportExportHelper.GetSiteUtilsFolder() + "Export"; path = ImportExportHelper.GetSiteUtilsFolderRelativePath(); if (path != null) { if (!AzureHelper.IsRunningOnAzure && !StorageHelper.IsAzureStorage) { targetUrl = ResolveUrl(path) + "Export/" + txtFileName.Text; } else { // Generate special link for Azure string url = AzureHelper.GetDownloadPath(path) + "Export/" + txtFileName.Text; string hash = ValidationHelper.GetHashString(URLHelper.GetQuery(url)); targetUrl = URLHelper.ResolveUrl(URLHelper.AppendQuery(url, "hash=" + hash)); } } else { targetUrl = null; } } } }
protected void Page_Load(object sender, EventArgs e) { backup = QueryHelper.GetBoolean("backup", false); // Check permissions if (backup) { if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("cms.globalpermissions", "BackupObjects", SiteContext.CurrentSiteName)) { RedirectToAccessDenied("cms.globalpermissions", "BackupObjects"); } } else if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("cms.globalpermissions", "ExportObjects", SiteContext.CurrentSiteName)) { RedirectToAccessDenied("cms.globalpermissions", "ExportObjects"); } // Register script for pendingCallbacks repair ScriptHelper.FixPendingCallbacks(Page); // Async control events binding ucAsyncControl.OnFinished += ucAsyncControl_OnFinished; ucAsyncControl.OnError += ucAsyncControl_OnError; if (!RequestHelper.IsCallback()) { try { // Delete temporary files ExportProvider.DeleteTemporaryFiles(); } catch (Exception ex) { DisplayError(ex); } if (backup) { SetTitle(GetString("BackupObject.Title")); } else { SetTitle(GetString("ExportObject.Title")); } // Display BETA warning lblBeta.Visible = CMSVersion.IsBetaVersion(); lblBeta.Text = string.Format(GetString("export.BETAwarning"), CMSVersion.GetFriendlySystemVersion(false)); // Get data from parameters objectId = QueryHelper.GetInteger("objectId", 0); objectType = QueryHelper.GetString("objectType", ""); // Get the object infoObj = ModuleManager.GetReadOnlyObject(objectType); if (infoObj == null) { plcExportDetails.Visible = false; lblIntro.Text = GetString("ExportObject.ObjectTypeNotFound"); lblIntro.CssClass = "ErrorLabel"; return; } // Get exported object exportObj = infoObj.GetObject(objectId); if (exportObj == null) { plcExportDetails.Visible = false; lblIntro.Text = GetString("ExportObject.ObjectNotFound"); lblIntro.CssClass = "ErrorLabel"; btnOk.Visible = false; return; } // Check permissions var info = (BaseInfo)exportObj; if (!CurrentUser.IsGlobalAdministrator) { try { if (info.Generalized.ObjectSiteID > 0) { CurrentUser.IsAuthorizedPerObject(PermissionsEnum.Read, info, SiteInfoProvider.GetSiteName(info.Generalized.ObjectSiteID), true); } else if ((info.TypeInfo.SiteBindingObject != null) && (info.AssignedSites[CurrentSiteName] == null)) { // Do not allow to clone objects with site binding which are not assigned to current site RedirectToAccessDenied(info.TypeInfo.ModuleName, PermissionsEnum.Read.ToString()); } else { CurrentUser.IsAuthorizedPerObject(PermissionsEnum.Read, info, CurrentSiteName, true); } } catch (PermissionCheckException ex) { RedirectToAccessDenied(ex.ModuleName, ex.PermissionFailed); } } // Store display name exportObjectDisplayName = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(exportObj.ObjectDisplayName)); lblIntro.Text = string.Format(GetString(backup ? "BackupObject.Intro" : "ExportObject.Intro"), exportObjectDisplayName); btnOk.Click += btnOk_Click; if (!RequestHelper.IsPostBack()) { lblIntro.Visible = true; lblFileName.Visible = true; txtFileName.Text = GetExportFileName(exportObj, backup); } btnOk.Text = GetString(backup ? "General.backup" : "General.export"); string path; if (backup) { path = ImportExportHelper.GetObjectBackupFolder(exportObj); targetFolder = Server.MapPath(path); targetUrl = ResolveUrl(path) + "/" + txtFileName.Text; } else { targetFolder = ImportExportHelper.GetSiteUtilsFolder() + "Export"; path = ImportExportHelper.GetSiteUtilsFolderRelativePath(); if (path != null) { string externalUrl = null; string fullPath = path + "Export/" + txtFileName.Text; // Handle external storage URL if (StorageHelper.IsExternalStorage(fullPath)) { externalUrl = File.GetFileUrl(fullPath, SiteContext.CurrentSiteName); } // Ensure default target URL if not set if (string.IsNullOrEmpty(externalUrl)) { targetUrl = ResolveUrl(path) + "Export/" + txtFileName.Text; } else { targetUrl = externalUrl; } } else { targetUrl = null; } } } }
/// <summary> /// Ensure user friendly file name /// </summary> /// <param name="infoObj">Object to be exported</param> /// <param name="backup">Indicates if export is treated as backup</param> private static string GetExportFileName(GeneralizedInfo infoObj, bool backup) { string prefix; // Get file name according to accessible object properties var ti = infoObj.TypeInfo; if (ti.CodeNameColumn != ObjectTypeInfo.COLUMN_NAME_UNKNOWN) { prefix = infoObj.ObjectCodeName; } else { string identifier = (ti.DisplayNameColumn != ObjectTypeInfo.COLUMN_NAME_UNKNOWN) ? infoObj.ObjectDisplayName : infoObj.ObjectGUID.ToString(); prefix = ValidationHelper.GetCodeName(identifier); } // Backup use short file name, in other cases use long file name with object type if (!backup) { string objectType = ti.Inherited ? ti.OriginalObjectType : ti.ObjectType; prefix = objectType + "_" + prefix; } return ImportExportHelper.GenerateExportFileName(prefix.Replace(".", "_")); }
/// <summary> /// Ensure user friendly file name /// </summary> /// <param name="infoObj">Object to be exported</param> /// <param name="backup">Indicates if export is treated as backup</param> private string GetExportFileName(GeneralizedInfo infoObj, bool backup) { string fileName = null; // Get file name accrding to accesible object properties if (infoObj.TypeInfo.CodeNameColumn != TypeInfo.COLUMN_NAME_UNKNOWN) { fileName = infoObj.ObjectCodeName; } else if (infoObj.TypeInfo.DisplayNameColumn != TypeInfo.COLUMN_NAME_UNKNOWN) { fileName = ValidationHelper.GetCodeName(infoObj.ObjectDisplayName); } else { fileName = ValidationHelper.GetCodeName(infoObj.ObjectGUID.ToString()); } fileName = fileName.Replace(".", "_") + "_" + DateTime.Now.ToString("yyyyMMdd") + "_" + DateTime.Now.ToString("HHmm") + ".zip"; fileName = ValidationHelper.GetSafeFileName(fileName); // Backup use short file name, in other cases use long file name with object type if (!backup) { fileName = infoObj.TypeInfo.OriginalObjectType.Replace(".", "_") + "_" + fileName; } return fileName; }
protected void Page_Load(object sender, EventArgs e) { if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("cms.globalpermissions", "RestoreObjects", SiteContext.CurrentSiteName)) { RedirectToAccessDenied("cms.globalpermissions", "RestoreObjects"); } // Register script for pendingCallbacks repair ScriptHelper.FixPendingCallbacks(Page); // Async control events binding ucAsyncControl.OnFinished += ucAsyncControl_OnFinished; ucAsyncControl.OnError += ucAsyncControl_OnError; if (!RequestHelper.IsCallback()) { try { // Delete temporary files ExportProvider.DeleteTemporaryFiles(); } catch (Exception ex) { DisplayError(ex); } SetTitle(GetString("RestoreObject.Title")); // Get data from parameters siteId = QueryHelper.GetInteger("siteId", 0); objectId = QueryHelper.GetInteger("objectId", 0); objectType = QueryHelper.GetString("objectType", ""); // Get the object infoObj = ModuleManager.GetReadOnlyObject(objectType); if (infoObj == null) { lblIntro.Text = GetString("ExportObject.ObjectTypeNotFound"); lblIntro.CssClass = "ErrorLabel"; return; } // Get exported object exportObj = infoObj.GetObject(objectId); if (exportObj == null) { lblIntro.Text = GetString("ExportObject.ObjectNotFound"); lblIntro.CssClass = "ErrorLabel"; btnRestore.Visible = false; return; } // Store display name exportObjectDisplayName = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(exportObj.ObjectDisplayName)); codeName = exportObj.ObjectCodeName; lblIntro.Text = string.Format(GetString("RestoreObject.Intro"), exportObjectDisplayName); targetFolder = ImportExportHelper.GetObjectBackupFolder(exportObj); btnRestore.Click += btnRestore_Click; if (!RequestHelper.IsPostBack()) { lblIntro.Visible = true; // Load the available backups if (lstImports.Items.Count == 0) { RefreshPackageList(); } } } }
/// <summary> /// Create new DataSet from table with specified table name /// </summary> /// <param name="sourceDs">Source DataSet</param> /// <param name="tableName">Main table name</param> /// <param name="obj">Object which data contains DataSet</param> /// <returns>Result DataSet</returns> private DataSet CreateTableDataSet(DataSet sourceDs, string tableName, GeneralizedInfo obj) { if (!DataHelper.DataSourceIsEmpty(sourceDs)) { DataTable dt = sourceDs.Tables[tableName]; DataSet dsResult = new DataSet(); if (!DataHelper.DataSourceIsEmpty(dt)) { dsResult.Tables.Add(dt.Copy()); return dsResult; } } return null; }
protected void Page_Load(object sender, EventArgs e) { if (!CMSContext.CurrentUser.IsAuthorizedPerResource("cms.globalpermissions", "RestoreObjects", CMSContext.CurrentSiteName)) { RedirectToCMSDeskAccessDenied("cms.globalpermissions", "RestoreObjects"); } // Register script for pendingCallbacks repair ScriptHelper.FixPendingCallbacks(Page); imgDelete.ImageUrl = GetImageUrl("Design/Controls/EditModeButtons/delete.png"); // Async control events binding ucAsyncControl.OnFinished += ucAsyncControl_OnFinished; ucAsyncControl.OnError += ucAsyncControl_OnError; if (!IsCallback) { try { // Delete temporary files ExportProvider.DeleteTemporaryFiles(); } catch (Exception ex) { DisplayError(ex); } SetTitle("CMSModules/CMS_ImportExport/restoreobject.png", GetString("RestoreObject.Title"), null, null); // Get data from parameters siteId = ValidationHelper.GetInteger(Request.QueryString["siteId"], 0); objectId = ValidationHelper.GetInteger(Request.QueryString["objectId"], 0); objectType = ValidationHelper.GetString(Request.QueryString["objectType"], ""); // Get the object infoObj = CMSObjectHelper.GetReadOnlyObject(objectType); if (infoObj == null) { lblIntro.Text = GetString("ExportObject.ObjectTypeNotFound"); lblIntro.CssClass = "ErrorLabel"; return; } // Get exported object exportObj = infoObj.GetObject(objectId); if (exportObj == null) { lblIntro.Text = GetString("ExportObject.ObjectNotFound"); lblIntro.CssClass = "ErrorLabel"; btnOk.Visible = false; return; } // Store display name exportObjectDisplayName = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(exportObj.ObjectDisplayName)); codeName = exportObj.ObjectCodeName; lblIntro.Text = string.Format(GetString("RestoreObject.Intro"), exportObjectDisplayName); targetFolder = ImportExportHelper.GetObjectBackupFolder(exportObj); btnOk.Click += btnOk_Click; if (!RequestHelper.IsPostBack()) { lblIntro.Visible = true; btnOk.Text = GetString("General.Restore"); btnCancel.Text = GetString("General.Close"); // Load the available backups if (lstImports.Items.Count == 0) { RefreshPackageList(); } } } }
/// <summary> /// Processes given object according to task type. /// It is expected that you use TranslateColumnsToExternal method before you process the task. /// The TranslateColumnsToExternal needs GetExternalObjectID and GetExternalDocumentID to be implemented. /// It traverses the given object and tries to translate foreign keys to match external (your) application. /// </summary> /// <param name="infoObj">Info object to process</param> /// <param name="translations">Translation helper object containing translations for given object</param> /// <param name="taskType">Type of task</param> /// <param name="dataType">Type of data</param> /// <param name="siteName">Name of site</param> /// <param name="errorMessage">Possible error message</param> /// <returns>Result of processing</returns> public override IntegrationProcessResultEnum ProcessInternalTaskAsync(GeneralizedInfo infoObj, TranslationHelper translations, TaskTypeEnum taskType, TaskDataTypeEnum dataType, string siteName, out string errorMessage) { try { // If object is of 'user' type // You can also use following condition: (((BaseInfo)infoObj) is CMS.SiteProvider.UserInfo) if (infoObj.ObjectType == PredefinedObjectType.USER) { bool log = false; // Create simple message string message = "User with username '" + infoObj.ObjectCodeName + "' has been"; switch (taskType) { case TaskTypeEnum.CreateObject: log = true; message += " created."; break; case TaskTypeEnum.UpdateObject: log = true; message += " updated."; break; case TaskTypeEnum.DeleteObject: log = true; message += " deleted."; break; } if (log) { EventLogProvider eventLog = new EventLogProvider(); // Log the message eventLog.LogEvent(EventLogProvider.EVENT_TYPE_INFORMATION, DateTime.Now, ConnectorName, taskType.ToString(), 0, null, 0, null, null, message, 0, null); } } errorMessage = null; return IntegrationProcessResultEnum.OK; } catch (Exception ex) { errorMessage = ex.Message; return IntegrationProcessResultEnum.Error; } finally { // Clear translations cached during TranslateColumnsToExternal which internally calls GetExternalObjectID, GetExternalDocumentID // This call is optional but recommended in the case where eg. collision of code names can occur ClearInternalTranslations(); } }
/// <summary> /// Initialize filter controls. /// </summary> private void SetupControl() { if ((Parameters != null) && (Parameters["ObjectType"] != null)) { // Get current object currentObject = CMSObjectHelper.GetObject(ValidationHelper.GetString(Parameters["ObjectType"], String.Empty)); // Check if object is not null and has parent object if ((currentObject != null) && !String.IsNullOrEmpty(currentObject.ParentObjectType)) { lblParent.ResourceString = "objecttype." + currentObject.ParentObjectType.Replace(".", "_"); // Set parent object selector properties parentSelector.ObjectType = currentObject.ParentObjectType; parentSelector.DropDownSingleSelect.AutoPostBack = true; parentSelector.OnSelectionChanged += new EventHandler(parentSelector_OnSelectionChanged); } else { plcParentObject.Visible = false; } } }
public override IntegrationProcessResultEnum ProcessInternalTaskAsync(GeneralizedInfo infoObj, TranslationHelper translations, TaskTypeEnum taskType, TaskDataTypeEnum dataType, string siteName, out string errorMessage) { try { //Determine if the record exists in Azure Storage // Retrieve the storage account from the connection string. CloudStorageAccount storageAccount = CloudStorageAccount.Parse(SettingsKeyInfoProvider.GetValue("Custom.AzureStorageConnectionString")); // Create the table client. CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); // Create the CloudTable object that represents the "kenticousers" table. CloudTable table = tableClient.GetTableReference("kenticousers"); // Create a retrieve operation that takes a customer entity. TableOperation retrieveOperation = TableOperation.Retrieve<KenticoUserEntity>(ValidationHelper.GetString(infoObj["UserGUID"], ""), ValidationHelper.GetString(infoObj["LastName"], "")); // Execute the operation. TableResult retrievedResult = table.Execute(retrieveOperation); // Assign the result to a CustomerEntity object. KenticoUserEntity existinguser = (KenticoUserEntity)retrievedResult.Result; //Check if the record already exists if (existinguser == null) { // create a new record KenticoUserEntity newuser = new KenticoUserEntity(ValidationHelper.GetString(infoObj["UserGUID"], ""), ValidationHelper.GetString(infoObj["LastName"], "")); newuser.firstname = ValidationHelper.GetString(infoObj["FirstName"], ""); newuser.lastname = ValidationHelper.GetString(infoObj["LastName"], ""); newuser.email = ValidationHelper.GetString(infoObj["Email"], ""); // Create the Insert TableOperation TableOperation insertOperation = TableOperation.Insert(newuser); // Execute the operation. table.Execute(insertOperation); EventLogProvider.LogEvent("I", "CustomIntegrationConnector", "Information", "Record inserted!"); } else { //update the record existinguser.firstname = ValidationHelper.GetString(infoObj["FirstName"], ""); existinguser.lastname = ValidationHelper.GetString(infoObj["LastName"], ""); existinguser.email = ValidationHelper.GetString(infoObj["Email"], ""); // Create the Update TableOperation TableOperation updateOperation = TableOperation.Replace(existinguser); // Execute the operation. table.Execute(updateOperation); EventLogProvider.LogEvent("I", "CustomIntegrationConnector", "Information", "Record updated!"); } //Set the error message to null and the response to OK errorMessage = null; return IntegrationProcessResultEnum.OK; } catch (Exception ex) { //There was a problem. errorMessage = ex.Message; return IntegrationProcessResultEnum.ErrorAndSkip; } }
/// <summary> /// Loads variables and objects. /// </summary> private void LoadControls() { // Display default name filter if (useDefaultNameFilter) { lblSearch.ResourceString = resourcePrefix + ".entersearch|general.entersearch"; btnSearch.ResourceString = "general.search"; pnlSearch.Visible = true; if (!RequestHelper.IsPostBack()) { ScriptHelper.RegisterStartupScript(this, typeof(string), "Focus", ScriptHelper.GetScript("try{document.getElementById('" + txtSearch.ClientID + "').focus();}catch(err){}")); } } // Load objects if (!String.IsNullOrEmpty(objectType)) { iObjectType = CMSObjectHelper.GetReadOnlyObject(objectType); if (iObjectType == null) { throw new Exception("[UniSelector.SelectionDialog]: Object type '" + objectType + "' not found."); } if (returnColumnName == null) { returnColumnName = iObjectType.IDColumn; } } if (!RequestHelper.IsPostBack()) { uniGrid.Pager.DefaultPageSize = itemsPerPage; } uniGrid.GridName = dialogGridName; uniGrid.GridView.EnableViewState = false; // Show the OK button if needed switch (selectionMode) { case SelectionModeEnum.Multiple: case SelectionModeEnum.MultipleTextBox: case SelectionModeEnum.MultipleButton: { pnlAll.Visible = true; lnkSelectAll.Text = GetString("UniSelector.SelectAll"); lnkDeselectAll.Text = GetString("UniSelector.DeselectAll"); } break; } }
/// <summary> /// Suitable for implementation of synchronous outcoming object processing. Identifiers of object are in their original state. /// </summary> /// <param name="infoObj">Object to process</param> /// <param name="taskType">Type of task</param> /// <param name="siteName">Name of site</param> /// <param name="errorMessage">Possible error message</param> /// <returns>Processing result</returns> public override IntegrationProcessResultEnum ProcessInternalTaskSync(GeneralizedInfo infoObj, TaskTypeEnum taskType, string siteName, out string errorMessage) { // Synchronous processing of objects (meaning processing is executed in the context of CMS right away) // (task is not being logged and processed afterwards in separate thread as in ProcessInternalTaskAsync method) errorMessage = null; return IntegrationProcessResultEnum.OK; }
// Get orderby expression private static string GetOrderByExpression(GeneralizedInfo info) { switch (info.TypeInfo.ObjectType) { case PageTemplateInfo.OBJECT_TYPE: return "PageTemplateIsReusable DESC," + info.DisplayNameColumn; default: { if (info.DisplayNameColumn != ObjectTypeInfo.COLUMN_NAME_UNKNOWN) { return info.DisplayNameColumn; } return info.CodeNameColumn; } } }
// Get orderby expression private string GetOrderByExpression(GeneralizedInfo info) { switch (info.ObjectType) { case PortalObjectType.PAGETEMPLATE: return "PageTemplateIsReusable DESC," + info.DisplayNameColumn; default: { if (info.DisplayNameColumn != TypeInfo.COLUMN_NAME_UNKNOWN) { return info.DisplayNameColumn; } else { return codeNameColumnName; } } } }
/// <summary> /// Sets info object to metadata editor. /// </summary> /// <param name="infoObject">Info object</param> public void SetMetaDataInfoObject(GeneralizedInfo infoObject) { metaDataEditor.InfoObject = infoObject; }