public async Task ImportMyLogsWithCachesAsync(Core.Storage.Database db, SiteInfo activeSite) { using (Utils.DataUpdater upd = new Utils.DataUpdater(db)) { await Task.Run(new Action(() => ImportMyLogsWithCaches(db, activeSite))); } }
public static Item GetWildcardSettingsFolder(SiteInfo siteInfo) { if(Sitecore.Context.Database == null || siteInfo == null) { return null; } string xpath = $"/sitecore/wildcard/settings/*[@name = '{siteInfo.Name}']"; var node = Factory.GetConfigNode(xpath); if (node == null) { node = Factory.GetConfigNode("/sitecore/wildcard/settings/*[@name = 'Default']"); } if(node == null) { return null; } var path = XmlUtil.GetAttribute("path", node, true); if(string.IsNullOrWhiteSpace(path)) { return null; } if(!path.StartsWith("/sitecore/", System.StringComparison.OrdinalIgnoreCase)) { path = string.Concat(siteInfo.RootPath, StringUtil.EnsurePrefix('/', path)); } return Sitecore.Context.Database.GetItem(path); }
protected void Page_Load(object sender, EventArgs e) { siteId = QueryHelper.GetInteger("siteid", 0); si = SiteInfoProvider.GetSiteInfo(siteId); EditedObject = si; if (!RequestHelper.IsPostBack()) { // Load input fields for the first time txtMessage.Value = si.SiteOfflineMessage; txtURL.Text = si.SiteOfflineRedirectURL; radURL.Checked = !String.IsNullOrEmpty(txtURL.Text); radMessage.Checked = !String.IsNullOrEmpty(txtMessage.Value); if (!radURL.Checked && !radMessage.Checked) { radMessage.Checked = true; } } txtMessage.MediaDialogConfig.HideContent = true; ScriptHelper.RegisterClientScriptBlock(Page, typeof(string), "EnableDisableTextBox", ScriptHelper.GetScript( "function EnableDisableBox(elementId, state) \n" + "{ var elem = document.getElementById(elementId); \n" + " if (elem) { \n" + " if (state == 0) { elem.disabled = 'disabled'; elem.readonly = 'readonly'; } \n" + " if (state == 1) { elem.disabled = ''; elem.readonly = ''; } \n" + " } \n" + "} \n")); radMessage.Attributes.Add("onclick", "EnableDisableBox('" + txtURL.ClientID + "', 0); EnableDisableBox('" + txtMessage.ClientID + "', 1);"); radURL.Attributes.Add("onclick", "EnableDisableBox('" + txtURL.ClientID + "', 1); EnableDisableBox('" + txtMessage.ClientID + "', 0);"); }
/// <summary> /// Gets number of users waiting for approval. /// </summary> /// <param name="site">Tile's site</param> /// <returns>Number of users waiting for approval</returns> private static int GetUsersWaitingForApprovalCount(SiteInfo site) { return UserInfoProvider.GetUsers() .Source(s => s.Join<UserSettingsInfo>("UserID", "UserSettingsUserID")) .OnSite(site.SiteID) .WhereEquals("UserWaitingForApproval", 1) .Count; }
private static string GetHostName(SiteInfo site) { if (!string.IsNullOrEmpty(site.TargetHostName)) return site.TargetHostName; if (Uri.CheckHostName(site.HostName) != UriHostNameType.Unknown) return site.HostName; throw new ConfigurationErrorsException($"Cannot determine hostname for site '{site}'"); }
/// <summary> /// Sets the specified site data. /// </summary> /// <param name="siteInfoObj">New site info data</param> protected override void SetSiteInfoInternal(SiteInfo siteInfoObj) { base.SetSiteInfoInternal(siteInfoObj); // Log the event that the site was updated EventLogProvider ev = new EventLogProvider(); ev.LogEvent(EventLogProvider.EVENT_TYPE_INFORMATION, DateTime.Now, "MyCustomSiteInfoProvider", "SetSiteInfo", null, "The site was updated"); }
public AuthorizationWindow(SiteInfo siteInfo) : this() { _siteInfo = siteInfo; webBrowser.LoadCompleted += webBrowser_LoadCompleted; webBrowser.NavigateToString("<html><body><h1>Loading authorization page, please wait...</h1></body></html>"); }
private SiteDefinition CreateSiteDefinition(SiteInfo siteInfo) { return new SiteDefinition { HostName = siteInfo.HostName, Name = siteInfo.Name, IsCurrent = IsCurrent(siteInfo.Name) }; }
public static void LogMessage(string message, SiteInfo siteInfo) { StringBuilder msg = new StringBuilder(Environment.NewLine); msg.Append("*** MESSAGE ***\r\n") .Append("SITE:\t").Append(siteInfo.SiteCode).Append("\r\n") .Append("DATE:\t").Append(DateTime.Now.ToString()).Append("\r\n") .Append("CONTENT:\t").Append(message).Append("\r\n"); File.AppendAllText(LOG_FILE, msg.ToString(), Encoding.UTF8); }
protected void Page_Load(object sender, EventArgs e) { // Initialization productId = QueryHelper.GetInteger("productId", 0); skuGuid = QueryHelper.GetGuid("skuguid", Guid.Empty); currentSite = SiteContext.CurrentSite; var skuObj = SKUInfoProvider.GetSKUInfo(productId); if ((skuObj != null) && skuObj.IsProductVariant) { // Get parent product of variant var parent = skuObj.Parent as SKUInfo; if (parent != null) { productId = parent.SKUID; skuGuid = parent.SKUGUID; } } string where = null; if (productId > 0) { where = "NodeSKUID = " + productId; } else if (skuGuid != Guid.Empty) { where = "SKUGUID = '" + skuGuid + "'"; } if ((where != null) && (currentSite != null)) { TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser); DataSet ds = tree.SelectNodes(currentSite.SiteName, "/%", TreeProvider.ALL_CULTURES, true, "", where); if (!DataHelper.DataSourceIsEmpty(ds)) { // Ger specified product url url = DocumentURLProvider.GetUrl(Convert.ToString(ds.Tables[0].Rows[0]["NodeAliasPath"])); } } if ((url != "") && (currentSite != null)) { // Redirect to specified product URLHelper.RedirectPermanent(url, currentSite.SiteName); } else { // Display error message lblInfo.Visible = true; lblInfo.Text = GetString("GetProduct.NotFound"); } }
public static void LogError(Exception ex, SiteInfo siteInfo) { StringBuilder err = new StringBuilder(Environment.NewLine); err.Append("=== EXCEPTION ===\r\n") .Append("SITE:\t").Append(siteInfo.SiteCode).Append("\r\n") .Append("DATE:\t").Append(DateTime.Now.ToString()).Append("\r\n") .Append("MESSAGE:").Append(ex.Message).Append("\r\n") .Append("STACKTRACE:").Append("\r\n") .Append(ex.StackTrace); File.AppendAllText(LOG_FILE, err.ToString(), Encoding.UTF8); }
public void GetDataSources_ShouldReturnSourceTemplateFromSiteDefinition([Frozen]ISettingsProvider settingsProvider, [Greedy]ConfigurationDatasourceProvider provider, string settingName, Item contextItem, DbItem sourceDbItem, Db db) { provider.Database = db.Database; db.Add(sourceDbItem); var sourceTemplate = db.GetItem(sourceDbItem.ID); var attributeName = $"{settingName}.{ConfigurationDatasourceProvider.DatasourceTemplatePostfix}"; var siteInfo = new SiteInfo(new StringDictionary { { attributeName, sourceTemplate.ID.ToString() } }); settingsProvider.GetCurrentSiteInfo(Arg.Any<Item>()).Returns(siteInfo); var sources = provider.GetDatasourceTemplate(settingName, contextItem); sources.Should().NotBeNull(); sources.ID.ShouldBeEquivalentTo(sourceTemplate.ID); }
private Item GetSiteRootItem(SiteInfo site) { if (site == null) throw new ArgumentNullException(nameof(site)); if (string.IsNullOrEmpty(site.Database)) return null; var database = Database.GetDatabase(site.Database); var item = database?.GetItem(site.RootPath); if (item == null || !IsSite(item)) return null; return item; }
/// <summary> /// Gets number of total pages waiting for the approval. /// </summary> /// <param name="siteInfo">Site the pages belongs to</param> /// <param name="userInfo">The user providing the approval</param> /// <returns>Total number of waiting pages</returns> private int GetNumberOfPendingPages(SiteInfo siteInfo, UserInfo userInfo) { int siteId = siteInfo.SiteID; // Get correct pending steps which may current user manage var steps = new IDQuery<WorkflowStepInfo>().Where(WorkflowStepInfoProvider.GetWorkflowPendingStepsWhereCondition(userInfo, siteId)); var docs = new IDQuery<TreeNode>() .OnSite(siteId) .WhereIn("DocumentWorkflowStepID", steps); return docs.Count; }
/// <summary> /// 获取carPm数据 /// </summary> /// <param name="siteInfo"></param> /// <param name="log"></param> /// <param name="tag"></param> /// <param name="xmlSql"></param> private void GetCarPmData(SiteInfo siteInfo, StringBuilder log, object tag, XmlDocument xmlSql, Database db, Database dbMultekApps) { // 从配置文件中获取,以分号隔开 string customerStr = xmlSql.SelectSingleNode("/Root/CarPm/Customers").InnerText.Trim(); string querySql = xmlSql.SelectSingleNode("/Root/CarPm/Select").InnerText; string insertSql = xmlSql.SelectSingleNode("/Root/CarPm/Insert").InnerText; string countSql = xmlSql.SelectSingleNode("/Root/CarPm/QueryCount").InnerText; string updateSql = xmlSql.SelectSingleNode("/Root/CarPm/Update").InnerText; // 拆分用户字段 string[] customs = customerStr.Split(new char[] {';', ',', ';', ','}); foreach (string custom in customs) { if (!string.IsNullOrWhiteSpace(custom)) { DataTable dtCarPm = dbMultekApps.CustomSql(string.Format(querySql, custom)).ToDataTable(); foreach (DataRow drCarPm in dtCarPm.Rows) {// 插入每行数据, 如存在则更新,否则插入 int count = db.CustomSql(string.Format(countSql, drCarPm["rpm"].ToString())).ToScalar<int>(); if (count > 0) {//存在,则更新 string updateSqlNew = string.Format(updateSql, drCarPm["pdesc"].ToString().Replace("'", "''"), drCarPm["compelet_date"].ToString(), drCarPm["resolution"].ToString().Replace("'", "''"), drCarPm["delay_date"].ToString(), drCarPm["rpm"].ToString()); db.CustomSql(updateSqlNew).ExecuteNonQuery(); } else {//不存在,插入 string insertSqlNew = string.Format(insertSql, drCarPm["rpm"].ToString(), custom, drCarPm["pdesc"].ToString().Replace("'", "''"), drCarPm["occurr_date"].ToString(), drCarPm["compelet_date"].ToString(), drCarPm["resolution"].ToString().Replace("'", "''"), drCarPm["delay_date"].ToString() ); db.CustomSql(insertSqlNew).ExecuteNonQuery(); } } } } }
public void CreateNewSiteInfo() { var profileId = profileRepository.FindProfileId(profileReference); siteInfoRepository.DeleteSiteInfo(profileId); var siteInfo = new SiteInfo { Id = string.Empty, ProfileId = profileId, Theme = "blue", Title = "Michael Quinn - .NET Developer Irvine, CA", Description = "Michael Quinn - .NET Developer Irvine, CA" }; siteInfoRepository.SaveSiteInfo(siteInfo); var results = siteInfoRepository.GetSiteInfo(profileId); Assert.AreEqual(profileId, results.ProfileId); }
protected void Page_Load(object sender, EventArgs e) { // Get the site info si = SiteInfoProvider.GetSiteInfo(QueryHelper.GetInteger("siteId", 0)); if (si != null) { bool multilingual = LicenseHelper.CheckFeature(URLHelper.GetDomainName(si.DomainName), FeatureEnum.Multilingual); bool cultureOnSite = CultureInfoProvider.IsCultureOnSite(CultureHelper.GetDefaultCulture(si.SiteName), si.SiteName); if (!multilingual && !cultureOnSite) { lnkAssignDefault.Text = GetString("sitecultures.assigntodefault"); lnkAssignDefault.Visible = true; plcAll.Visible = false; } else { // Redirect only if cultures not exceeded => to be able to unassign if (!CultureInfoProvider.LicenseVersionCheck(si.DomainName, FeatureEnum.Multilingual, VersionActionEnum.Edit)) { LicenseHelper.CheckFeatureAndRedirect(URLHelper.GetDomainName(si.DomainName), FeatureEnum.Multilingual); } } lblAvialable.Text = GetString("site_edit_cultures.culturetitle"); siteName = si.SiteName; // Store default culture (it can't be removed) defaultCulture = CultureHelper.GetDefaultCulture(siteName); // Get the active cultures from DB DataSet ds = CultureInfoProvider.GetCultures("CultureID IN (SELECT CultureID FROM CMS_SiteCulture WHERE SiteID = " + si.SiteID + ")", null, 0, "CultureCode"); if (!DataHelper.DataSourceIsEmpty(ds)) { currentValues = TextHelper.Join(";", SystemDataHelper.GetStringValues(ds.Tables[0], "CultureCode")); } if (!RequestHelper.IsPostBack()) { uniSelector.Value = currentValues; } } uniSelector.ReturnColumnName = "CultureCode"; uniSelector.OnSelectionChanged += uniSelector_OnSelectionChanged; }
protected void Page_Load(object sender, EventArgs e) { configuredSite = SiteInfoProvider.GetSiteInfo(ConfiguredSiteID); // Check permissions for CMS Desk -> Ecommerce if (!CMSContext.CurrentUser.IsAuthorizedPerUIElement("CMS.Ecommerce", "Configuration.Settings.CheckoutProcess")) { RedirectToCMSDeskUIElementAccessDenied("CMS.Ecommerce", "Configuration.Settings.CheckoutProcess"); } // Set up header CurrentMaster.HeaderActions.Actions = GetHeaderActions(); CurrentMaster.HeaderActions.ActionPerformed += HeaderActions_ActionPerformed; // Modify page content css class Panel pnl = CurrentMaster.PanelBody.FindControl("pnlContent") as Panel; if (pnl != null) { pnl.CssClass = ""; } // Hide buttons - this page has custom header action ucCheckoutProcess.ShowActions = false; ucCheckoutProcess.OnModeChanged += new CMSModules_Ecommerce_FormControls_CheckoutProcess.ModeChangedHandler(ucCheckoutProcess_OnModeChanged); // Register javascript to confirm generate default checkout process string script = "function ConfirmGlobalProcess() {return confirm(" + ScriptHelper.GetString(GetString("CheckoutProcess.ConfirmGlobalProcess")) + ");}"; ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "ConfirmGlobalProcess", ScriptHelper.GetScript(script)); ucCheckoutProcess.OnCheckoutProcessDefinitionUpdate += new OnCheckoutProcessDefinitionUpdateEventHandler(ucCheckoutProcess_OnCheckoutProcessDefinitionUpdate); // Load data if (!RequestHelper.IsPostBack()) { if (configuredSite != null) { ucCheckoutProcess.Value = ECommerceSettings.CheckoutProcess(configuredSite.SiteName); } else { ucCheckoutProcess.Value = ECommerceSettings.CheckoutProcess(null); } ucCheckoutProcess.EnableDefaultCheckoutProcessTypes = true; } }
protected void Page_Load(object sender, EventArgs e) { configuredSite = SiteInfoProvider.GetSiteInfo(ConfiguredSiteID); // Check UI element var elementName = IsMultiStoreConfiguration ? "Tools.Ecommerce.ChackoutSettings" : "Configuration.Settings.CheckoutProcess"; CheckUIElementAccessHierarchical(ModuleName.ECOMMERCE, elementName); // Set up header InitHeaderActions(); // Modify page content css class Panel pnl = CurrentMaster.PanelBody.FindControl("pnlContent") as Panel; if (pnl != null) { pnl.CssClass = ""; } ucCheckoutProcess.OnModeChanged += ucCheckoutProcess_OnModeChanged; // Register javascript to confirm generate default checkout process string script = "function ConfirmGlobalProcess() {return confirm(" + ScriptHelper.GetString(GetString("CheckoutProcess.ConfirmGlobalProcess")) + ");}"; ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "ConfirmGlobalProcess", ScriptHelper.GetScript(script)); ucCheckoutProcess.OnCheckoutProcessDefinitionUpdate += ucCheckoutProcess_OnCheckoutProcessDefinitionUpdate; // Load data if (!RequestHelper.IsPostBack()) { if (configuredSite != null) { ucCheckoutProcess.Value = ECommerceSettings.CheckoutProcess(configuredSite.SiteName); } else { ucCheckoutProcess.Value = ECommerceSettings.CheckoutProcess(null); } ucCheckoutProcess.EnableDefaultCheckoutProcessTypes = true; } }
protected void Page_Load(object sender, EventArgs e) { // Initialization productId = QueryHelper.GetInteger("productId", 0); skuGuid = QueryHelper.GetGuid("skuguid", Guid.Empty); currentSite = CMSContext.CurrentSite; string where = null; if (productId > 0) { where = "NodeSKUID = " + productId; } else if (skuGuid != Guid.Empty) { where = "SKUGUID = '" + skuGuid.ToString() + "'"; } if ((where != null) && (currentSite != null)) { TreeProvider tree = new TreeProvider(CMSContext.CurrentUser); DataSet ds = tree.SelectNodes(currentSite.SiteName, "/%", TreeProvider.ALL_CULTURES, true, "", where); if (!DataHelper.DataSourceIsEmpty(ds)) { // Ger specified product url url = CMSContext.GetUrl(Convert.ToString(ds.Tables[0].Rows[0]["NodeAliasPath"])); } } if (url != "") { // Redirect to specified product URLHelper.Redirect(url); } else { // Display error message lblInfo.Visible = true; lblInfo.Text = GetString("GetProduct.NotFound"); } }
/// <summary> /// 执行job /// </summary> /// <param name="siteInfo"></param> /// <param name="log"></param> /// <param name="tag"></param> protected override void Execute(SiteInfo siteInfo, StringBuilder log, object tag) { // 读取xml中的sql语句执行 XmlDocument xmlSql = new XmlDocument(); xmlSql.Load(AppDomain.CurrentDomain.BaseDirectory + "SqlCommandText.xml"); Database db = new Database(DatabaseType.SqlServer, siteInfo.ConnectionConfig); //创建multek_801 Multek_Apps数据库的连接 ConnectionStringSettings sqlServerConnectionApps = ConfigurationManager.ConnectionStrings["db_mcn801multekapp"]; Database dbMultekApps = new Database(DatabaseType.SqlServer, sqlServerConnectionApps.ConnectionString); //创建multek_801 Multek_Apps数据库的连接 ConnectionStringSettings sqlServerConnectionBI = ConfigurationManager.ConnectionStrings["db_mcn801multekbi"]; Database dbMultekBI = new Database(DatabaseType.SqlServer, sqlServerConnectionBI.ConnectionString); //获取carPm数据 GetCarPmData(siteInfo, log, tag, xmlSql, db, dbMultekApps); //获取ForeCast, period_amount, bklog_amount数据 GetPeriodDataByCustom(siteInfo, log, tag, xmlSql, db, dbMultekBI); }
private static ArrayList GetSites() { ArrayList sites = f_sites; if (sites == null) { sites = new ArrayList(); XmlNodeList configSites = GetSitesNodes("sites/site"); List<string> hostNames = new List<string>(); if (configSites != null) { foreach (XmlNode node in configSites) { SiteInfo info = new SiteInfo(node); if (info.IsActive) { sites.Add(info); } } } f_sites = sites; } return sites; }
private static string GetColumnValue(Dictionary <string, string> nameValueCacheDict, SiteInfo siteInfo, ContentInfo contentInfo, TableStyleInfo styleInfo) { var value = string.Empty; if (StringUtils.EqualsIgnoreCase(styleInfo.AttributeName, ContentAttribute.AddUserName)) { if (!string.IsNullOrEmpty(contentInfo.AddUserName)) { var key = ContentAttribute.AddUserName + ":" + contentInfo.AddUserName; if (!nameValueCacheDict.TryGetValue(key, out value)) { value = AdminManager.GetDisplayName(contentInfo.AddUserName); nameValueCacheDict[key] = value; } } } else if (StringUtils.EqualsIgnoreCase(styleInfo.AttributeName, ContentAttribute.LastEditUserName)) { if (!string.IsNullOrEmpty(contentInfo.LastEditUserName)) { var key = ContentAttribute.LastEditUserName + ":" + contentInfo.LastEditUserName; if (!nameValueCacheDict.TryGetValue(key, out value)) { value = AdminManager.GetDisplayName(contentInfo.LastEditUserName); nameValueCacheDict[key] = value; } } } else if (StringUtils.EqualsIgnoreCase(styleInfo.AttributeName, ContentAttribute.CheckUserName)) { var checkUserName = contentInfo.GetString(ContentAttribute.CheckUserName); if (!string.IsNullOrEmpty(checkUserName)) { var key = ContentAttribute.CheckUserName + ":" + checkUserName; if (!nameValueCacheDict.TryGetValue(key, out value)) { value = AdminManager.GetDisplayName(checkUserName); nameValueCacheDict[key] = value; } } } else if (StringUtils.EqualsIgnoreCase(styleInfo.AttributeName, ContentAttribute.CheckDate)) { var checkDate = contentInfo.GetDateTime(ContentAttribute.CheckDate, DateTime.MinValue); if (checkDate != DateTime.MinValue) { value = DateUtils.GetDateAndTimeString(checkDate); } } else if (StringUtils.EqualsIgnoreCase(styleInfo.AttributeName, ContentAttribute.CheckReasons)) { value = contentInfo.GetString(ContentAttribute.CheckReasons); } else if (StringUtils.EqualsIgnoreCase(styleInfo.AttributeName, ContentAttribute.AddDate)) { value = DateUtils.GetDateAndTimeString(contentInfo.AddDate); } else if (StringUtils.EqualsIgnoreCase(styleInfo.AttributeName, ContentAttribute.LastEditDate)) { value = DateUtils.GetDateAndTimeString(contentInfo.LastEditDate); } else if (StringUtils.EqualsIgnoreCase(styleInfo.AttributeName, ContentAttribute.SourceId)) { value = SourceManager.GetSourceName(contentInfo.SourceId); } else if (StringUtils.EqualsIgnoreCase(styleInfo.AttributeName, ContentAttribute.Tags)) { value = contentInfo.Tags; } else if (StringUtils.EqualsIgnoreCase(styleInfo.AttributeName, ContentAttribute.GroupNameCollection)) { value = contentInfo.GroupNameCollection; } else if (StringUtils.EqualsIgnoreCase(styleInfo.AttributeName, ContentAttribute.Hits)) { value = contentInfo.Hits.ToString(); } else if (StringUtils.EqualsIgnoreCase(styleInfo.AttributeName, ContentAttribute.HitsByDay)) { value = contentInfo.HitsByDay.ToString(); } else if (StringUtils.EqualsIgnoreCase(styleInfo.AttributeName, ContentAttribute.HitsByWeek)) { value = contentInfo.HitsByWeek.ToString(); } else if (StringUtils.EqualsIgnoreCase(styleInfo.AttributeName, ContentAttribute.HitsByMonth)) { value = contentInfo.HitsByMonth.ToString(); } else if (StringUtils.EqualsIgnoreCase(styleInfo.AttributeName, ContentAttribute.LastHitsDate)) { value = DateUtils.GetDateAndTimeString(contentInfo.LastHitsDate); } else if (StringUtils.EqualsIgnoreCase(styleInfo.AttributeName, ContentAttribute.Downloads)) { value = contentInfo.Downloads.ToString(); } else if (StringUtils.EqualsIgnoreCase(styleInfo.AttributeName, ContentAttribute.IsTop) || StringUtils.EqualsIgnoreCase(styleInfo.AttributeName, ContentAttribute.IsColor) || StringUtils.EqualsIgnoreCase(styleInfo.AttributeName, ContentAttribute.IsHot) || StringUtils.EqualsIgnoreCase(styleInfo.AttributeName, ContentAttribute.IsRecommend)) { value = StringUtils.GetTrueImageHtml(contentInfo.GetString(styleInfo.AttributeName)); } else { value = InputParserUtility.GetContentByTableStyle(contentInfo.GetString(styleInfo.AttributeName), siteInfo, styleInfo); } return(value); }
bool IExportControl.Run() { var filePath = txtTargetPath.Text; if (string.IsNullOrEmpty(filePath)) { ShowMessageBox(Strings.MessageSelectOutputPathFirst); return(false); } #if !R2014 if (CustomExporter.IsRenderingSupported() == false && ShowConfirmBox(Strings.ExportWillFailBecauseMaterialLib) == false) { return(false); } #endif if (File.Exists(filePath) && ShowConfirmBox(Strings.OutputFileExistedWarning) == false) { return(false); } var homePath = InnerApp.GetHomePath(); if (InnerApp.CheckHomeFolder(homePath) == false && ShowConfirmBox(Strings.HomeFolderIsInvalid) == false) { return(false); } var visualStyle = cbVisualStyle.SelectedItem as VisualStyleInfo; if (visualStyle != null) { foreach (var p in visualStyle.Features) { _Features.FirstOrDefault(x => x.Type == p.Key)?.ChangeSelected(_Features, p.Value); } } var levelOfDetail = (cbLevelOfDetail.SelectedItem as ComboItemInfo) ?? _LevelOfDetailDefault; #region 更新界面选项到 _Features void SetFeature(FeatureType featureType, bool selected) { _Features.FirstOrDefault(x => x.Type == featureType)?.ChangeSelected(_Features, selected); } //SetFeature(FeatureType.ExportGrids, cbIncludeGrids.Checked); SetFeature(FeatureType.ExcludeLines, cbExcludeLines.Checked); SetFeature(FeatureType.ExcludePoints, cbExcludeModelPoints.Checked); SetFeature(FeatureType.OnlySelected, cbExcludeUnselectedElements.Checked); SetFeature(FeatureType.UseGoogleDraco, cbUseDraco.Checked); SetFeature(FeatureType.ExtractShell, cbUseExtractShell.Checked); SetFeature(FeatureType.GenerateModelsDb, cbGeneratePropDbSqlite.Checked); SetFeature(FeatureType.ExportSvfzip, cbExportSvfzip.Checked); #endregion var isCanncelled = false; using (var session = LicenseConfig.Create()) { if (session.IsValid == false) { LicenseConfig.ShowDialog(session, ParentForm); return(false); } #region 保存设置 var config = _LocalConfig; config.Features = _Features.Where(x => x.Selected).Select(x => x.Type).ToList(); config.LastTargetPath = txtTargetPath.Text; config.VisualStyle = visualStyle?.Key; config.LevelOfDetail = levelOfDetail?.Value ?? -1; _Config.Save(); #endregion var sw = Stopwatch.StartNew(); try { var setting = new ExportSetting(); setting.LevelOfDetail = config.LevelOfDetail; setting.OutputPath = config.LastTargetPath; setting.Features = _Features.Where(x => x.Selected && x.Enabled).Select(x => x.Type).ToList(); setting.SelectedElementIds = _ElementIds?.Where(x => x.Value).Select(x => x.Key).ToList(); setting.Site = ExporterHelper.GetSiteInfo(_View.Document) ?? SiteInfo.CreateDefault(); setting.Oem = LicenseConfig.GetOemInfo(homePath); var hasSuccess = false; using (var progress = new ProgressExHelper(this.ParentForm, Strings.MessageExporting)) { var cancellationToken = progress.GetCancellationToken(); #if !DEBUG //在有些 Revit 会遇到时不时无法转换的问题,循环多次重试, 应该可以成功 for (var i = 0; i < 5; i++) { try { StartExport(_UIDocument, _View, setting, progress.GetProgressCallback(), cancellationToken); hasSuccess = true; break; } catch (Autodesk.Revit.Exceptions.ExternalApplicationException) { Application.DoEvents(); } catch (IOException ex) { ShowMessageBox("文件保存失败: " + ex.Message); hasSuccess = true; break; } } #endif //如果之前多次重试仍然没有成功, 这里再试一次,如果再失败就会给出稍后重试的提示 if (hasSuccess == false) { StartExport(_UIDocument, _View, setting, progress.GetProgressCallback(), cancellationToken); } isCanncelled = cancellationToken.IsCancellationRequested; } sw.Stop(); var ts = sw.Elapsed; ExportDuration = new TimeSpan(ts.Days, ts.Hours, ts.Minutes, ts.Seconds); //去掉毫秒部分 Debug.WriteLine(Strings.MessageOperationSuccessAndElapsedTime, ExportDuration); if (isCanncelled == false) { ShowMessageBox(string.Format(Strings.MessageExportSuccess, ExportDuration)); } } catch (IOException ex) { sw.Stop(); Debug.WriteLine(Strings.MessageOperationFailureAndElapsedTime, sw.Elapsed); ShowMessageBox(string.Format(Strings.MessageFileSaveFailure, ex.Message)); } catch (Autodesk.Revit.Exceptions.ExternalApplicationException) { sw.Stop(); Debug.WriteLine(Strings.MessageOperationFailureAndElapsedTime, sw.Elapsed); ShowMessageBox(Strings.MessageOperationFailureAndTryLater); } catch (Exception ex) { sw.Stop(); Debug.WriteLine(Strings.MessageOperationFailureAndElapsedTime, sw.Elapsed); ShowMessageBox(ex.ToString()); } } return(isCanncelled == false); }
public static void TransContentInfo(SiteInfo siteInfo, ChannelInfo channelInfo, int contentId, SiteInfo targetSiteInfo, int targetChannelId) { var targetTableName = ChannelManager.GetTableName(targetSiteInfo, targetChannelId); var tableName = ChannelManager.GetTableName(siteInfo, channelInfo); var contentInfo = DataProvider.ContentDao.GetContentInfo(tableName, contentId); FileUtility.MoveFileByContentInfo(siteInfo, targetSiteInfo, contentInfo); contentInfo.SiteId = targetSiteInfo.Id; contentInfo.SourceId = channelInfo.Id; contentInfo.ChannelId = targetChannelId; contentInfo.IsChecked = targetSiteInfo.Additional.IsCrossSiteTransChecked; contentInfo.CheckedLevel = 0; //复制 if (Equals(channelInfo.Additional.TransDoneType, ETranslateContentType.Copy)) { contentInfo.Set(ContentAttribute.TranslateContentType, ETranslateContentType.Copy.ToString()); } //引用地址 else if (Equals(channelInfo.Additional.TransDoneType, ETranslateContentType.Reference)) { contentInfo.SiteId = targetSiteInfo.Id; contentInfo.SourceId = channelInfo.Id; contentInfo.ChannelId = targetChannelId; contentInfo.ReferenceId = contentId; contentInfo.Set(ContentAttribute.TranslateContentType, ETranslateContentType.Reference.ToString()); } //引用内容 else if (Equals(channelInfo.Additional.TransDoneType, ETranslateContentType.ReferenceContent)) { contentInfo.SiteId = targetSiteInfo.Id; contentInfo.SourceId = channelInfo.Id; contentInfo.ChannelId = targetChannelId; contentInfo.ReferenceId = contentId; contentInfo.Set(ContentAttribute.TranslateContentType, ETranslateContentType.ReferenceContent.ToString()); } if (!string.IsNullOrEmpty(targetTableName)) { DataProvider.ContentDao.Insert(targetTableName, targetSiteInfo, contentInfo); #region 制资源 //资源:图片,文件,视频 if (!string.IsNullOrEmpty(contentInfo.GetString(BackgroundContentAttribute.ImageUrl))) { //修改图片 var sourceImageUrl = PathUtility.MapPath(siteInfo, contentInfo.GetString(BackgroundContentAttribute.ImageUrl)); CopyReferenceFiles(targetSiteInfo, sourceImageUrl, siteInfo); } else if (!string.IsNullOrEmpty(contentInfo.GetString(ContentAttribute.GetExtendAttributeName(BackgroundContentAttribute.ImageUrl)))) { var sourceImageUrls = TranslateUtils.StringCollectionToStringList(contentInfo.GetString(ContentAttribute.GetExtendAttributeName(BackgroundContentAttribute.ImageUrl))); foreach (string imageUrl in sourceImageUrls) { var sourceImageUrl = PathUtility.MapPath(siteInfo, imageUrl); CopyReferenceFiles(targetSiteInfo, sourceImageUrl, siteInfo); } } if (!string.IsNullOrEmpty(contentInfo.GetString(BackgroundContentAttribute.FileUrl))) { //修改附件 var sourceFileUrl = PathUtility.MapPath(siteInfo, contentInfo.GetString(BackgroundContentAttribute.FileUrl)); CopyReferenceFiles(targetSiteInfo, sourceFileUrl, siteInfo); } else if (!string.IsNullOrEmpty(contentInfo.GetString(ContentAttribute.GetExtendAttributeName(BackgroundContentAttribute.FileUrl)))) { var sourceFileUrls = TranslateUtils.StringCollectionToStringList(contentInfo.GetString(ContentAttribute.GetExtendAttributeName(BackgroundContentAttribute.FileUrl))); foreach (string fileUrl in sourceFileUrls) { var sourceFileUrl = PathUtility.MapPath(siteInfo, fileUrl); CopyReferenceFiles(targetSiteInfo, sourceFileUrl, siteInfo); } } #endregion } }
private static void CopyReferenceFiles(SiteInfo targetSiteInfo, string sourceUrl, SiteInfo sourceSiteInfo) { var targetUrl = StringUtils.ReplaceFirst(sourceSiteInfo.SiteDir, sourceUrl, targetSiteInfo.SiteDir); if (!FileUtils.IsFileExists(targetUrl)) { FileUtils.CopyFile(sourceUrl, targetUrl, true); } }
private void Set(Context context, SiteSettings ss, DataRow dataRow, string tableAlias = null) { AccessStatus = Databases.AccessStatuses.Selected; foreach (DataColumn dataColumn in dataRow.Table.Columns) { var column = new ColumnNameInfo(dataColumn.ColumnName); if (column.TableAlias == tableAlias) { switch (column.Name) { case "TenantId": if (dataRow[column.ColumnName] != DBNull.Value) { TenantId = dataRow[column.ColumnName].ToInt(); SavedTenantId = TenantId; } break; case "Ver": Ver = dataRow[column.ColumnName].ToInt(); SavedVer = Ver; break; case "TenantName": TenantName = dataRow[column.ColumnName].ToString(); SavedTenantName = TenantName; break; case "Title": Title = new Title(dataRow, "TenantId"); SavedTitle = Title.Value; break; case "Body": Body = dataRow[column.ColumnName].ToString(); SavedBody = Body; break; case "ContractSettings": ContractSettings = GetContractSettings(dataRow); SavedContractSettings = ContractSettings?.RecordingJson(); break; case "ContractDeadline": ContractDeadline = dataRow[column.ColumnName].ToDateTime(); SavedContractDeadline = ContractDeadline; break; case "DisableAllUsersPermission": DisableAllUsersPermission = dataRow[column.ColumnName].ToBool(); SavedDisableAllUsersPermission = DisableAllUsersPermission; break; case "LogoType": LogoType = (LogoTypes)dataRow[column.ColumnName].ToInt(); SavedLogoType = LogoType.ToInt(); break; case "HtmlTitleTop": HtmlTitleTop = dataRow[column.ColumnName].ToString(); SavedHtmlTitleTop = HtmlTitleTop; break; case "HtmlTitleSite": HtmlTitleSite = dataRow[column.ColumnName].ToString(); SavedHtmlTitleSite = HtmlTitleSite; break; case "HtmlTitleRecord": HtmlTitleRecord = dataRow[column.ColumnName].ToString(); SavedHtmlTitleRecord = HtmlTitleRecord; break; case "Comments": Comments = dataRow[column.ColumnName].ToString().Deserialize <Comments>() ?? new Comments(); SavedComments = Comments.ToJson(); break; case "Creator": Creator = SiteInfo.User(context: context, userId: dataRow.Int(column.ColumnName)); SavedCreator = Creator.Id; break; case "Updator": Updator = SiteInfo.User(context: context, userId: dataRow.Int(column.ColumnName)); SavedUpdator = Updator.Id; break; case "CreatedTime": CreatedTime = new Time(context, dataRow, column.ColumnName); SavedCreatedTime = CreatedTime.Value; break; case "UpdatedTime": UpdatedTime = new Time(context, dataRow, column.ColumnName); Timestamp = dataRow.Field <DateTime>(column.ColumnName).ToString("yyyy/M/d H:m:s.fff"); SavedUpdatedTime = UpdatedTime.Value; break; case "IsHistory": VerType = dataRow.Bool(column.ColumnName) ? Versions.VerTypes.History : Versions.VerTypes.Latest; break; default: switch (Def.ExtendedColumnTypes.Get(column.Name)) { case "Class": Class( columnName: column.Name, value: dataRow[column.ColumnName].ToString()); SavedClass( columnName: column.Name, value: Class(columnName: column.Name)); break; case "Num": Num( columnName: column.Name, value: dataRow[column.ColumnName].ToDecimal()); SavedNum( columnName: column.Name, value: Num(columnName: column.Name)); break; case "Date": Date( columnName: column.Name, value: dataRow[column.ColumnName].ToDateTime()); SavedDate( columnName: column.Name, value: Date(columnName: column.Name)); break; case "Description": Description( columnName: column.Name, value: dataRow[column.ColumnName].ToString()); SavedDescription( columnName: column.Name, value: Description(columnName: column.Name)); break; case "Check": Check( columnName: column.Name, value: dataRow[column.ColumnName].ToBool()); SavedCheck( columnName: column.Name, value: Check(columnName: column.Name)); break; case "Attachments": Attachments( columnName: column.Name, value: dataRow[column.ColumnName].ToString() .Deserialize <Attachments>() ?? new Attachments()); SavedAttachments( columnName: column.Name, value: Attachments(columnName: column.Name).ToJson()); break; } break; } } } }
protected DataSet gridDocuments_OnDataReload(string completeWhere, string currentOrder, int currentTopN, string columns, int currentOffset, int currentPageSize, ref int totalRecords) { dataLoaded = true; if (Node != null) { if (gridDocuments.FilterForm.FieldControls != null) { // Get value of filter checkbox FormEngineUserControl checkboxControl = gridDocuments.FilterForm.FieldControls["ShowAllLevels"]; if (checkboxControl != null) { ShowAllLevels = ValidationHelper.GetBoolean(checkboxControl.Value, false); } } // Setup where condition string where; if (ShowAllLevels) { if (!checkPermissions) { // Add required columns if check permissions is false because of all levels enabled (Browse tree security check is performed) columns = SqlHelper.MergeColumns(TreeProvider.SECURITYCHECK_REQUIRED_COLUMNS, columns); } string path = aliasPath ?? string.Empty; path = path.TrimEnd('/'); where = string.Format("NodeAliasPath LIKE N'{0}/%' AND NodeLevel > 0", SqlHelper.EscapeLikeText(SqlHelper.EscapeQuotes(path))); } else { where = string.Format("NodeParentID = {0} AND NodeLevel = {1}", Node.NodeID, Node.NodeLevel + 1); // Extend the where condition to include the root document if (RequiresDialog && (Node != null) && (Node.NodeParentID == 0)) { where = SqlHelper.AddWhereCondition(where, "NodeParentID = 0", "OR"); OrderBy = "NodeParentID ASC" + ((OrderBy.Length > 0) ? "," : "") + OrderBy; } } if (ClassID > 0) { where = SqlHelper.AddWhereCondition(where, "NodeClassID = " + ClassID); } where = SqlHelper.AddWhereCondition(where, WhereCodition); completeWhere = SqlHelper.AddWhereCondition(completeWhere, where); // Get the site SiteInfo si = SiteInfoProvider.GetSiteInfo(Node.NodeSiteID); if (si != null) { DataSet ds = null; if (!checkPermissions || (MembershipContext.AuthenticatedUser.IsAuthorizedPerDocument(Node, NodePermissionsEnum.Read) == AuthorizationResultEnum.Allowed)) { // Merge document and grid specific columns columns = SqlHelper.MergeColumns(TreeProvider.SELECTNODES_REQUIRED_COLUMNS, columns); var query = DocumentHelper.GetDocuments() .TopN(gridDocuments.TopN) .Columns(columns) .OnSite(currentSiteName) .Published(false) .CombineWithDefaultCulture() .Culture(GetSiteCultures()) .Where(completeWhere) .OrderBy(OrderBy); query.Offset = currentOffset; query.MaxRecords = currentPageSize; if (ClassID > 0) { query.ClassName = DataClassInfoProvider.GetClassName(ClassID); } ds = query.Result; totalRecords = query.TotalRecords; } else { gridDocuments.ZeroRowsText = GetString("ContentTree.ReadDocumentDenied"); } // Check permissions if (checkPermissions || ShowAllLevels) { NodePermissionsEnum[] permissions = null; if (checkPermissions && ShowAllLevels) { permissions = new[] { NodePermissionsEnum.Read, NodePermissionsEnum.ExploreTree }; } else if (checkPermissions) { permissions = new[] { NodePermissionsEnum.Read }; } else if (ShowAllLevels) { permissions = new[] { NodePermissionsEnum.ExploreTree }; } ds = TreeSecurityProvider.FilterDataSetByPermissions(ds, permissions, currentUserInfo, false, true); } // Hide mass actions when no data ctrlMassActions.Visible = !DataHelper.DataSourceIsEmpty(ds); // Set the data source return(ds); } } return(null); }
public static string GetCheckState(SiteInfo siteInfo, bool isChecked, int level) { if (isChecked) { return(Level.YiShenHe); } var retval = String.Empty; if (level == LevelInt.CaoGao) { retval = Level.CaoGao; } else if (level == LevelInt.DaiShen) { retval = Level.DaiShen; } else { var checkContentLevel = siteInfo.Additional.CheckContentLevel; if (checkContentLevel == 1) { if (level == LevelInt.Fail1) { retval = Level1.Fail1; } } else if (checkContentLevel == 2) { if (level == LevelInt.Pass1) { retval = Level2.Pass1; } else if (level == LevelInt.Fail1) { retval = Level2.Fail1; } else if (level == LevelInt.Fail2) { retval = Level2.Fail2; } } else if (checkContentLevel == 3) { if (level == LevelInt.Pass1) { retval = Level3.Pass1; } else if (level == LevelInt.Pass2) { retval = Level3.Pass2; } else if (level == LevelInt.Fail1) { retval = Level3.Fail1; } else if (level == LevelInt.Fail2) { retval = Level3.Fail2; } else if (level == LevelInt.Fail3) { retval = Level3.Fail3; } } else if (checkContentLevel == 4) { if (level == LevelInt.Pass1) { retval = Level4.Pass1; } else if (level == LevelInt.Pass2) { retval = Level4.Pass2; } else if (level == LevelInt.Pass3) { retval = Level4.Pass3; } else if (level == LevelInt.Fail1) { retval = Level4.Fail1; } else if (level == LevelInt.Fail2) { retval = Level4.Fail2; } else if (level == LevelInt.Fail3) { retval = Level4.Fail3; } else if (level == LevelInt.Fail4) { retval = Level4.Fail4; } } else if (checkContentLevel == 5) { if (level == LevelInt.Pass1) { retval = Level5.Pass1; } else if (level == LevelInt.Pass2) { retval = Level5.Pass2; } else if (level == LevelInt.Pass3) { retval = Level5.Pass3; } else if (level == LevelInt.Pass4) { retval = Level5.Pass4; } else if (level == LevelInt.Fail1) { retval = Level5.Fail1; } else if (level == LevelInt.Fail2) { retval = Level5.Fail2; } else if (level == LevelInt.Fail3) { retval = Level5.Fail3; } else if (level == LevelInt.Fail4) { retval = Level5.Fail4; } else if (level == LevelInt.Fail5) { retval = Level5.Fail5; } } if (String.IsNullOrEmpty(retval)) { if (checkContentLevel == 1) { retval = Level.DaiShen; } else if (checkContentLevel == 2) { retval = Level2.Pass1; } else if (checkContentLevel == 3) { retval = Level3.Pass2; } else if (checkContentLevel == 4) { retval = Level4.Pass3; } } } return($"<span style='color:red'>{retval}</span>"); }
public static void LoadContentLevelToCheck(ListControl listControl, SiteInfo siteInfo, bool isChecked, int checkedLevel) { var checkContentLevel = siteInfo.Additional.CheckContentLevel; if (isChecked) { checkedLevel = checkContentLevel; } var listItem = new ListItem(Level.CaoGao, LevelInt.CaoGao.ToString()); listControl.Items.Add(listItem); listItem = new ListItem(Level.DaiShen, LevelInt.DaiShen.ToString()); listControl.Items.Add(listItem); if (checkContentLevel == 1) { listItem = new ListItem(Level1.Fail1, LevelInt.Fail1.ToString()) { Enabled = isChecked }; listControl.Items.Add(listItem); } else if (checkContentLevel == 2) { listItem = new ListItem(Level2.Fail1, LevelInt.Fail1.ToString()) { Enabled = checkedLevel >= 1 }; listControl.Items.Add(listItem); listItem = new ListItem(Level2.Fail2, LevelInt.Fail2.ToString()) { Enabled = isChecked }; listControl.Items.Add(listItem); } else if (checkContentLevel == 3) { listItem = new ListItem(Level3.Fail1, LevelInt.Fail1.ToString()) { Enabled = checkedLevel >= 1 }; listControl.Items.Add(listItem); listItem = new ListItem(Level3.Fail2, LevelInt.Fail2.ToString()) { Enabled = checkedLevel >= 2 }; listControl.Items.Add(listItem); listItem = new ListItem(Level3.Fail3, LevelInt.Fail3.ToString()) { Enabled = isChecked }; listControl.Items.Add(listItem); } else if (checkContentLevel == 4) { listItem = new ListItem(Level4.Fail1, LevelInt.Fail1.ToString()) { Enabled = checkedLevel >= 1 }; listControl.Items.Add(listItem); listItem = new ListItem(Level4.Fail2, LevelInt.Fail2.ToString()) { Enabled = checkedLevel >= 2 }; listControl.Items.Add(listItem); listItem = new ListItem(Level4.Fail3, LevelInt.Fail3.ToString()) { Enabled = checkedLevel >= 3 }; listControl.Items.Add(listItem); listItem = new ListItem(Level4.Fail4, LevelInt.Fail4.ToString()) { Enabled = isChecked }; listControl.Items.Add(listItem); } else if (checkContentLevel == 5) { listItem = new ListItem(Level5.Fail1, LevelInt.Fail1.ToString()) { Enabled = checkedLevel >= 1 }; listControl.Items.Add(listItem); listItem = new ListItem(Level5.Fail2, LevelInt.Fail2.ToString()) { Enabled = checkedLevel >= 2 }; listControl.Items.Add(listItem); listItem = new ListItem(Level5.Fail3, LevelInt.Fail3.ToString()) { Enabled = checkedLevel >= 3 }; listControl.Items.Add(listItem); listItem = new ListItem(Level5.Fail4, LevelInt.Fail4.ToString()) { Enabled = checkedLevel >= 4 }; listControl.Items.Add(listItem); listItem = new ListItem(Level5.Fail5, LevelInt.Fail5.ToString()) { Enabled = isChecked }; listControl.Items.Add(listItem); } if (checkContentLevel == 0 || checkContentLevel == 1) { listItem = new ListItem(Level1.Pass1, LevelInt.Pass1.ToString()) { Enabled = isChecked }; listControl.Items.Add(listItem); } else if (checkContentLevel == 2) { listItem = new ListItem(Level2.Pass1, LevelInt.Pass1.ToString()) { Enabled = checkedLevel >= 1 }; listControl.Items.Add(listItem); listItem = new ListItem(Level2.Pass2, LevelInt.Pass2.ToString()) { Enabled = isChecked }; listControl.Items.Add(listItem); } else if (checkContentLevel == 3) { listItem = new ListItem(Level3.Pass1, LevelInt.Pass1.ToString()) { Enabled = checkedLevel >= 1 }; listControl.Items.Add(listItem); listItem = new ListItem(Level3.Pass2, LevelInt.Pass2.ToString()) { Enabled = checkedLevel >= 2 }; listControl.Items.Add(listItem); listItem = new ListItem(Level3.Pass3, LevelInt.Pass3.ToString()) { Enabled = isChecked }; listControl.Items.Add(listItem); } else if (checkContentLevel == 4) { listItem = new ListItem(Level4.Pass1, LevelInt.Pass1.ToString()) { Enabled = checkedLevel >= 1 }; listControl.Items.Add(listItem); listItem = new ListItem(Level4.Pass2, LevelInt.Pass2.ToString()) { Enabled = checkedLevel >= 2 }; listControl.Items.Add(listItem); listItem = new ListItem(Level4.Pass3, LevelInt.Pass3.ToString()) { Enabled = checkedLevel >= 3 }; listControl.Items.Add(listItem); listItem = new ListItem(Level4.Pass4, LevelInt.Pass4.ToString()) { Enabled = isChecked }; listControl.Items.Add(listItem); } else if (checkContentLevel == 5) { listItem = new ListItem(Level5.Pass1, LevelInt.Pass1.ToString()) { Enabled = checkedLevel >= 1 }; listControl.Items.Add(listItem); listItem = new ListItem(Level5.Pass2, LevelInt.Pass2.ToString()) { Enabled = checkedLevel >= 2 }; listControl.Items.Add(listItem); listItem = new ListItem(Level5.Pass3, LevelInt.Pass3.ToString()) { Enabled = checkedLevel >= 3 }; listControl.Items.Add(listItem); listItem = new ListItem(Level5.Pass4, LevelInt.Pass4.ToString()) { Enabled = checkedLevel >= 4 }; listControl.Items.Add(listItem); listItem = new ListItem(Level5.Pass5, LevelInt.Pass5.ToString()) { Enabled = isChecked }; listControl.Items.Add(listItem); } ControlUtils.SelectSingleItem(listControl, checkedLevel.ToString()); }
public static void LoadContentLevelToList(ListControl listControl, SiteInfo siteInfo, bool isCheckOnly, bool isChecked, int checkedLevel) { var checkContentLevel = siteInfo.Additional.CheckContentLevel; if (isChecked) { checkedLevel = checkContentLevel; } listControl.Items.Add(new ListItem(Level.All, LevelInt.All.ToString())); listControl.Items.Add(new ListItem(Level.CaoGao, LevelInt.CaoGao.ToString())); listControl.Items.Add(new ListItem(Level.DaiShen, LevelInt.DaiShen.ToString())); if (checkContentLevel == 1) { if (isChecked) { listControl.Items.Add(new ListItem(Level1.Fail1, LevelInt.Fail1.ToString())); } } else if (checkContentLevel == 2) { if (checkedLevel >= 1) { listControl.Items.Add(new ListItem(Level2.Fail1, LevelInt.Fail1.ToString())); } if (isChecked) { listControl.Items.Add(new ListItem(Level2.Fail2, LevelInt.Fail2.ToString())); } } else if (checkContentLevel == 3) { if (checkedLevel >= 1) { listControl.Items.Add(new ListItem(Level3.Fail1, LevelInt.Fail1.ToString())); } if (checkedLevel >= 2) { listControl.Items.Add(new ListItem(Level3.Fail2, LevelInt.Fail2.ToString())); } if (isChecked) { listControl.Items.Add(new ListItem(Level3.Fail3, LevelInt.Fail3.ToString())); } } else if (checkContentLevel == 4) { if (checkedLevel >= 1) { listControl.Items.Add(new ListItem(Level4.Fail1, LevelInt.Fail1.ToString())); } if (checkedLevel >= 2) { listControl.Items.Add(new ListItem(Level4.Fail2, LevelInt.Fail2.ToString())); } if (checkedLevel >= 3) { listControl.Items.Add(new ListItem(Level4.Fail3, LevelInt.Fail3.ToString())); } if (isChecked) { listControl.Items.Add(new ListItem(Level4.Fail4, LevelInt.Fail4.ToString())); } } else if (checkContentLevel == 5) { if (checkedLevel >= 1) { listControl.Items.Add(new ListItem(Level5.Fail1, LevelInt.Fail1.ToString())); } if (checkedLevel >= 2) { listControl.Items.Add(new ListItem(Level5.Fail2, LevelInt.Fail2.ToString())); } if (checkedLevel >= 3) { listControl.Items.Add(new ListItem(Level5.Fail3, LevelInt.Fail3.ToString())); } if (checkedLevel >= 4) { listControl.Items.Add(new ListItem(Level5.Fail4, LevelInt.Fail4.ToString())); } if (isChecked) { listControl.Items.Add(new ListItem(Level5.Fail5, LevelInt.Fail5.ToString())); } } if (isCheckOnly) { return; } if (checkContentLevel == 1) { if (isChecked) { listControl.Items.Add(new ListItem(Level1.Pass1, LevelInt.Pass1.ToString())); } } if (checkContentLevel == 2) { if (checkedLevel >= 1) { listControl.Items.Add(new ListItem(Level2.Pass1, LevelInt.Pass1.ToString())); } if (isChecked) { listControl.Items.Add(new ListItem(Level2.Pass2, LevelInt.Pass2.ToString())); } } else if (checkContentLevel == 3) { if (checkedLevel >= 1) { listControl.Items.Add(new ListItem(Level3.Pass1, LevelInt.Pass1.ToString())); } if (checkedLevel >= 2) { listControl.Items.Add(new ListItem(Level3.Pass2, LevelInt.Pass2.ToString())); } if (isChecked) { listControl.Items.Add(new ListItem(Level3.Pass3, LevelInt.Pass3.ToString())); } } else if (checkContentLevel == 4) { if (checkedLevel >= 1) { listControl.Items.Add(new ListItem(Level4.Pass1, LevelInt.Pass1.ToString())); } if (checkedLevel >= 2) { listControl.Items.Add(new ListItem(Level4.Pass2, LevelInt.Pass2.ToString())); } if (checkedLevel >= 3) { listControl.Items.Add(new ListItem(Level4.Pass3, LevelInt.Pass3.ToString())); } if (isChecked) { listControl.Items.Add(new ListItem(Level4.Pass4, LevelInt.Pass4.ToString())); } } else if (checkContentLevel == 5) { if (checkedLevel >= 2) { listControl.Items.Add(new ListItem(Level5.Pass1, LevelInt.Pass1.ToString())); } if (checkedLevel >= 3) { listControl.Items.Add(new ListItem(Level5.Pass2, LevelInt.Pass2.ToString())); } if (checkedLevel >= 4) { listControl.Items.Add(new ListItem(Level5.Pass3, LevelInt.Pass3.ToString())); } if (checkedLevel >= 5) { listControl.Items.Add(new ListItem(Level5.Pass4, LevelInt.Pass4.ToString())); } if (isChecked) { listControl.Items.Add(new ListItem(Level5.Pass5, LevelInt.Pass5.ToString())); } } }
public static void LoadContentLevelToEdit(ListControl listControl, SiteInfo siteInfo, int channelId, ContentInfo contentInfo, bool isChecked, int checkedLevel) { var checkContentLevel = siteInfo.Additional.CheckContentLevel; if (isChecked) { checkedLevel = checkContentLevel; } ListItem listItem; var isCheckable = false; if (contentInfo != null) { isCheckable = IsCheckable(siteInfo, channelId, contentInfo.IsChecked, contentInfo.CheckedLevel, isChecked, checkedLevel); if (isCheckable) { listItem = new ListItem(Level.NotChange, LevelInt.NotChange.ToString()); listControl.Items.Add(listItem); } } listItem = new ListItem(Level.CaoGao, LevelInt.CaoGao.ToString()); listControl.Items.Add(listItem); listItem = new ListItem(Level.DaiShen, LevelInt.DaiShen.ToString()); listControl.Items.Add(listItem); if (checkContentLevel == 0 || checkContentLevel == 1) { listItem = new ListItem(Level1.Pass1, LevelInt.Pass1.ToString()) { Enabled = isChecked }; listControl.Items.Add(listItem); } else if (checkContentLevel == 2) { listItem = new ListItem(Level2.Pass1, LevelInt.Pass1.ToString()) { Enabled = checkedLevel >= 1 }; listControl.Items.Add(listItem); listItem = new ListItem(Level2.Pass2, LevelInt.Pass2.ToString()) { Enabled = isChecked }; listControl.Items.Add(listItem); } else if (checkContentLevel == 3) { listItem = new ListItem(Level3.Pass1, LevelInt.Pass1.ToString()) { Enabled = checkedLevel >= 1 }; listControl.Items.Add(listItem); listItem = new ListItem(Level3.Pass2, LevelInt.Pass2.ToString()) { Enabled = checkedLevel >= 2 }; listControl.Items.Add(listItem); listItem = new ListItem(Level3.Pass3, LevelInt.Pass3.ToString()) { Enabled = isChecked }; listControl.Items.Add(listItem); } else if (checkContentLevel == 4) { listItem = new ListItem(Level4.Pass1, LevelInt.Pass1.ToString()) { Enabled = checkedLevel >= 1 }; listControl.Items.Add(listItem); listItem = new ListItem(Level4.Pass2, LevelInt.Pass2.ToString()) { Enabled = checkedLevel >= 2 }; listControl.Items.Add(listItem); listItem = new ListItem(Level4.Pass3, LevelInt.Pass3.ToString()) { Enabled = checkedLevel >= 3 }; listControl.Items.Add(listItem); listItem = new ListItem(Level4.Pass4, LevelInt.Pass4.ToString()) { Enabled = isChecked }; listControl.Items.Add(listItem); } else if (checkContentLevel == 5) { listItem = new ListItem(Level5.Pass1, LevelInt.Pass1.ToString()) { Enabled = checkedLevel >= 1 }; listControl.Items.Add(listItem); listItem = new ListItem(Level5.Pass2, LevelInt.Pass2.ToString()) { Enabled = checkedLevel >= 2 }; listControl.Items.Add(listItem); listItem = new ListItem(Level5.Pass3, LevelInt.Pass3.ToString()) { Enabled = checkedLevel >= 3 }; listControl.Items.Add(listItem); listItem = new ListItem(Level5.Pass4, LevelInt.Pass4.ToString()) { Enabled = checkedLevel >= 4 }; listControl.Items.Add(listItem); listItem = new ListItem(Level5.Pass5, LevelInt.Pass5.ToString()) { Enabled = isChecked }; listControl.Items.Add(listItem); } if (contentInfo == null) { ControlUtils.SelectSingleItem(listControl, checkedLevel.ToString()); } else { ControlUtils.SelectSingleItem(listControl, isCheckable ? LevelInt.NotChange.ToString() : checkedLevel.ToString()); } }
public static string GetLevelName(int level, SiteInfo siteInfo) { var retval = string.Empty; if (level == CaoGao) { retval = "草稿"; } else if (level == DaiShen) { retval = "待审核"; } else if (level == Pass1) { retval = "初审通过"; } else if (level == Pass2) { retval = "二审通过"; } else if (level == Pass3) { retval = "三审通过"; } else if (level == Pass4) { retval = "四审通过"; } else if (level == Pass5) { retval = "终审通过"; } else if (level == Fail1) { retval = "初审退稿"; } else if (level == Fail2) { retval = "二审退稿"; } else if (level == Fail3) { retval = "三审退稿"; } else if (level == Fail4) { retval = "四审退稿"; } else if (level == Fail5) { retval = "终审退稿"; } else if (level == NotChange) { retval = "保持不变"; } if (siteInfo.Additional.IsCheckContentLevel) { if (siteInfo.Additional.CheckContentLevel <= level) { retval = "终审通过"; } } else { if (level > 1) { retval = "终审通过"; } } return(retval); }
public static KeyValuePair <bool, int> GetUserCheckLevel(PermissionManager permissionManager, SiteInfo siteInfo, int channelId) { if (permissionManager.IsSystemAdministrator) { return(new KeyValuePair <bool, int>(true, siteInfo.Additional.CheckContentLevel)); } var isChecked = false; var checkedLevel = 0; if (siteInfo.Additional.IsCheckContentLevel == false) { if (permissionManager.HasChannelPermissions(siteInfo.Id, channelId, ConfigManager.ChannelPermissions.ContentCheck)) { isChecked = true; } } else { if (permissionManager.HasChannelPermissions(siteInfo.Id, channelId, ConfigManager.ChannelPermissions.ContentCheckLevel5)) { isChecked = true; } else if (permissionManager.HasChannelPermissions(siteInfo.Id, channelId, ConfigManager.ChannelPermissions.ContentCheckLevel4)) { if (siteInfo.Additional.CheckContentLevel <= 4) { isChecked = true; } else { checkedLevel = 4; } } else if (permissionManager.HasChannelPermissions(siteInfo.Id, channelId, ConfigManager.ChannelPermissions.ContentCheckLevel3)) { if (siteInfo.Additional.CheckContentLevel <= 3) { isChecked = true; } else { checkedLevel = 3; } } else if (permissionManager.HasChannelPermissions(siteInfo.Id, channelId, ConfigManager.ChannelPermissions.ContentCheckLevel2)) { if (siteInfo.Additional.CheckContentLevel <= 2) { isChecked = true; } else { checkedLevel = 2; } } else if (permissionManager.HasChannelPermissions(siteInfo.Id, channelId, ConfigManager.ChannelPermissions.ContentCheckLevel1)) { if (siteInfo.Additional.CheckContentLevel <= 1) { isChecked = true; } else { checkedLevel = 1; } } else { checkedLevel = 0; } } return(new KeyValuePair <bool, int>(isChecked, checkedLevel)); }
/// <summary> /// Handles the UniGrid's OnAction event. /// </summary> /// <param name="actionName">Name of item (button) that throws event</param> /// <param name="actionArgument">ID (value of Primary key) of corresponding data row</param> protected void Control_OnAction(string actionName, object actionArgument) { SiteInfo si = SiteInfoProvider.GetSiteInfo(ValidationHelper.GetInteger(actionArgument, 0)); if (si != null) { string siteName = si.SiteName; switch (actionName) { case "delete": URLHelper.Redirect("~/CMSModules/Sites/Pages/site_delete.aspx?siteid=" + actionArgument); break; case "editContent": { // Build URL for site in format 'http(s)://sitedomain/application/admin' string sitedomain = si.DomainName.TrimEnd('/'); string application = null; // Support of multiple web sites on single domain if (!sitedomain.Contains("/")) { application = UrlResolver.ResolveUrl("~/.").TrimEnd('/'); } // Application includes string '/admin'. application += "/admin/"; string url = RequestContext.CurrentScheme + "://" + sitedomain + application; ScriptHelper.RegisterStartupScript(Control.Page, typeof(string), "EditContentScript", ScriptHelper.GetScript("window.open('" + url + "');")); } break; case "openLiveSite": { string url; if (si.SiteIsContentOnly) { // Site is ContentOnly -> just redirect to sites's presentation URL url = si.SitePresentationURL; } else { // Make url for site in form 'http(s)://sitedomain/application'. string sitedomain = si.DomainName.TrimEnd('/'); string application = null; // Support of multiple web sites on single domain if (!sitedomain.Contains("/")) { application = UrlResolver.ResolveUrl("~/.").TrimEnd('/'); } url = RequestContext.CurrentScheme + "://" + sitedomain + application + "/"; } ScriptHelper.RegisterStartupScript(Control.Page, typeof(string), "OpenLiveSiteScript", ScriptHelper.GetScript("window.open('" + url + "');")); } break; case "start": try { SiteInfoProvider.RunSite(siteName); } catch (Exception ex) { Control.ShowError(ResHelper.GetString("Site_List.ErrorMsg"), ex.Message, null); } break; case "stop": SiteInfoProvider.StopSite(siteName); SessionManager.Clear(siteName); break; case "export": URLHelper.Redirect(URLHelper.AppendQuery(UIContextHelper.GetElementUrl(ModuleName.CMS, "Export", false), "siteID=" + actionArgument)); break; } } }
/// <summary> /// Apply control settings. /// </summary> public bool ApplySettings() { // Set additional settings Settings.ExistingSite = !radNewSite.Checked; Settings.SetSettings(ImportExportHelper.SETTINGS_BIZFORM_DATA, radNewSite.Checked); Settings.SetSettings(ImportExportHelper.SETTINGS_FORUM_POSTS, radNewSite.Checked); Settings.SetSettings(ImportExportHelper.SETTINGS_BOARD_MESSAGES, radNewSite.Checked); Settings.SetSettings(ImportExportHelper.SETTINGS_USER_DASHBOARDS, radNewSite.Checked); Settings.SetSettings(ImportExportHelper.SETTINGS_USER_SITE_DASHBOARDS, radNewSite.Checked); Settings.SetSettings(ImportExportHelper.SETTINGS_PAGETEMPLATE_SCOPES, radNewSite.Checked); Settings.SetSettings(ImportExportHelper.SETTINGS_PAGETEMPLATE_VARIANTS, radNewSite.Checked); Settings.SetSettings(ImportExportHelper.SETTINGS_CUSTOMTABLE_DATA, radNewSite.Checked); Settings.SetSettings(ImportExportHelper.SETTINGS_WORKFLOW_SCOPES, radNewSite.Checked); Settings.SetSettings(ImportExportHelper.SETTINGS_WORKFLOW_TRIGGERS, radNewSite.Checked); Settings.SetSettings(ImportExportHelper.SETTINGS_MEDIA_FILES, radNewSite.Checked); Settings.SetSettings(ImportExportHelper.SETTINGS_MEDIA_FILES_PHYSICAL, radNewSite.Checked); if (!radNewSite.Checked) { Settings.SiteId = ValidationHelper.GetInteger(siteSelector.Value, 0); // Get site info SiteInfo si = SiteInfoProvider.GetSiteInfo(Settings.SiteId); if (si != null) { Settings.SiteDisplayName = si.DisplayName; Settings.SiteDomain = si.DomainName; Settings.SiteName = si.SiteName; } return(true); } Settings.SiteId = 0; // Existing site bool isValid = rfvSiteDisplayName.IsValid && rfvDomain.IsValid; // Get site name var siteName = txtSiteName.Text.Trim(); if (siteName != InfoHelper.CODENAME_AUTOMATIC) { var validator = new Validator().NotEmpty(siteName, GetString("ImportSite.StepSiteDetails.SiteNameError")) .IsCodeName(siteName, GetString("ImportSite.StepSiteDetails.SiteNameNotValid")); // Get validation result string codeNameError = validator.Result; // Check if there is site with specified code name if (string.IsNullOrEmpty(codeNameError) && SiteInfoProvider.GetSiteInfo(siteName) != null) { codeNameError = GetString("NewSite_SiteDetails.ErrorSiteExists"); } if (!string.IsNullOrEmpty(codeNameError)) { lblErrorSiteName.Text = codeNameError; lblErrorSiteName.Visible = true; isValid = false; } } if (isValid) { txtDomain.Text = URLHelper.RemoveProtocol(txtDomain.Text); // Set site details Settings.SiteDisplayName = txtSiteDisplayName.Text; Settings.SiteDomain = txtDomain.Text; Settings.SiteName = siteName; } return(isValid); }
/// <summary> /// External data binding handler. /// </summary> protected object gridDocuments_OnExternalDataBound(object sender, string sourceName, object parameter) { int currentNodeId; sourceName = sourceName.ToLowerCSafe(); switch (sourceName) { case "view": { // Dialog view item DataRowView data = ((DataRowView)((GridViewRow)parameter).DataItem); CMSGridActionButton btn = ((CMSGridActionButton)sender); // Current row is the Root document isRootDocument = (ValidationHelper.GetInteger(data["NodeParentID"], 0) == 0); isCurrentDocument = (ValidationHelper.GetInteger(data["NodeID"], 0) == WOpenerNodeID); string culture = ValidationHelper.GetString(data["DocumentCulture"], string.Empty); // Existing document culture if (culture.ToLowerCSafe() == CultureCode.ToLowerCSafe()) { string url = ResolveUrl(!isRootDocument ? DocumentURLProvider.GetUrl(Convert.ToString(data["NodeAliasPath"])) : "~/"); btn.OnClientClick = "ViewItem(" + ScriptHelper.GetString(url) + "); return false;"; } // New culture version else { currentNodeId = ValidationHelper.GetInteger(data["NodeID"], 0); btn.OnClientClick = "wopener.NewDocumentCulture(" + currentNodeId + ", '" + CultureCode + "'); CloseDialog(); return false;"; } } break; case "edit": { CMSGridActionButton btn = ((CMSGridActionButton)sender); if (IsEditVisible) { DataRowView data = ((DataRowView)((GridViewRow)parameter).DataItem); string culture = ValidationHelper.GetString(data["DocumentCulture"], string.Empty); currentNodeId = ValidationHelper.GetInteger(data["NodeID"], 0); int nodeParentId = ValidationHelper.GetInteger(data["NodeParentID"], 0); if (!RequiresDialog || (culture.ToLowerCSafe() == CultureCode.ToLowerCSafe())) { // Go to the selected document or create a new culture version when not used in a dialog btn.OnClientClick = "EditItem(" + currentNodeId + ", " + nodeParentId + "); return false;"; } else { // New culture version in a dialog btn.OnClientClick = "wopener.NewDocumentCulture(" + currentNodeId + ", '" + CultureCode + "'); CloseDialog(); return false;"; } } else { btn.Visible = false; } } break; case "delete": { // Delete button CMSGridActionButton btn = ((CMSGridActionButton)sender); // Hide the delete button for the root document btn.Visible = !isRootDocument; } break; case "contextmenu": { // Dialog context menu item CMSGridActionButton btn = ((CMSGridActionButton)sender); // Hide the context menu for the root document btn.Visible = !isRootDocument && !ShowAllLevels; } break; case "published": { // Published state return(UniGridFunctions.ColoredSpanYesNo(parameter)); } case "versionnumber": { // Version number if (parameter == DBNull.Value) { parameter = "-"; } parameter = HTMLHelper.HTMLEncode(parameter.ToString()); return(parameter); } case "documentname": { // Document name DataRowView data = (DataRowView)parameter; string className = ValidationHelper.GetString(data["ClassName"], string.Empty); string classDisplayName = ValidationHelper.GetString(data["classdisplayname"], null); string name = ValidationHelper.GetString(data["DocumentName"], string.Empty); string culture = ValidationHelper.GetString(data["DocumentCulture"], string.Empty); string cultureString = null; currentNodeId = ValidationHelper.GetInteger(data["NodeID"], 0); int nodeParentId = ValidationHelper.GetInteger(data["NodeParentID"], 0); if (isRootDocument) { // User site name for the root document name = SiteContext.CurrentSiteName; } // Default culture if (culture.ToLowerCSafe() != CultureCode.ToLowerCSafe()) { cultureString = " (" + culture + ")"; } StringBuilder sb = new StringBuilder(); if (ShowDocumentTypeIcon) { // Prepare tooltip for document type icon string iconTooltip = ""; if (ShowDocumentTypeIconTooltip && (classDisplayName != null)) { iconTooltip = string.Format("onmouseout=\"UnTip()\" onmouseover=\"Tip('{0}')\"", HTMLHelper.HTMLEncode(ResHelper.LocalizeString(classDisplayName))); } if (className.EqualsCSafe("cms.file", true)) { string extension = ValidationHelper.GetString(data["DocumentType"], string.Empty); sb.Append(UIHelper.GetFileIcon(Page, extension, additionalAttributes: iconTooltip)); } // Use class icons else { var dataClass = DataClassInfoProvider.GetDataClassInfo(className); if (dataClass != null) { var iconClass = (string)dataClass.GetValue("ClassIconClass"); sb.Append(UIHelper.GetDocumentTypeIcon(Page, className, iconClass, additionalAttributes: iconTooltip)); } } } string safeName = HTMLHelper.HTMLEncode(TextHelper.LimitLength(name, 50)); if (DocumentNameAsLink && !isRootDocument) { string tooltip = UniGridFunctions.DocumentNameTooltip(data); string selectFunction = SelectItemJSFunction + "(" + currentNodeId + ", " + nodeParentId + ");"; sb.Append("<a href=\"javascript: ", selectFunction, "\""); // Ensure onclick action on mobile devices. This is necessary due to Tip/UnTip functions. They block default click behavior on mobile devices. if (DeviceContext.CurrentDevice.IsMobile) { sb.Append(" ontouchend=\"", selectFunction, "\""); } sb.Append(" onmouseout=\"UnTip()\" onmouseover=\"Tip('", tooltip, "')\">", safeName, cultureString, "</a>"); } else { sb.Append(safeName, cultureString); } // Show document marks only if method is not called from grid export and document marks are allowed if ((sender != null) && ShowDocumentMarks) { // Prepare parameters int workflowStepId = ValidationHelper.GetInteger(DataHelper.GetDataRowViewValue(data, "DocumentWorkflowStepID"), 0); WorkflowStepTypeEnum stepType = WorkflowStepTypeEnum.Undefined; if (workflowStepId > 0) { WorkflowStepInfo stepInfo = WorkflowStepInfoProvider.GetWorkflowStepInfo(workflowStepId); if (stepInfo != null) { stepType = stepInfo.StepType; } } // Create data container IDataContainer container = new DataRowContainer(data); // Add icons and use current culture of processed node because of 'Not translated document' icon sb.Append(" ", DocumentHelper.GetDocumentMarks(Page, currentSiteName, ValidationHelper.GetString(container.GetValue("DocumentCulture"), string.Empty), stepType, container)); } return(sb.ToString()); } case "documentculture": { DocumentFlagsControl ucDocFlags = null; if (OnDocumentFlagsCreating != null) { // Raise event for obtaining custom DocumentFlagControl object result = OnDocumentFlagsCreating(this, sourceName, parameter); ucDocFlags = result as DocumentFlagsControl; // Check if something other than DocumentFlagControl was returned if ((ucDocFlags == null) && (result != null)) { return(result); } } // Dynamically load document flags control when not created if (ucDocFlags == null) { ucDocFlags = LoadUserControl("~/CMSAdminControls/UI/DocumentFlags.ascx") as DocumentFlagsControl; } // Set document flags properties if (ucDocFlags != null) { DataRowView data = (DataRowView)parameter; // Get node ID currentNodeId = ValidationHelper.GetInteger(data["NodeID"], 0); if (!string.IsNullOrEmpty(SelectLanguageJSFunction)) { ucDocFlags.SelectJSFunction = SelectLanguageJSFunction; } ucDocFlags.ID = "docFlags" + currentNodeId; ucDocFlags.SiteCultures = SiteCultures; ucDocFlags.NodeID = currentNodeId; ucDocFlags.StopProcessing = true; ucDocFlags.ItemUrl = ResolveUrl(DocumentURLProvider.GetUrl(Convert.ToString(data["NodeAliasPath"]))); // Keep the control for later usage FlagsControls.Add(ucDocFlags); return(ucDocFlags); } } break; case "modifiedwhen": case "modifiedwhentooltip": // Modified when if (string.IsNullOrEmpty(parameter.ToString())) { return(string.Empty); } else { DateTime modifiedWhen = ValidationHelper.GetDateTime(parameter, DateTimeHelper.ZERO_TIME); currentUserInfo = currentUserInfo ?? MembershipContext.AuthenticatedUser; currentSiteInfo = currentSiteInfo ?? SiteContext.CurrentSite; if (sourceName.EqualsCSafe("modifiedwhen", StringComparison.InvariantCultureIgnoreCase)) { return(TimeZoneHelper.ConvertToUserTimeZone(modifiedWhen, true, currentUserInfo, currentSiteInfo)); } else { return(TimeZoneHelper.GetUTCLongStringOffset(currentUserInfo, currentSiteInfo)); } } case "classdisplayname": case "classdisplaynametooltip": // Localize class display name if (!string.IsNullOrEmpty(parameter.ToString())) { return(HTMLHelper.HTMLEncode(ResHelper.LocalizeString(parameter.ToString()))); } return(string.Empty); default: if (OnExternalAdditionalDataBound != null) { return(OnExternalAdditionalDataBound(sender, sourceName, parameter)); } break; } return(parameter); }
public static bool IsEdit(SiteInfo siteInfo, int channelId, PermissionsImpl permissionsImpl) { return(permissionsImpl.HasChannelPermissions(siteInfo.Id, channelId, ConfigManager.ChannelPermissions.ContentEdit)); }
public static void LoadSiteIdDropDownList(DropDownList siteIdDropDownList, SiteInfo siteInfo, int channelId) { siteIdDropDownList.Items.Clear(); var channelInfo = ChannelManager.GetChannelInfo(siteInfo.Id, channelId); if (channelInfo.Additional.TransType == ECrossSiteTransType.SelfSite || channelInfo.Additional.TransType == ECrossSiteTransType.SpecifiedSite || channelInfo.Additional.TransType == ECrossSiteTransType.ParentSite) { int theSiteId; if (channelInfo.Additional.TransType == ECrossSiteTransType.SelfSite) { theSiteId = siteInfo.Id; } else if (channelInfo.Additional.TransType == ECrossSiteTransType.SpecifiedSite) { theSiteId = channelInfo.Additional.TransSiteId; } else { theSiteId = SiteManager.GetParentSiteId(siteInfo.Id); } if (theSiteId > 0) { var theSiteInfo = SiteManager.GetSiteInfo(theSiteId); if (theSiteInfo != null) { var listitem = new ListItem(theSiteInfo.SiteName, theSiteInfo.Id.ToString()); siteIdDropDownList.Items.Add(listitem); } } } else if (channelInfo.Additional.TransType == ECrossSiteTransType.AllParentSite) { var siteIdList = SiteManager.GetSiteIdList(); var allParentSiteIdList = new List <int>(); SiteManager.GetAllParentSiteIdList(allParentSiteIdList, siteIdList, siteInfo.Id); foreach (var psId in siteIdList) { if (psId == siteInfo.Id) { continue; } var psInfo = SiteManager.GetSiteInfo(psId); var show = psInfo.IsRoot || allParentSiteIdList.Contains(psInfo.Id); if (show) { var listitem = new ListItem(psInfo.SiteName, psId.ToString()); if (psInfo.IsRoot) { listitem.Selected = true; } siteIdDropDownList.Items.Add(listitem); } } } else if (channelInfo.Additional.TransType == ECrossSiteTransType.AllSite) { var siteIdList = SiteManager.GetSiteIdList(); foreach (var psId in siteIdList) { var psInfo = SiteManager.GetSiteInfo(psId); var listitem = new ListItem(psInfo.SiteName, psId.ToString()); if (psInfo.IsRoot) { listitem.Selected = true; } siteIdDropDownList.Items.Add(listitem); } } }
/// <summary> /// Grid external data bound handler. /// </summary> protected object gridFiles_OnExternalDataBound(object sender, string sourceName, object parameter) { // Get the data row view from parameter DataRowView drv = null; if (parameter is DataRowView) { drv = (DataRowView)parameter; } else if (parameter is GridViewRow) { // Get data from the grid view row GridViewRow gvr = (parameter as GridViewRow); if (gvr != null) { drv = (DataRowView)gvr.DataItem; } } // Get the action button CMSGridActionButton btn = null; if (sender is CMSGridActionButton) { btn = (CMSGridActionButton)sender; } switch (sourceName) { case "delete": { // Delete action int siteId = ValidationHelper.GetInteger(drv["MetaFileSiteID"], 0); string siteName = GetSiteName(siteId); Guid guid = ValidationHelper.GetGuid(drv["MetaFileGUID"], Guid.Empty); string extension = ValidationHelper.GetString(drv["MetaFileExtension"], ""); // Check if the file is in DB bool db = ValidationHelper.GetBoolean(drv["HasBinary"], false); // Check if the file is in the file system bool fs = false; string path = MetaFileInfoProvider.GetFilePhysicalPath(siteName, guid.ToString(), extension); if (File.Exists(path)) { fs = true; } // If the file is present in both file system and database, delete is allowed if (fs && db) { // If the files are stored in file system, delete is allowed in database if (StoreInFileSystem(siteId)) { btn.OnClientClick = btn.OnClientClick.Replace("'delete'", "'deleteindatabase'"); btn.ToolTip = "Delete from database"; return(parameter); } // If the files are stored in database, delete is allowed in file system if (StoreInDatabase(siteId)) { btn.OnClientClick = btn.OnClientClick.Replace("'delete'", "'deleteinfilesystem'"); btn.ToolTip = "Delete from file system"; return(parameter); } } btn.Visible = false; } break; case "copy": { // Delete action int siteId = ValidationHelper.GetInteger(drv["MetaFileSiteID"], 0); string siteName = GetSiteName(siteId); Guid guid = ValidationHelper.GetGuid(drv["MetaFileGUID"], Guid.Empty); string extension = ValidationHelper.GetString(drv["MetaFileExtension"], ""); // Check if the file is in DB bool db = ValidationHelper.GetBoolean(drv["HasBinary"], false); // Check if the file is in the file system bool fs = false; string path = MetaFileInfoProvider.GetFilePhysicalPath(siteName, guid.ToString(), extension); if (File.Exists(path)) { fs = true; } // If the file is stored in file system and the file is not present in database, copy to database is allowed if (fs && !db && StoreInDatabase(siteId) && StoreInFileSystem(siteId)) { btn.OnClientClick = btn.OnClientClick.Replace("'copy'", "'copytodatabase'"); btn.ToolTip = "Copy to database"; //btn.ImageUrl = return(parameter); } // If the file is stored in database and the file is not present in file system, copy to file system is allowed if (db && !fs && StoreInFileSystem(siteId)) { btn.OnClientClick = btn.OnClientClick.Replace("'copy'", "'copytofilesystem'"); btn.ToolTip = "Copy to file system"; return(parameter); } btn.Visible = false; } break; case "name": { // MetaFile name string name = ValidationHelper.GetString(drv["MetaFileName"], ""); Guid guid = ValidationHelper.GetGuid(drv["MetaFileGUID"], Guid.Empty); int siteId = ValidationHelper.GetInteger(drv["MetaFileSiteID"], 0); string extension = ValidationHelper.GetString(drv["MetaFileExtension"], ""); // File name name = Path.GetFileNameWithoutExtension(name); string url = ResolveUrl("~/CMSPages/GetMetaFile.aspx?fileguid=") + guid; if (siteId != currentSiteId) { // Add the site name to the URL if not current site SiteInfo si = SiteInfoProvider.GetSiteInfo(siteId); if (si != null) { url += "&sitename=" + si.SiteName; } } string tooltipSpan = name; bool isImage = ImageHelper.IsImage(extension); if (isImage) { int imageWidth = ValidationHelper.GetInteger(DataHelper.GetDataRowViewValue(drv, "MetaFileImageWidth"), 0); int imageHeight = ValidationHelper.GetInteger(DataHelper.GetDataRowViewValue(drv, "MetaFileImageHeight"), 0); string tooltip = UIHelper.GetTooltipAttributes(url, imageWidth, imageHeight, null, name, extension, null, null, 300); tooltipSpan = "<span id=\"" + guid + "\" " + tooltip + ">" + name + "</span>"; } return(UIHelper.GetFileIcon(Page, extension, tooltip: name) + " <a href=\"" + url + "\" target=\"_blank\">" + tooltipSpan + "</a>"); } case "size": // File size return(DataHelper.GetSizeString(ValidationHelper.GetInteger(parameter, 0))); case "yesno": // Yes / No return(UniGridFunctions.ColoredSpanYesNo(parameter)); case "site": { int siteId = ValidationHelper.GetInteger(parameter, 0); if (siteId > 0) { SiteInfo si = SiteInfoProvider.GetSiteInfo(siteId); if (si != null) { return(si.DisplayName); } } return(null); } case "storedinfilesystem": { // Delete action int siteId = ValidationHelper.GetInteger(drv["MetaFileSiteID"], 0); string siteName = GetSiteName(siteId); Guid guid = ValidationHelper.GetGuid(drv["MetaFileGUID"], Guid.Empty); string extension = ValidationHelper.GetString(drv["MetaFileExtension"], ""); // Check if the file is in DB bool db = ValidationHelper.GetBoolean(drv["HasBinary"], false); // Check if the file is in the file system bool fs = false; string path = MetaFileInfoProvider.GetFilePhysicalPath(siteName, guid.ToString(), extension); if (File.Exists(path)) { fs = true; } return(UniGridFunctions.ColoredSpanYesNo(fs)); } } return(parameter); }
public bool Delete(SiteInfo item) { return(crawled.Delete(item?.DatabaseId)); }
/// <summary> /// External data binding handler. /// </summary> protected object gridElem_OnExternalDataBound(object sender, string sourceName, object parameter) { // Prepare variables int nodeId = 0; string culture = string.Empty; DataRowView data = null; sourceName = sourceName.ToLower(); SiteInfo site = null; switch (sourceName) { // Edit button case EXTERNALSOURCE_EDIT: if (sender is ImageButton) { ImageButton editButton = (ImageButton)sender; data = UniGridFunctions.GetDataRowView(editButton.Parent as DataControlFieldCell); site = GetSiteFromRow(data); nodeId = ValidationHelper.GetInteger(data[SOURCE_NODEID], 0); culture = ValidationHelper.GetString(data[SOURCE_DOCUMENTCULTURE], string.Empty); string type = ValidationHelper.GetString(DataHelper.GetDataRowViewValue(data, SOURCE_TYPE), string.Empty); // Check permissions if ((site.Status != SiteStatusEnum.Running) || (!CMSMyDeskPage.IsUserAuthorizedPerContent(site.SiteName) || ((ListingType == ListingTypeEnum.All) && (type == LISTINGTYPE_RECYCLEBIN)))) { editButton.ImageUrl = GetImageUrl("Design/Controls/UniGrid/Actions/Editdisabled.png"); editButton.OnClientClick = "return false"; editButton.Style.Add(HtmlTextWriterStyle.Cursor, "default"); } else { editButton.OnClientClick = "return SelectItem(" + nodeId + ", '" + culture + "','" + ResolveSiteUrl(site) + "');"; } return editButton; } return sender; // Preview button case EXTERNALSOURCE_PREVIEW: if (sender is ImageButton) { ImageButton previewButton = (ImageButton)sender; data = UniGridFunctions.GetDataRowView(previewButton.Parent as DataControlFieldCell); site = GetSiteFromRow(data); string type = ValidationHelper.GetString(DataHelper.GetDataRowViewValue(data, SOURCE_TYPE), string.Empty); if ((site.Status != SiteStatusEnum.Running) || ((ListingType == ListingTypeEnum.All) && (type == LISTINGTYPE_RECYCLEBIN))) { previewButton.ImageUrl = GetImageUrl("Design/Controls/UniGrid/Actions/Viewdisabled.png"); previewButton.OnClientClick = "return false"; previewButton.Style.Add(HtmlTextWriterStyle.Cursor, "default"); } else { nodeId = ValidationHelper.GetInteger(data[SOURCE_NODEID], 0); culture = ValidationHelper.GetString(data[SOURCE_DOCUMENTCULTURE], string.Empty); string nodeAliasPath = ValidationHelper.GetString(data[SOURCE_NODEALIASPATH], string.Empty); // Generate preview URL string url = CMSContext.GetUrl(nodeAliasPath, null, site.SiteName); url = URLHelper.AddParameterToUrl(url, "viewmode", "2"); url = URLHelper.AddParameterToUrl(url, URLHelper.LanguageParameterName, culture); previewButton.OnClientClick = "window.open('" + URLHelper.ResolveUrl(url) + "','LiveSite');return false;"; } return previewButton; } return sender; // Document name column case EXTERNALSOURCE_DOCUMENTNAME: data = (DataRowView)parameter; string name = ValidationHelper.GetString(data[SOURCE_DOCUMENTNAME], string.Empty); nodeId = ValidationHelper.GetInteger(data[SOURCE_NODEID], 0); culture = ValidationHelper.GetString(data[SOURCE_DOCUMENTCULTURE], string.Empty); string className = ValidationHelper.GetString(data[SOURCE_CLASSNAME], string.Empty); site = GetSiteFromRow(data); if (name == string.Empty) { name = GetString("general.notspecified"); } // Add document type icon string result = string.Empty; switch (ListingType) { case ListingTypeEnum.DocTypeDocuments: break; default: result = "<img src=\"" + UIHelper.GetDocumentTypeIconUrl(Parent.Page, className, String.Empty, true) + "\" class=\"UnigridActionButton\" />"; break; } result += "<span style=\"vertical-align: bottom;\">" + HTMLHelper.HTMLEncode(TextHelper.LimitLength(name, 50)) + "</span>"; if (ListingType != ListingTypeEnum.All) { bool isLink = (data.Row.Table.Columns.Contains(SOURCE_NODELINKEDNODEID) && (data[SOURCE_NODELINKEDNODEID] != DBNull.Value)); if (isLink) { // Add link icon result += UIHelper.GetDocumentMarkImage(Parent.Page, DocumentMarkEnum.Link); } } return result; // Class name column case EXTERNALSOURCE_CLASSDISPLAYNAME: string displayName = ValidationHelper.GetString(parameter, string.Empty); if (sourceName.ToLower() == EXTERNALSOURCE_CLASSDISPLAYNAMETOOLTIP) { displayName = TextHelper.LimitLength(displayName, 50); } if (displayName == string.Empty) { displayName = "-"; } return HTMLHelper.HTMLEncode(displayName); case EXTERNALSOURCE_DOCUMENTNAMETOOLTIP: data = (DataRowView)parameter; return UniGridFunctions.DocumentNameTooltip(data); case EXTERNALSOURCE_STEPDISPLAYNAME: // Step display name string stepName = ValidationHelper.GetString(parameter, string.Empty); if (stepName == string.Empty) { stepName = "-"; } return HTMLHelper.HTMLEncode(ResHelper.LocalizeString(stepName)); case EXTERNALSOURCE_STEPNAME: // Step display name from ID int stepId = ValidationHelper.GetInteger(parameter, 0); if (stepId > 0) { WorkflowStepInfo wsi = WorkflowStepInfoProvider.GetWorkflowStepInfo(stepId); if (wsi != null) { return HTMLHelper.HTMLEncode(ResHelper.LocalizeString(wsi.StepDisplayName)); } } return "-"; case EXTERNALSOURCE_CULTURE: data = (DataRowView)parameter; culture = ValidationHelper.GetString(data[SOURCE_DOCUMENTCULTURE], string.Empty); // Add icon if (culture != String.Empty) { return UniGridFunctions.DocumentCultureFlag(data, Page); } return "-"; // Version column case EXTERNALSOURCE_VERSION: if (parameter == DBNull.Value) { parameter = "-"; } parameter = HTMLHelper.HTMLEncode(parameter.ToString()); return parameter; // Site name column case EXTERNALSOURCE_SITENAME: string siteName = ValidationHelper.GetString(parameter, string.Empty); siteInfo = SiteInfoProvider.GetSiteInfo(siteName); return HTMLHelper.HTMLEncode(siteInfo.DisplayName); case EXTERNALSOURCE_SITEID: int siteId = ValidationHelper.GetInteger(parameter, 0); siteInfo = SiteInfoProvider.GetSiteInfo(siteId); return HTMLHelper.HTMLEncode(siteInfo.DisplayName); // Document timestamp column case EXTERNALSOURCE_MODIFIEDWHEN: case EXTERNALSOURCE_MODIFIEDWHENTOOLTIP: if (string.IsNullOrEmpty(parameter.ToString())) { return string.Empty; } else { if (currentSiteInfo == null) { currentSiteInfo = CMSContext.CurrentSite; } bool displayGMT = (sourceName == EXTERNALSOURCE_MODIFIEDWHENTOOLTIP); DateTime time = ValidationHelper.GetDateTime(parameter, DateTimeHelper.ZERO_TIME); return TimeZoneHelper.ConvertToUserTimeZone(time, displayGMT, currentUserInfo, currentSiteInfo); } } return parameter; }
private static HtmlBuilder NavigationMenu( this HtmlBuilder hb, Context context, SiteSettings ss, long siteId, string referenceType, bool useNavigationMenu) { var canManageGroups = context.UserSettings?.DisableGroupAdmin != true; var canManageSite = siteId != 0 && context.CanManageSite(ss: ss, site: true); var canManageDepts = Permissions.CanManageTenant(context: context); var canManageUsers = Permissions.CanManageTenant(context: context); var canManageTrashBox = CanManageTrashBox(context: context, ss: ss); return(hb.Ul( id: "NavigationMenu", action: () => hb .Li( action: () => hb .Div(action: () => hb .A( href: NewHref(context: context, ss: ss), attributes: SiteIndex(context: context, ss: ss) ? new HtmlAttributes() .OnClick("$p.templates($(this));") .DataAction("Templates") .DataMethod("post") : null, action: () => hb .Span(css: "ui-icon ui-icon-plus") .Text(text: Displays.New(context: context)))), _using: ss.ReferenceType == "Sites" && context.Action == "index" ? context.CanManageSite(ss: ss) : context.CanCreate(ss: ss) && ss.ReferenceType != "Wikis" && context.Action != "trashbox") .Li( css: "sub-menu", action: () => hb .Div( attributes: new HtmlAttributes().DataId("ViewModeMenu"), action: () => hb .Span(css: "ui-icon ui-icon-triangle-1-e") .Text(text: Displays.View(context: context))) .ViewModeMenu(context: context, ss: ss), _using: Def.ViewModeDefinitionCollection .Any(o => o.ReferenceType == referenceType)) .Li( css: "sub-menu", action: () => hb .Div( attributes: new HtmlAttributes().DataId("SettingsMenu"), action: () => hb .Span(css: "ui-icon ui-icon-gear") .Text(text: Displays.Manage(context: context))) .SettingsMenu( context: context, ss: ss, siteId: siteId, canManageSite: canManageSite, canManageDepts: canManageDepts, canManageGroups: canManageGroups, canManageUsers: canManageUsers, canManageTrashBox: canManageTrashBox), _using: canManageSite || canManageDepts || canManageGroups || canManageUsers) .Li( css: "sub-menu", action: () => hb .Div( attributes: new HtmlAttributes().DataId("AccountMenu"), action: () => hb .Span(css: "ui-icon ui-icon-person") .Text(text: SiteInfo.UserName( context: context, userId: context.UserId))) .AccountMenu(context: context)))); }
/// <summary> /// Make URL for site in form 'http(s)://sitedomain/application/admin'. /// </summary> /// <param name="site">Site info object</param> private string ResolveSiteUrl(SiteInfo site) { string sitedomain = site.DomainName.TrimEnd('/'); string application = null; // Support of multiple web sites on single domain if (!sitedomain.Contains("/")) { application = ResolveUrl("~/.").TrimEnd('/'); } // Application includes string '/admin'. application += "/Admin/CMSAdministration.aspx"; return RequestContext.CurrentScheme + "://" + sitedomain + application; }
public virtual void UpdateSite(StatsSite site) { // update site SiteAdmin stAdmin = new SiteAdmin(); PrepareProxy(stAdmin); int siteId = Int32.Parse(site.SiteId); // get original site SiteInfoResult siteResult = stAdmin.GetSite(Username, Password, siteId); if (siteResult.Site == null) { return; } SiteInfo origSite = siteResult.Site; // update site with only required properties GenericResult1 result = stAdmin.UpdateSite(Username, Password, siteId, site.Name, origSite.LogDirectory, origSite.LogFormat, origSite.LogWildcard, origSite.LogDaysBeforeDelete, origSite.SmarterLogDirectory, origSite.SmarterLogMonthsBeforeDelete, origSite.ExportPath, origSite.ExportPathURL, origSite.TimeZoneID); if (!result.Result) { throw new Exception("Error updating statistics site: " + result.Message); } // update site users UserAdmin usrAdmin = new UserAdmin(); PrepareProxy(usrAdmin); // get original users if (site.Users != null) { List <string> origUsers = new List <string>(); List <string> newUsers = new List <string>(); string ownerUsername = null; UserInfoResultArray usrResult = usrAdmin.GetUsers(Username, Password, siteId); foreach (UserInfo user in usrResult.user) { // add to original users origUsers.Add(user.UserName.ToLower()); // remember owner (he can't be deleted) if (user.IsSiteOwner) { ownerUsername = user.UserName.ToLower(); } } // add, update users foreach (StatsUser user in site.Users) { if (!origUsers.Contains(user.Username.ToLower())) { // add user GenericResult2 r = usrAdmin.AddUser(Username, Password, siteId, user.Username, user.Password, user.FirstName, user.LastName, user.IsAdmin); if (!r.Result) { throw new Exception("Error adding site user: "******"Error updating site user: " + r.Message); } } // add to new users list newUsers.Add(user.Username.ToLower()); } // delete users foreach (string username in origUsers) { if (!newUsers.Contains(username) && username != ownerUsername) { // delete user GenericResult2 r = usrAdmin.DeleteUser(Username, Password, siteId, username); } } } }
protected object gridElem_OnExternalDataBound(object sender, string sourceName, object parameter) { switch (sourceName) { case "remove": if (sender is CMSGridActionButton) { // Get action button CMSGridActionButton deleteBtn = (CMSGridActionButton)sender; deleteBtn.Enabled = friendsManagePermission; return deleteBtn; } else { return string.Empty; } case "approve": if (sender is CMSGridActionButton) { // Get action button CMSGridActionButton approveBtn = (CMSGridActionButton)sender; // Get full row view DataRowView drv = UniGridFunctions.GetDataRowView((DataControlFieldCell)approveBtn.Parent); // Add custom reject action approveBtn.OnClientClick = "return FM_Approve_" + ClientID + "('" + drv["FriendID"] + "',null,'" + ApproveDialogUrl + "');"; approveBtn.Enabled = friendsManagePermission; return approveBtn; } else { return string.Empty; } case "friendrejectedwhen": if (currentUserInfo == null) { currentUserInfo = MembershipContext.AuthenticatedUser; } if (currentSiteInfo == null) { currentSiteInfo = SiteContext.CurrentSite; } DateTime currentDateTime = ValidationHelper.GetDateTime(parameter, DateTimeHelper.ZERO_TIME); if (IsLiveSite) { return TimeZoneMethods.ConvertDateTime(currentDateTime, this); } else { return TimeZoneHelper.ConvertToUserTimeZone(currentDateTime, true, currentUserInfo, currentSiteInfo); } case "formattedusername": return HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(Convert.ToString(parameter), IsLiveSite)); } return parameter; }
private static List <Tab> GetTopMenus(SiteInfo siteInfo, bool isSuperAdmin, List <int> siteIdListLatestAccessed, List <int> siteIdListWithPermissions) { var menus = new List <Tab>(); if (siteInfo != null && siteIdListWithPermissions.Contains(siteInfo.Id)) { var siteMenus = new List <Tab>(); if (siteIdListWithPermissions.Count == 1) { menus.Add(new Tab { Text = siteInfo.SiteName, Children = siteMenus.ToArray() }); } else { var siteIdList = AdminManager.GetLatestTop10SiteIdList(siteIdListLatestAccessed, siteIdListWithPermissions); foreach (var siteId in siteIdList) { var site = SiteManager.GetSiteInfo(siteId); if (site == null) { continue; } siteMenus.Add(new Tab { Href = PageUtils.GetMainUrl(site.Id), Target = "_top", Text = site.SiteName }); } siteMenus.Add(new Tab { Href = ModalSiteSelect.GetRedirectUrl(siteInfo.Id), Target = "_layer", Text = "全部站点..." }); menus.Add(new Tab { Text = siteInfo.SiteName, Href = ModalSiteSelect.GetRedirectUrl(siteInfo.Id), Target = "_layer", Children = siteMenus.ToArray() }); } var linkMenus = new List <Tab> { new Tab { Href = PageUtility.GetSiteUrl(siteInfo, false), Target = "_blank", Text = "访问站点" }, new Tab { Href = ApiRoutePreview.GetSiteUrl(siteInfo.Id), Target = "_blank", Text = "预览站点" } }; menus.Add(new Tab { Text = "站点链接", Children = linkMenus.ToArray() }); } if (isSuperAdmin) { foreach (var tab in TabManager.GetTopMenuTabs()) { var tabs = TabManager.GetTabList(tab.Id, 0); tab.Children = tabs.ToArray(); menus.Add(tab); } } return(menus); }
protected void Page_Load(object sender, EventArgs e) { // Register script files ScriptHelper.RegisterCMS(this); ScriptHelper.RegisterScriptFile(this, "~/CMSModules/Content/CMSDesk/Operation.js"); // Set current UI culture currentCulture = CultureHelper.PreferredUICultureCode; // Initialize current user currentUser = MembershipContext.AuthenticatedUser; // Initialize current site currentSite = SiteContext.CurrentSite; // Initialize events ctlAsyncLog.OnFinished += ctlAsyncLog_OnFinished; ctlAsyncLog.OnError += ctlAsyncLog_OnError; ctlAsyncLog.OnCancel += ctlAsyncLog_OnCancel; if (!RequestHelper.IsCallback()) { DataSet allDocs = null; TreeProvider tree = new TreeProvider(currentUser); // Current Node ID to delete string parentAliasPath = string.Empty; if (Parameters != null) { parentAliasPath = ValidationHelper.GetString(Parameters["parentaliaspath"], string.Empty); } if (string.IsNullOrEmpty(parentAliasPath)) { nodeIdsArr = QueryHelper.GetString("nodeid", string.Empty).Trim('|').Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries); foreach (string nodeId in nodeIdsArr) { int id = ValidationHelper.GetInteger(nodeId, 0); if (id != 0) { nodeIds.Add(id); } } } else { var where = new WhereCondition(WhereCondition) .WhereNotEquals("ClassName", SystemDocumentTypes.Root); allDocs = tree.SelectNodes(currentSite.SiteName, parentAliasPath.TrimEnd(new[] { '/' }) + "/%", TreeProvider.ALL_CULTURES, true, ClassID > 0 ? DataClassInfoProvider.GetClassName(ClassID) : TreeProvider.ALL_CLASSNAMES, where.ToString(true), "DocumentName", TreeProvider.ALL_LEVELS, false, 0, DocumentColumnLists.SELECTNODES_REQUIRED_COLUMNS + ",DocumentName,NodeParentID,NodeSiteID,NodeAliasPath,NodeSKUID"); if (!DataHelper.DataSourceIsEmpty(allDocs)) { foreach (DataTable table in allDocs.Tables) { foreach (DataRow row in table.Rows) { nodeIds.Add(ValidationHelper.GetInteger(row["NodeID"], 0)); } } } } // Setup page title text and image PageTitle.TitleText = GetString("Content.DeleteTitle"); EnsureDocumentBreadcrumbs(PageBreadcrumbs, action: PageTitle.TitleText); // Register the dialog script ScriptHelper.RegisterDialogScript(this); ctlAsyncLog.TitleText = GetString("ContentDelete.DeletingDocuments"); // Set visibility of panels pnlContent.Visible = true; pnlLog.Visible = false; bool isMultilingual = CultureSiteInfoProvider.IsSiteMultilingual(currentSite.SiteName); if (!isMultilingual) { // Set all cultures checkbox chkAllCultures.Checked = true; pnlAllCultures.Visible = false; } if (nodeIds.Count > 0) { if (nodeIds.Count == 1) { // Single document deletion int nodeId = ValidationHelper.GetInteger(nodeIds[0], 0); TreeNode node = null; if (string.IsNullOrEmpty(parentAliasPath)) { // Get any culture if current not found node = tree.SelectSingleNode(nodeId, CultureCode) ?? tree.SelectSingleNode(nodeId, TreeProvider.ALL_CULTURES); } else { if (allDocs != null) { DataRow dr = allDocs.Tables[0].Rows[0]; node = TreeNode.New(ValidationHelper.GetString(dr["ClassName"], string.Empty), dr, tree); } } if (node != null) { bool rootDeleteDisabled = false; if (IsProductsMode) { string startingPath = SettingsKeyInfoProvider.GetValue(CurrentSiteName + ".CMSStoreProductsStartingPath"); if (node.NodeAliasPath.CompareToCSafe(startingPath) == 0) { string closeLink = "<a href=\"#\"><span style=\"cursor: pointer;\" " + "onclick=\"SelectNode(" + node.NodeID + "); return false;\">" + GetString("general.back") + "</span></a>"; ShowError(string.Format(GetString("com.productsection.deleteroot"), closeLink, "")); pnlDelete.Visible = false; rootDeleteDisabled = true; } } if (node.IsRoot() && isMultilingual) { // Hide 'Delete all cultures' checkbox pnlAllCultures.Visible = false; if (!URLHelper.IsPostback()) { // Check if there are any documents in another culture or current culture has some documents pnlDeleteRoot.Visible = IsAnyDocumentInAnotherCulture(node) && (tree.SelectNodesCount(SiteContext.CurrentSiteName, "/%", LocalizationContext.PreferredCultureCode, false, null, null, null, TreeProvider.ALL_LEVELS, false) > 0); if (pnlDeleteRoot.Visible) { // Insert 'Delete current root' option if current root node is translated to current culture if (node.DocumentCulture == LocalizationContext.PreferredCultureCode) { rblRoot.Items.Add(new ListItem(GetString("rootdeletion.currentroot"), "current")); } rblRoot.Items.Add(new ListItem(GetString("rootdeletion.currentculture"), "allculturepages")); rblRoot.Items.Add(new ListItem(GetString("rootdeletion.allpages"), "allpages")); } else { rblRoot.Items.Add(new ListItem(GetString("rootdeletion.allpages"), "allpages")); } if (rblRoot.SelectedIndex < 0) { rblRoot.SelectedIndex = 0; } } } // Display warning for root node if (!rootDeleteDisabled && node.IsRoot()) { if (!currentUser.IsGlobalAdministrator) { pnlDelete.Visible = false; ShowInformation(GetString("delete.rootonlyglobaladmin")); } else { if ((rblRoot.SelectedValue == "allpages") || !isMultilingual || ((rblRoot.SelectedValue == "allculturepages") && !IsAnyDocumentInAnotherCulture(node))) { messagesPlaceholder.ShowWarning(GetString("Delete.RootWarning")); plcDeleteRoot.Visible = true; } else { plcDeleteRoot.Visible = false; } } } hasChildren = node.NodeHasChildren; bool authorizedToDeleteSKU = !node.HasSKU || IsUserAuthorizedToModifySKU(node); if (!RequestHelper.IsPostBack()) { bool authorizedToDeleteDocument = IsUserAuthorizedToDeleteDocument(node); if (!authorizedToDeleteDocument || !authorizedToDeleteSKU) { pnlDelete.Visible = false; RedirectToAccessDenied(String.Format(GetString("cmsdesk.notauthorizedtodeletedocument"), HTMLHelper.HTMLEncode(node.NodeAliasPath))); } } if (node.IsLink) { PageTitle.TitleText = GetString("Content.DeleteTitleLink") + " \"" + HTMLHelper.HTMLEncode(ResHelper.LocalizeString(node.GetDocumentName())) + "\""; headQuestion.Text = GetString("ContentDelete.QuestionLink"); chkAllCultures.Checked = true; plcCheck.Visible = false; } else { string nodeName = HTMLHelper.HTMLEncode(node.GetDocumentName()); // Get name for root document if (node.IsRoot()) { nodeName = HTMLHelper.HTMLEncode(currentSite.DisplayName); } PageTitle.TitleText = GetString("Content.DeleteTitle") + " \"" + HTMLHelper.HTMLEncode(ResHelper.LocalizeString(nodeName)) + "\""; } // Show or hide checkbox pnlDestroy.Visible = CanDestroy(node); cancelNodeId = IsMultipleAction ? node.NodeParentID : node.NodeID; lblDocuments.Text = HTMLHelper.HTMLEncode(node.GetDocumentName()); if (node.IsRoot()) { // Change SEO panel if root is selected pnlSeo.Visible = false; } } else { if (!RequestHelper.IsPostBack()) { URLHelper.Redirect(UIHelper.GetInformationUrl("editeddocument.notexists")); } else { // Hide everything pnlContent.Visible = false; } } headQuestion.Text = GetString("ContentDelete.Question"); lblAllCultures.Text = GetString("ContentDelete.AllCultures"); lblDestroy.Text = GetString("ContentDelete.Destroy"); headDeleteDocument.Text = GetString("ContentDelete.Document"); } else if (nodeIds.Count > 1) { string where = "NodeID IN ("; foreach (int nodeID in nodeIds) { where += nodeID + ","; } where = where.TrimEnd(',') + ")"; DataSet ds = allDocs ?? tree.SelectNodes(currentSite.SiteName, "/%", TreeProvider.ALL_CULTURES, true, null, where, "DocumentName", -1, false); if (!DataHelper.DataSourceIsEmpty(ds)) { string docList = null; if (string.IsNullOrEmpty(parentAliasPath)) { cancelNodeId = DataHelper.GetIntValue(ds.Tables[0].Rows[0], "NodeParentID"); } else { cancelNodeId = TreePathUtils.GetNodeIdByAliasPath(currentSite.SiteName, parentAliasPath); } bool canDestroy = true; bool permissions = true; foreach (DataTable table in ds.Tables) { foreach (DataRow dr in table.Rows) { bool isLink = (dr["NodeLinkedNodeID"] != DBNull.Value); string name = (string)dr["DocumentName"]; docList += HTMLHelper.HTMLEncode(name); if (isLink) { docList += DocumentUIHelper.GetDocumentMarkImage(Page, DocumentMarkEnum.Link); } docList += "<br />"; lblDocuments.Text = docList; // Set visibility of checkboxes TreeNode node = TreeNode.New(ValidationHelper.GetString(dr["ClassName"], string.Empty), dr); if (!IsUserAuthorizedToDeleteDocument(node)) { permissions = false; AddError(String.Format( GetString("cmsdesk.notauthorizedtodeletedocument"), HTMLHelper.HTMLEncode(node.NodeAliasPath)), null); } // Can destroy if "can destroy all previous AND current" canDestroy = CanDestroy(node) && canDestroy; if (!hasChildren) { hasChildren = node.NodeHasChildren; } } } pnlDelete.Visible = permissions; pnlDestroy.Visible = canDestroy; } else { if (!RequestHelper.IsPostBack()) { URLHelper.Redirect(UIHelper.GetInformationUrl("editeddocument.notexists")); } else { // Hide everything pnlContent.Visible = false; } } headQuestion.Text = GetString("ContentDelete.QuestionMultiple"); PageTitle.TitleText = GetString("Content.DeleteTitleMultiple"); lblAllCultures.Text = GetString("ContentDelete.AllCulturesMultiple"); lblDestroy.Text = GetString("ContentDelete.DestroyMultiple"); headDeleteDocument.Text = GetString("global.pages"); } lblAltPath.AssociatedControlClientID = selAltPath.PathTextBox.ClientID; selAltPath.SiteID = currentSite.SiteID; chkUseDeletedPath.CheckedChanged += chkUseDeletedPath_CheckedChanged; if (!RequestHelper.IsPostBack()) { selAltPath.Enabled = false; chkAltSubNodes.Enabled = false; chkAltAliases.Enabled = false; // Set default path if is defined selAltPath.Value = SettingsKeyInfoProvider.GetValue(CurrentSiteName + ".CMSDefaultDeletedNodePath"); if (!hasChildren) { chkAltSubNodes.Checked = false; chkAltSubNodes.Enabled = false; } } // If user has allowed cultures specified if (currentUser.UserHasAllowedCultures) { // Get all site cultures DataSet siteCultures = CultureSiteInfoProvider.GetSiteCultures(currentSite.SiteName); bool denyAllCulturesDeletion = false; // Check that user can edit all site cultures foreach (DataRow culture in siteCultures.Tables[0].Rows) { string cultureCode = DataHelper.GetStringValue(culture, "CultureCode"); if (!currentUser.IsCultureAllowed(cultureCode, currentSite.SiteName)) { denyAllCulturesDeletion = true; } } // If user can't edit all site cultures if (denyAllCulturesDeletion) { // Hide all cultures selector pnlAllCultures.Visible = false; chkAllCultures.Checked = false; } } pnlDeleteDocument.Visible = pnlAllCultures.Visible || pnlDestroy.Visible; } else { // Hide everything pnlContent.Visible = false; } } // Initialize header action InitializeActionMenu(); }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); EnsureScripts(); radCopy.Text = GetString("ContentNewCultureVersion.Copy"); radEmpty.Text = GetString("ContentNewCultureVersion.Empty"); radTranslate.Text = GetString("ContentNewCultureVersion.Translate"); radCopy.Attributes.Add("onclick", "ShowSelection();"); radEmpty.Attributes.Add("onclick", "ShowSelection()"); radTranslate.Attributes.Add("onclick", "ShowSelection()"); btnCreateDocument.Text = GetString("ContentNewCultureVersion.Create"); btnTranslate.Text = GetString("ContentNewCultureVersion.TranslateButton"); btnTranslate.Click += btnTranslate_Click; btnCreateDocument.Click += btnCreateDocument_Click; if ((NodeID <= 0) || (Node == null)) { return; } // Fill in the existing culture versions bool translationAllowed = SettingsKeyInfoProvider.GetBoolValue(Node.NodeSiteName + ".CMSEnableTranslations") && LicenseHelper.IsFeatureAvailableInUI(FeatureEnum.TranslationServices, ModuleName.TRANSLATIONSERVICES); if (translationAllowed) { var settings = new TranslationSettings(); settings.TargetLanguages.Add(RequiredCulture); translationElem.TranslationSettings = settings; translationElem.NodeID = Node.NodeID; } else { translationElem.StopProcessing = true; plcTranslationServices.Visible = false; } if (!MembershipContext.AuthenticatedUser.IsAuthorizedToCreateNewDocument(Node.NodeParentID, Node.NodeClassName)) { pnlNewVersion.Visible = false; headNewCultureVersion.Visible = false; ShowError(GetString("accessdenied.notallowedtocreatenewcultureversion")); } else { SiteInfo si = SiteInfoProvider.GetSiteInfo(Node.NodeSiteID); if (si == null) { return; } TreeNode originalNode = Tree.GetOriginalNode(Node); copyCulturesElem.UniSelector.DisplayNameFormat = "{% CultureName %}{% if (CultureCode == \"" + CultureHelper.GetDefaultCultureCode(si.SiteName) + "\") { \" \" +\"" + GetString("general.defaultchoice") + "\" } %}"; copyCulturesElem.AdditionalWhereCondition = "CultureCode IN (SELECT DocumentCulture FROM CMS_Document WHERE DocumentNodeID = " + originalNode.NodeID + ")"; if (!MembershipContext.AuthenticatedUser.IsCultureAllowed(RequiredCulture, si.SiteName)) { pnlNewVersion.Visible = false; headNewCultureVersion.Visible = false; ShowError(GetString("transman.notallowedcreate")); } } }
public static string GetColumnsHtml(Dictionary <string, string> nameValueCacheDict, SiteInfo siteInfo, ContentInfo contentInfo, StringCollection attributesOfDisplay, List <TableStyleInfo> displayStyleInfoList, Dictionary <string, Dictionary <string, Func <IContentContext, string> > > pluginColumns) { var builder = new StringBuilder(); foreach (var styleInfo in displayStyleInfoList) { if (!attributesOfDisplay.Contains(styleInfo.AttributeName) || styleInfo.AttributeName == ContentAttribute.Title) { continue; } var value = GetColumnValue(nameValueCacheDict, siteInfo, contentInfo, styleInfo); builder.Append($@"<td class=""text-nowrap"">{value}</td>"); } if (pluginColumns != null) { foreach (var pluginId in pluginColumns.Keys) { var contentColumns = pluginColumns[pluginId]; if (contentColumns == null || contentColumns.Count == 0) { continue; } foreach (var columnName in contentColumns.Keys) { var attributeName = $"{pluginId}:{columnName}"; if (!attributesOfDisplay.Contains(attributeName)) { continue; } try { var func = contentColumns[columnName]; var value = func(new ContentContextImpl { SiteId = contentInfo.SiteId, ChannelId = contentInfo.ChannelId, ContentId = contentInfo.Id }); builder.Append($@"<td class=""text-nowrap"">{value}</td>"); } catch (Exception ex) { LogUtils.AddErrorLog(pluginId, ex); } } } } return(builder.ToString()); }
/// <summary> /// External data binding handler. /// </summary> protected object gridElem_OnExternalDataBound(object sender, string sourceName, object parameter) { // Prepare variables string culture; DataRowView data; sourceName = sourceName.ToLowerCSafe(); SiteInfo site; switch (sourceName) { // Edit button case EXTERNALSOURCE_EDIT: if (sender is CMSGridActionButton) { var editButton = (CMSGridActionButton)sender; data = UniGridFunctions.GetDataRowView(editButton.Parent as DataControlFieldCell); site = GetSiteFromRow(data); int nodeId = ValidationHelper.GetInteger(data[SOURCE_NODEID], 0); culture = ValidationHelper.GetString(data[SOURCE_DOCUMENTCULTURE], string.Empty); string type = ValidationHelper.GetString(DataHelper.GetDataRowViewValue(data, SOURCE_TYPE), string.Empty); // Check permissions if ((site.Status != SiteStatusEnum.Running) || (!CMSPage.IsUserAuthorizedPerContent(site.SiteName) || ((ListingType == ListingTypeEnum.All) && (type == LISTINGTYPE_RECYCLEBIN)))) { editButton.Enabled = false; editButton.Style.Add(HtmlTextWriterStyle.Cursor, "default"); } else { editButton.Attributes.Add("data-site-url", ResolveSiteUrl(site)); editButton.Attributes.Add("data-node-id", nodeId.ToString()); editButton.Attributes.Add("data-document-culture", culture); } editButton.OnClientClick = "return false"; return editButton; } return sender; // Preview button case EXTERNALSOURCE_PREVIEW: if (sender is CMSGridActionButton) { var previewButton = (CMSGridActionButton)sender; data = UniGridFunctions.GetDataRowView(previewButton.Parent as DataControlFieldCell); site = GetSiteFromRow(data); string type = ValidationHelper.GetString(DataHelper.GetDataRowViewValue(data, SOURCE_TYPE), string.Empty); if ((site.Status != SiteStatusEnum.Running) || ((ListingType == ListingTypeEnum.All) && (type == LISTINGTYPE_RECYCLEBIN))) { previewButton.Enabled = false; previewButton.Style.Add(HtmlTextWriterStyle.Cursor, "default"); } else { culture = ValidationHelper.GetString(data[SOURCE_DOCUMENTCULTURE], string.Empty); var nodeID = ValidationHelper.GetInteger(data[SOURCE_NODEID], 0); // Generate preview URL var query = QueryHelper.BuildQuery("viewmode", ((int)ViewModeEnum.Preview).ToString(), URLHelper.LanguageParameterName, culture); string url = DocumentURLProvider.GetPresentationUrlHandlerPath(culture, nodeID, query); previewButton.Attributes.Add("data-preview-url", URLHelper.GetAbsoluteUrl(url, site.DomainName)); } previewButton.OnClientClick = "return false"; return previewButton; } return sender; // Document name column case EXTERNALSOURCE_DOCUMENTNAME: data = (DataRowView)parameter; string name = ValidationHelper.GetString(data[SOURCE_DOCUMENTNAME], string.Empty); string className = ValidationHelper.GetString(data[SOURCE_CLASSNAME], string.Empty); if (name == string.Empty) { name = GetString("general.root"); } // Add document type icon string result = string.Empty; switch (ListingType) { case ListingTypeEnum.DocTypeDocuments: break; default: var dataClass = DataClassInfoProvider.GetDataClassInfo(className); if (dataClass != null) { var iconClass = (string)dataClass.GetValue(SOURCE_CLASSICONCLASS); result = UIHelper.GetDocumentTypeIcon(Page, className, iconClass); } break; } result += "<span>" + HTMLHelper.HTMLEncode(TextHelper.LimitLength(name, 50)) + "</span>"; // Show document marks only if method is not called from grid export if ((sender != null) && (ListingType != ListingTypeEnum.All)) { bool isLink = (data.Row.Table.Columns.Contains(SOURCE_NODELINKEDNODEID) && (data[SOURCE_NODELINKEDNODEID] != DBNull.Value)); if (isLink) { // Add link icon result += DocumentUIHelper.GetDocumentMarkImage(Parent.Page, DocumentMarkEnum.Link); } } return result; // Class name column case EXTERNALSOURCE_CLASSDISPLAYNAME: string displayName = ValidationHelper.GetString(parameter, string.Empty); if (sourceName.ToLowerCSafe() == EXTERNALSOURCE_CLASSDISPLAYNAMETOOLTIP) { displayName = TextHelper.LimitLength(displayName, 50); } if (displayName == string.Empty) { displayName = "-"; } return HTMLHelper.HTMLEncode(ResHelper.LocalizeString(displayName)); case EXTERNALSOURCE_DOCUMENTNAMETOOLTIP: data = (DataRowView)parameter; return UniGridFunctions.DocumentNameTooltip(data); case EXTERNALSOURCE_STEPDISPLAYNAME: // Step display name int stepId = ValidationHelper.GetInteger(parameter, 0); if (stepId > 0) { return new ObjectTransformation(WorkflowStepInfo.OBJECT_TYPE, stepId) { Transformation = "{%stepdisplayname|(encode)%}" }; } return "-"; // Version column case EXTERNALSOURCE_VERSION: if (parameter == DBNull.Value) { parameter = "-"; } parameter = HTMLHelper.HTMLEncode(parameter.ToString()); return parameter; // Document timestamp column case EXTERNALSOURCE_MODIFIEDWHEN: case EXTERNALSOURCE_MODIFIEDWHENTOOLTIP: if (String.IsNullOrEmpty(parameter.ToString())) { return String.Empty; } if (currentSiteInfo == null) { currentSiteInfo = SiteContext.CurrentSite; } if (sourceName.EqualsCSafe(EXTERNALSOURCE_MODIFIEDWHEN, StringComparison.InvariantCultureIgnoreCase)) { DateTime time = ValidationHelper.GetDateTime(parameter, DateTimeHelper.ZERO_TIME); return TimeZoneHelper.ConvertToUserTimeZone(time, true, currentUserInfo, currentSiteInfo); } return mGMTTooltip ?? (mGMTTooltip = TimeZoneHelper.GetUTCLongStringOffset(currentUserInfo, currentSiteInfo)); } return parameter; }
private void Set(Context context, DataRow dataRow, string tableAlias = null) { AccessStatus = Databases.AccessStatuses.Selected; foreach (DataColumn dataColumn in dataRow.Table.Columns) { var column = new ColumnNameInfo(dataColumn.ColumnName); if (column.TableAlias == tableAlias) { switch (column.Name) { case "OwnerId": if (dataRow[column.ColumnName] != DBNull.Value) { OwnerId = dataRow[column.ColumnName].ToLong(); SavedOwnerId = OwnerId; } break; case "OwnerType": if (dataRow[column.ColumnName] != DBNull.Value) { OwnerType = dataRow[column.ColumnName].ToString(); SavedOwnerType = OwnerType; } break; case "MailAddressId": if (dataRow[column.ColumnName] != DBNull.Value) { MailAddressId = dataRow[column.ColumnName].ToLong(); SavedMailAddressId = MailAddressId; } break; case "Ver": Ver = dataRow[column.ColumnName].ToInt(); SavedVer = Ver; break; case "MailAddress": MailAddress = dataRow[column.ColumnName].ToString(); SavedMailAddress = MailAddress; break; case "Comments": Comments = dataRow[column.ColumnName].ToString().Deserialize <Comments>() ?? new Comments(); SavedComments = Comments.ToJson(); break; case "Creator": Creator = SiteInfo.User(context: context, userId: dataRow.Int(column.ColumnName)); SavedCreator = Creator.Id; break; case "Updator": Updator = SiteInfo.User(context: context, userId: dataRow.Int(column.ColumnName)); SavedUpdator = Updator.Id; break; case "CreatedTime": CreatedTime = new Time(context, dataRow, column.ColumnName); SavedCreatedTime = CreatedTime.Value; break; case "UpdatedTime": UpdatedTime = new Time(context, dataRow, column.ColumnName); Timestamp = dataRow.Field <DateTime>(column.ColumnName).ToString("yyyy/M/d H:m:s.fff"); SavedUpdatedTime = UpdatedTime.Value; break; case "IsHistory": VerType = dataRow.Bool(column.ColumnName) ? Versions.VerTypes.History : Versions.VerTypes.Latest; break; default: switch (Def.ExtendedColumnTypes.Get(column.Name)) { case "Class": Class( columnName: column.Name, value: dataRow[column.ColumnName].ToString()); SavedClass( columnName: column.Name, value: Class(columnName: column.Name)); break; case "Num": Num( columnName: column.Name, value: dataRow[column.ColumnName].ToDecimal()); SavedNum( columnName: column.Name, value: Num(columnName: column.Name)); break; case "Date": Date( columnName: column.Name, value: dataRow[column.ColumnName].ToDateTime()); SavedDate( columnName: column.Name, value: Date(columnName: column.Name)); break; case "Description": Description( columnName: column.Name, value: dataRow[column.ColumnName].ToString()); SavedDescription( columnName: column.Name, value: Description(columnName: column.Name)); break; case "Check": Check( columnName: column.Name, value: dataRow[column.ColumnName].ToBool()); SavedCheck( columnName: column.Name, value: Check(columnName: column.Name)); break; case "Attachments": Attachments( columnName: column.Name, value: dataRow[column.ColumnName].ToString() .Deserialize <Attachments>() ?? new Attachments()); SavedAttachments( columnName: column.Name, value: Attachments(columnName: column.Name).ToJson()); break; } break; } } } }
/// <summary> /// Setups grid where condition to filter out by given restrictions. /// </summary> private void SetupGridFilterWhereCondition() { string where = String.Empty; // Set proper base where condition switch (ListingType) { case ListingTypeEnum.CheckedOut: where = "DocumentCheckedOutByUserID = @UserID"; break; case ListingTypeEnum.MyDocuments: where = "NodeOwner = @UserID"; break; case ListingTypeEnum.RecentDocuments: where = "((DocumentCreatedByUserID = @UserID OR DocumentModifiedByUserID = @UserID OR DocumentCheckedOutByUserID = @UserID))"; break; case ListingTypeEnum.PendingDocuments: where = "DocumentWorkflowStepID IN (SELECT StepID FROM CMS_WorkflowStep WHERE " + WorkflowStepInfoProvider.GetWorkflowPendingStepsWhereCondition(currentUserInfo, new SiteInfoIdentifier(SiteName)).ToString(false) + ")"; break; case ListingTypeEnum.OutdatedDocuments: where = "DocumentCreatedByUserID = @UserID OR DocumentModifiedByUserID = @UserID OR DocumentCheckedOutByUserID = @UserID"; break; case ListingTypeEnum.All: where = String.Format("(UserID1 = {0} OR UserID2 = {0} OR UserID3 = {0})", currentUserInfo.UserID); break; } gridElem.WhereCondition = SqlHelper.AddWhereCondition(gridElem.WhereCondition, where); // Selected site filter if (!String.IsNullOrEmpty(SiteName) && (SiteName != UniGrid.ALL)) { selectedSiteInfo = SiteInfoProvider.GetSiteInfo(SiteName); if (selectedSiteInfo != null) { gridElem.WhereCondition = SqlHelper.AddWhereCondition(gridElem.WhereCondition, SOURCE_NODESITEID + " = " + selectedSiteInfo.SiteID); } } // Site running filter if ((SiteName == UniGrid.ALL) && DisplayOnlyRunningSites) { gridElem.WhereCondition = SqlHelper.AddWhereCondition(gridElem.WhereCondition, "NodeSiteID IN (SELECT SiteID FROM CMS_Site WHERE SiteStatus = 'RUNNING')"); } // Path filter if (Path != String.Empty) { gridElem.WhereCondition = SqlHelper.AddWhereCondition(gridElem.WhereCondition, ((ListingType == ListingTypeEnum.All) ? SOURCE_DOCUMENTNAMEPATH : SOURCE_NODEALIASPATH) + " LIKE N'" + SqlHelper.EscapeQuotes(MacroResolver.ResolveCurrentPath(Path)) + "'"); } // Document type filer if (!String.IsNullOrEmpty(DocumentType)) { string classNames = DocumentTypeHelper.GetClassNames(DocumentType); gridElem.WhereCondition = SqlHelper.AddWhereCondition(gridElem.WhereCondition, SqlHelper.GetWhereCondition<string>(SOURCE_CLASSNAME, classNames.Split(';'), true)); } // Document name filter if (DocumentName != String.Empty) { gridElem.WhereCondition = SqlHelper.AddWhereCondition(gridElem.WhereCondition, SOURCE_DOCUMENTNAME + " LIKE N'%" + SqlHelper.EscapeLikeText(SqlHelper.EscapeQuotes(DocumentName)) + "%'"); } }
public static List <ContentInfo> GetContentListByTxtFile(string directoryPath, SiteInfo siteInfo, ChannelInfo nodeInfo) { var contentInfoList = new List <ContentInfo>(); var filePaths = DirectoryUtils.GetFilePaths(directoryPath); foreach (var filePath in filePaths) { if (!EFileSystemTypeUtils.Equals(EFileSystemType.Txt, PathUtils.GetExtension(filePath))) { continue; } try { var content = FileUtils.ReadText(filePath, ECharset.gb2312); if (!string.IsNullOrEmpty(content)) { content = content.Trim(); var title = StringUtils.GetFirstOfStringCollection(content, '\r'); if (!string.IsNullOrEmpty(title)) { var contentInfo = new ContentInfo { Title = title.Trim(), SiteId = siteInfo.Id, ChannelId = nodeInfo.Id, LastEditDate = DateTime.Now }; contentInfo.Set(BackgroundContentAttribute.Content, StringUtils.ReplaceNewlineToBr(content.Replace(title, string.Empty).Trim())); contentInfoList.Add(contentInfo); } } } catch { // ignored } } return(contentInfoList); }
public BinSettingsContainer(CurrentUserInfo user, What what, SiteInfo site) : this() { User = user; CurrentWhat = what; Site = site; }
private void Set(DataRow dataRow, string tableAlias = null) { AccessStatus = Databases.AccessStatuses.Selected; foreach (DataColumn dataColumn in dataRow.Table.Columns) { var column = new ColumnNameInfo(dataColumn.ColumnName); if (column.TableAlias == tableAlias) { switch (column.Name) { case "TenantId": if (dataRow[column.ColumnName] != DBNull.Value) { TenantId = dataRow[column.ColumnName].ToInt(); SavedTenantId = TenantId; } break; case "StatusId": if (dataRow[column.ColumnName] != DBNull.Value) { StatusId = dataRow[column.ColumnName].ToInt(); SavedStatusId = StatusId; } break; case "Ver": Ver = dataRow[column.ColumnName].ToInt(); SavedVer = Ver; break; case "Value": Value = dataRow[column.ColumnName].ToString(); SavedValue = Value; break; case "Comments": Comments = dataRow[column.ColumnName].ToString().Deserialize <Comments>() ?? new Comments(); SavedComments = Comments.ToJson(); break; case "Creator": Creator = SiteInfo.User(dataRow[column.ColumnName].ToInt()); SavedCreator = Creator.Id; break; case "Updator": Updator = SiteInfo.User(dataRow[column.ColumnName].ToInt()); SavedUpdator = Updator.Id; break; case "CreatedTime": CreatedTime = new Time(dataRow, column.ColumnName); SavedCreatedTime = CreatedTime.Value; break; case "UpdatedTime": UpdatedTime = new Time(dataRow, column.ColumnName); Timestamp = dataRow.Field <DateTime>(column.ColumnName).ToString("yyyy/M/d H:m:s.fff"); SavedUpdatedTime = UpdatedTime.Value; break; case "IsHistory": VerType = dataRow[column.ColumnName].ToBool() ? Versions.VerTypes.History : Versions.VerTypes.Latest; break; } } } }
public void ReloadData() { if (StopProcessing) { newFileElem.StopProcessing = true; gridAttachments.StopProcessing = true; } else { // Initialize button for adding attachments newFileElem.DisplayInline = false; newFileElem.Text = GetString("attach.uploadfile"); newFileElem.InnerElementClass = InnerDivClass; newFileElem.InnerLoadingElementClass = InnerLoadingDivClass; newFileElem.IsLiveSite = IsLiveSite; newFileElem.SourceType = MediaSourceEnum.MediaLibraries; newFileElem.MediaFileID = MediaFileID; newFileElem.ParentElemID = ClientID; newFileElem.LibraryFolderPath = LibraryFolderPath; newFileElem.IsMediaThumbnail = IsMediaThumbnail; newFileElem.LibraryID = LibraryID; newFileElem.ReloadData(); // Get preview info if (IsMediaThumbnail && (FileInfo != null)) { SiteInfo si = SiteInfoProvider.GetSiteInfo(LibraryInfo.LibrarySiteID); if (si != null) { previewPath = MediaFileInfoProvider.GetPreviewFilePath(FileInfo.FilePath, si.SiteName, LibraryInfo.LibraryID); if (previewPath.Length < 260) { string previewFolder = Path.GetDirectoryName(previewPath); if (Directory.Exists(previewFolder)) { string[] files = Directory.GetFiles(previewFolder, Path.GetFileName(previewPath)); if (files.Length > 0) { previewPath = files[0]; previewName = Path.GetFileNameWithoutExtension(previewPath); previewExt = Path.GetExtension(previewPath).TrimStart('.'); } else { previewPath = ""; } } else { previewPath = ""; } } else { previewPath = ""; } } } // Bind UniGrid to DataSource gridAttachments.GridView.AllowPaging = false; gridAttachments.GridView.AllowSorting = false; // Get the data if (IsMediaThumbnail) { if (!string.IsNullOrEmpty(previewPath)) { // Create DataSet manually for preview FileInfo file = CMS.IO.FileInfo.New(previewPath); if (file.Exists) { DataSet ds = new DataSet(); DataTable table = ds.Tables.Add(); table.Columns.Add("FileID", typeof(int)); table.Columns.Add("FileSize", typeof(long)); table.Columns.Add("FileName", typeof(string)); table.Rows.Add(0, file.Length, previewName); gridAttachments.DataSource = ds; } } else { gridAttachments.DataSource = null; } } else { gridAttachments.DataSource = MediaFileInfoProvider.GetMediaFiles("FileID = " + MediaFileID); } gridAttachments.ReloadData(); updPanel.Update(); } }
private void Set( Context context, SiteSettings ss, DataRow dataRow, string tableAlias) { foreach (DataColumn dataColumn in dataRow.Table.Columns) { var column = new ColumnNameInfo(dataColumn.ColumnName); if (column.TableAlias == tableAlias) { switch (column.Name) { case "SiteId": SiteId = dataRow[column.ColumnName].ToLong(); break; case "IssueId": IssueId = dataRow[column.ColumnName].ToLong(); break; case "Ver": Ver = dataRow[column.ColumnName].ToInt(); break; case "Title": Title = new Title(context: context, ss: ss, dataRow: dataRow, column: column); break; case "Body": Body = dataRow[column.ColumnName].ToString(); break; case "StartTime": StartTime = dataRow[column.ColumnName].ToDateTime(); break; case "CompletionTime": CompletionTime = new CompletionTime(context: context, ss: ss, dataRow: dataRow, column: column); break; case "WorkValue": WorkValue = new WorkValue(dataRow, column); break; case "ProgressRate": ProgressRate = new ProgressRate(dataRow, column); break; case "RemainingWorkValue": RemainingWorkValue = dataRow[column.ColumnName].ToDecimal(); break; case "Status": Status = new Status(dataRow, column); break; case "Manager": Manager = SiteInfo.User(context: context, userId: dataRow.Int(column.ColumnName)); break; case "Owner": Owner = SiteInfo.User(context: context, userId: dataRow.Int(column.ColumnName)); break; case "Locked": Locked = dataRow[column.ColumnName].ToBool(); break; case "Comments": Comments = dataRow[column.ColumnName].ToString().Deserialize <Comments>() ?? new Comments(); break; case "Creator": Creator = SiteInfo.User(context: context, userId: dataRow.Int(column.ColumnName)); break; case "Updator": Updator = SiteInfo.User(context: context, userId: dataRow.Int(column.ColumnName)); break; case "CreatedTime": CreatedTime = new Time(context, dataRow, column.ColumnName); break; default: switch (Def.ExtendedColumnTypes.Get(column.Name)) { case "Class": Class( columnName: column.Name, value: dataRow[column.ColumnName].ToString()); break; case "Num": Num( columnName: column.Name, value: dataRow[column.ColumnName].ToDecimal()); break; case "Date": Date( columnName: column.Name, value: dataRow[column.ColumnName].ToDateTime()); break; case "Description": Description( columnName: column.Name, value: dataRow[column.ColumnName].ToString()); break; case "Check": Check( columnName: column.Name, value: dataRow[column.ColumnName].ToBool()); break; } break; } } } }
protected object gridElem_OnExternalDataBound(object sender, string sourceName, object parameter) { DataRowView drv = null; switch (sourceName) { case "reject": if (sender is ImageButton) { // Get action button ImageButton rejectBtn = (ImageButton)sender; // Get full row view drv = UniGridFunctions.GetDataRowView((DataControlFieldCell)rejectBtn.Parent); // Add custom reject action rejectBtn.Attributes["onclick"] = "return FM_Reject_" + ClientID + "('" + drv["FriendID"] + "',null,'" + RejectDialogUrl + "');"; return rejectBtn; } else { return string.Empty; } case "approve": if (sender is ImageButton) { // Get action button ImageButton approveBtn = (ImageButton)sender; // Get full row view drv = UniGridFunctions.GetDataRowView((DataControlFieldCell)approveBtn.Parent); // Add custom reject action approveBtn.Attributes["onclick"] = "return FM_Approve_" + ClientID + "('" + drv["FriendID"] + "',null,'" + ApproveDialogUrl + "');"; return approveBtn; } else { return string.Empty; } case "friendrequestedwhen": if (currentUserInfo == null) { currentUserInfo = CMSContext.CurrentUser; } if (currentSiteInfo == null) { currentSiteInfo = CMSContext.CurrentSite; } DateTime currentDateTime = ValidationHelper.GetDateTime(parameter, DateTimeHelper.ZERO_TIME); if (IsLiveSite) { return CMSContext.ConvertDateTime(currentDateTime, this); } else { return TimeZoneHelper.GetCurrentTimeZoneDateTimeString(currentDateTime, currentUserInfo, currentSiteInfo, out usedTimeZone); } case "formattedusername": return HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(Convert.ToString(parameter), this.IsLiveSite)); } return parameter; }
public WsFederatedSiteInfo(SiteInfo site) : base(site) { }