private void InitializeUploadControl() { var info = Form.EditedObject as BaseInfo; if (info != null) { fileUploader.ObjectType = info.TypeInfo.ObjectType; if (info.Generalized.ObjectSiteID > 0) { fileUploader.SiteID = info.Generalized.ObjectSiteID; } fileUploader.ObjectID = info.Generalized.ObjectID; } else { var item = Form.EditedObject as IDataClass; if (item != null) { fileUploader.ObjectType = item.ClassName; if (!string.IsNullOrEmpty(Form.SiteName)) { fileUploader.SiteID = SiteInfoProvider.GetSiteID(Form.SiteName); } fileUploader.ObjectID = item.ID; } } }
/// <summary> /// Initializes media file info. /// </summary> /// <param name="objectGuid">Media file GUID</param> /// <param name="siteName">Site name</param> private void metaDataEditor_InitializeObject(Guid objectGuid, string siteName) { // Get mediafile mediaFileInfo = MediaFileInfo.Provider.Get(objectGuid, SiteInfoProvider.GetSiteID(siteName)); // If media file is not null if (mediaFileInfo != null) { MediaLibraryInfo mli = MediaLibraryInfo.Provider.Get(ValidationHelper.GetInteger(mediaFileInfo.FileLibraryID, 0)); // Check permission 'FileModify' if (metaDataEditor.CheckPermissions && !MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(mli, "filemodify")) { RedirectToAccessDenied(GetString("metadata.errors.filemodify")); } // Fire event GetObjectExtension if (GetObjectExtension != null) { GetObjectExtension(mediaFileInfo.FileExtension); } } else { RedirectToInformation(GetString("editedobject.notexists")); } }
/// <summary> /// Initializes the upload control. /// </summary> private void InitializeUploadControl() { if (Form.EditedObject is BaseInfo) { BaseInfo info = (BaseInfo)Form.EditedObject; fileList.ObjectType = info.TypeInfo.ObjectType; if (info.Generalized.ObjectSiteID > 0) { fileList.SiteID = info.Generalized.ObjectSiteID; } fileList.ObjectID = info.Generalized.ObjectID; } else if (Form.EditedObject is IDataClass) { IDataClass item = (IDataClass)Form.EditedObject; fileList.ObjectType = item.ClassName; if (!string.IsNullOrEmpty(Form.SiteName)) { fileList.SiteID = SiteInfoProvider.GetSiteID(Form.SiteName); } fileList.ObjectID = item.ID; } }
private void SetupFileUploaderControl() { fileUploader.Category = Category; fileUploader.AllowedExtensions = String.Join(";", ImageHelper.ImageExtensions); if (Form.EditedObject is BaseInfo) { BaseInfo info = (BaseInfo)Form.EditedObject; fileUploader.ObjectType = info.TypeInfo.ObjectType; if (info.Generalized.ObjectSiteID > 0) { fileUploader.SiteID = info.Generalized.ObjectSiteID; } fileUploader.ObjectID = info.Generalized.ObjectID; } else if (Form.EditedObject is IDataClass) { IDataClass item = (IDataClass)Form.EditedObject; fileUploader.ObjectType = item.ClassName; if (!string.IsNullOrEmpty(Form.SiteName)) { fileUploader.SiteID = SiteInfoProvider.GetSiteID(Form.SiteName); } fileUploader.ObjectID = item.ID; } }
protected void Page_Load(object sender, EventArgs e) { // Set control properties from parent Form if (Form != null) { Form.OnBeforeRedirect += new EventHandler(Form_OnBeforeRedirect); if (Form is UIForm) { BaseInfo info = ((UIForm)Form).EditedObject as BaseInfo; if (info != null) { fileUploader.ObjectType = info.TypeInfo.ObjectType; if (info.Generalized.ObjectSiteID > 0) { fileUploader.SiteID = info.Generalized.ObjectSiteID; } fileUploader.ObjectID = info.Generalized.ObjectID; } } else if (Form.EditedObject is IDataClass) { IDataClass item = Form.EditedObject as IDataClass; if (item != null) { fileUploader.ObjectType = item.ClassName; if (!string.IsNullOrEmpty(Form.SiteName)) { fileUploader.SiteID = SiteInfoProvider.GetSiteID(Form.SiteName); } fileUploader.ObjectID = item.ID; } } // Set metafile category fileUploader.Category = ValidationHelper.GetString(GetValue("ObjectCategory"), CMSConstants.OBJECT_CATEGORY_THUMBNAIL); } // Set style properties of control if (!String.IsNullOrEmpty(ControlStyle)) { fileUploader.Attributes.Add("style", ControlStyle); ControlStyle = null; } if (!String.IsNullOrEmpty(CssClass)) { fileUploader.CssClass = CssClass; CssClass = null; } CheckFieldEmptiness = false; }
/// <summary> /// Setups grid query parameters. /// </summary> private void SetupGridQueryParameters() { // Create query parameters QueryDataParameters parameters = new QueryDataParameters(); parameters.Add("@Now", DateTime.Now); if (ListingType == ListingTypeEnum.OutdatedDocuments) { parameters.Add("@SiteID", SiteContext.CurrentSiteID); } // Initialize UserID query parameter int userID = currentUserInfo.UserID; if (ListingType == ListingTypeEnum.PendingDocuments) { parameters.Add("@SiteID", SiteInfoProvider.GetSiteID(SiteName)); if ((currentUserInfo.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin)) || (currentUserInfo.IsAuthorizedPerResource("CMS.Content", "manageworkflow"))) { userID = -1; } } parameters.Add("@UserID", userID); // Document Age if (DocumentAge != String.Empty) { string[] ages = DocumentAge.Split(';'); if (ages.Length == 2) { // Add from a to values to temp parameters int from = ValidationHelper.GetInteger(ages[1], 0); int to = ValidationHelper.GetInteger(ages[0], 0); if (@from > 0) { gridElem.WhereCondition = SqlHelper.AddWhereCondition(gridElem.WhereCondition, SOURCE_MODIFIEDWHEN + " >= @FROM"); parameters.Add("@FROM", DateTime.Now.AddDays((-1) * @from)); } if (to > 0) { gridElem.WhereCondition = SqlHelper.AddWhereCondition(gridElem.WhereCondition, SOURCE_MODIFIEDWHEN + " <= @TO"); parameters.Add("@TO", DateTime.Now.AddDays((-1) * to)); } } } // Set parameters gridElem.QueryParameters = parameters; }
public bool IsAtSynchronizedSite(CategoryInfo category) { // Synchronize global categories if (category.CategorySiteID == 0) { return(true); } var siteId = SiteInfoProvider.GetSiteID(Settings.Sitename); return(category.CategorySiteID == siteId); }
private IList <Guid> GetCategoryGuids(TreeNode node) { var siteId = SiteInfoProvider.GetSiteID(Settings.Sitename); var guids = DocumentCategoryInfoProvider.GetDocumentCategories(node.DocumentID) .OnSite(Settings.Sitename, true) .WhereNull("CategoryUserID") .TypedResult .Select(category => category.CategoryGUID) .ToList(); return(guids); }
public static int TranslateBindingTranslateID(int ItemID, DataSet TaskData, string classname) { DataTable ObjectTranslationTable = TaskData.Tables.Cast <DataTable>().Where(x => x.TableName.ToLower() == "objecttranslation").FirstOrDefault(); if (ObjectTranslationTable == null) { EventLogProvider.LogEvent("E", "RelHelper.TranslateBindingTranslateID", "NoObjectTranslationTable", "Could not find an ObjectTranslation table in the Task Data, please make sure to only call this with a task that has an ObjectTranslation table"); return(-1); } foreach (DataRow ItemDR in ObjectTranslationTable.Rows.Cast <DataRow>() .Where(x => ValidationHelper.GetString(x["ObjectType"], "").ToLower() == classname.ToLower() && ValidationHelper.GetInteger(x["ID"], -1) == ItemID)) { int TranslationID = ValidationHelper.GetInteger(ItemDR["ID"], 0); if (ItemID == TranslationID) { GetIDParameters ItemParams = new GetIDParameters(); if (ValidationHelper.GetGuid(ItemDR["GUID"], Guid.Empty) != Guid.Empty) { ItemParams.Guid = (Guid)ItemDR["GUID"]; } if (!string.IsNullOrWhiteSpace(ValidationHelper.GetString(ItemDR["CodeName"], ""))) { ItemParams.CodeName = (string)ItemDR["CodeName"]; } if (ObjectTranslationTable.Columns.Contains("SiteName") && !string.IsNullOrWhiteSpace(ValidationHelper.GetString(ItemDR["SiteName"], ""))) { int SiteID = SiteInfoProvider.GetSiteID((string)ItemDR["SiteName"]); if (SiteID > 0) { ItemParams.SiteId = SiteID; } } try { int NewID = TranslationHelper.GetIDFromDB(ItemParams, classname); if (NewID > 0) { ItemID = NewID; } } catch (Exception ex) { EventLogProvider.LogException("RelHelper.TranslateBindingTranslateID", "No Translation Found", ex, additionalMessage: "No Translation found."); return(-1); } } } return(ItemID); }
/// <summary> /// Returns image name, title and description according to image type. /// </summary> /// <returns>Image name, title and description</returns> private void baseImageEditor_GetMetaData() { if (mfi == null) { mfi = MediaFileInfo.Provider.Get(mediafileGuid, SiteInfoProvider.GetSiteID(CurrentSiteName)); } if (mfi != null) { string name = mfi.FileName; baseImageEditor.GetNameResult = name; baseImageEditor.GetTitleResult = mfi.FileTitle; baseImageEditor.GetDescriptionResult = mfi.FileDescription; } }
private void LogExceptionToEventLog(Exception ex, string uiCulture) { var logData = new EventLogData(EventTypeEnum.Error, "Content", "TRANSLATEDOC") { EventDescription = EventLogProvider.GetExceptionLogMessage(ex), EventUrl = RequestContext.RawURL, UserID = currentUser.UserID, UserName = currentUser.UserName, IPAddress = RequestContext.UserHostAddress, SiteID = SiteInfoProvider.GetSiteID(CurrentSiteName) }; Service.Resolve <IEventLogService>().LogEvent(logData); AddError(GetString("ContentRequest.TranslationFailed", uiCulture) + ex.Message); }
protected void Page_Load(object sender, EventArgs e) { mediafileGuid = QueryHelper.GetGuid("mediafileguid", Guid.Empty); isPreview = QueryHelper.GetBoolean("isPreview", false); // Get media file information if (mfi == null) { mfi = MediaFileInfo.Provider.Get(mediafileGuid, SiteInfoProvider.GetSiteID(CurrentSiteName)); } if (mfi != null) { // Get media library information MediaLibraryInfo mli = MediaLibraryInfo.Provider.Get(mfi.FileLibraryID); if (mli != null) { // Get path to media file folder string path = Path.GetDirectoryName(DirectoryHelper.CombinePath(MediaLibraryInfoProvider.GetMediaLibraryFolderPath(mli.LibraryID), mfi.FilePath)); // Enable control if permissions are sufficient to edit image Enabled = DirectoryHelper.CheckPermissions(path, false, true, true, true); if (!Enabled) { // Set error message baseImageEditor.ShowError(GetString("img.errors.filesystempermissions")); } } } // Enable or disable image editor baseImageEditor.Enabled = Enabled; baseImageEditor.LoadImageType += baseImageEditor_LoadImageType; baseImageEditor.InitializeProperties += baseImageEditor_InitializeProperties; baseImageEditor.InitializeLabels += baseImageEditor_InitializeLabels; baseImageEditor.SaveImage += baseImageEditor_SaveImage; baseImageEditor.GetMetaData += baseImageEditor_GetMetaData; baseImageEditor.LoadImageUrl += baseImageEditor_LoadImageUrl; }
/// <summary> /// Convert given department name to its ID for specified site. /// </summary> /// <param name="name">Name of the department to be converted.</param> /// <param name="siteName">Name of the site of the department.</param> protected override int GetID(string name, string siteName) { DepartmentInfo dept; if (ShowAllSites) { // Take any department dept = DepartmentInfo.Provider.Get() .TopN(1) .WithCodeName(name) .OrderByAscending("DepartmentSiteID") .FirstOrDefault(); } else { dept = DepartmentInfo.Provider.Get(name, SiteInfoProvider.GetSiteID(siteName)); } return(dept?.DepartmentID ?? 0); }
/// <summary> /// Determines if the discount coupons are available for the current site. /// </summary> private bool AreDiscountCouponsAvailableOnSite() { string siteName = this.ShoppingCartInfoObj.SiteName; // Check site and global discount coupons string where = "DiscountCouponSiteID = " + SiteInfoProvider.GetSiteID(siteName); if (ECommerceSettings.AllowGlobalDiscountCoupons(siteName)) { where += " OR DiscountCouponSiteID IS NULL"; } // Coupons are available if found any DataSet ds = DiscountCouponInfoProvider.GetDiscountCoupons(where, null, -1, "count(DiscountCouponID)"); if (!DataHelper.DataSourceIsEmpty(ds)) { return(ValidationHelper.GetInteger(ds.Tables[0].Rows[0][0], 0) > 0); } return(false); }
/// <summary> /// Updates uni selector where condition based on current properties values. /// </summary> public string UpdateWhereCondition(string siteName) { string where = String.Empty; if (OnlyUsersBlogs) { where = "NodeOwner=" + MembershipContext.AuthenticatedUser.UserID; } DataClassInfo dci = DataClassInfoProvider.GetDataClassInfo("cms.blog"); if (dci != null) { where = SqlHelper.AddWhereCondition(where, "NodeClassID=" + dci.ClassID); } if (!String.IsNullOrEmpty(siteName)) { where = SqlHelper.AddWhereCondition(where, "NodeSiteID=" + SiteInfoProvider.GetSiteID(siteName)); } return(where); }
/// <summary> /// Enable or disable controls with dependence on current settings. /// </summary> /// <param name="clear">Indicates whether selector value should be cleared</param> protected void SetControlsStatus(bool clear) { if (clear) { selectForm.Value = null; } selectForm.Enabled = true; string siteName = ValidationHelper.GetString(selSite.Value, String.Empty); if (String.IsNullOrEmpty(siteName) || (siteName == "-1")) { selectForm.Enabled = false; btnOk.Enabled = false; } else { selectForm.WhereCondition = new WhereCondition() .WhereEquals("FormSiteID", SiteInfoProvider.GetSiteID(siteName)) .ToString(true); } selectForm.Reload(true); }
public int GetSiteID(string SiteName) { return(SiteInfoProvider.GetSiteID(SiteName)); }
private void LogExceptionToEventLog(Exception ex, string uiCulture) { EventLogProvider.LogEvent(EventType.ERROR, "Content", "TRANSLATEDOC", EventLogProvider.GetExceptionLogMessage(ex), RequestContext.RawURL, currentUser.UserID, currentUser.UserName, 0, null, RequestContext.UserHostAddress, SiteInfoProvider.GetSiteID(CurrentSiteName)); AddError(ResHelper.GetString("ContentRequest.TranslationFailed", uiCulture) + ex.Message); }
/// <summary> /// Translates document(s). /// </summary> private void Translate(object parameter) { var parameters = parameter as AsyncParameters; if ((parameters == null) || nodeIds.Count < 1) { return; } AbstractMachineTranslationService machineService = null; AbstractHumanTranslationService humanService = null; TranslationSubmissionInfo submission = null; string submissionFileName = ""; int charCount = 0; int wordCount = 0; int refreshId = 0; int itemCount = 0; int pageCount = 0; bool oneSubmission = translationElem.CreateSeparateSubmission; bool success = false; bool separateSubmissionCreated = false; TreeProvider tree = new TreeProvider(); tree.AllowAsyncActions = false; try { // Begin log AddLog(ResHelper.GetString("contentrequest.starttranslate", parameters.UICulture)); // Prepare translation settings var settings = PrepareTranslationSettings(); // Check selected service var service = TranslationServiceInfoProvider.GetTranslationServiceInfo(translationElem.SelectedService); if (service == null) { return; } // Set if we need target tag (Translations.com workaround) settings.GenerateTargetTag = service.TranslationServiceGenerateTargetTag; if (service.TranslationServiceIsMachine) { machineService = AbstractMachineTranslationService.GetTranslationService(service, CurrentSiteName); } else { humanService = AbstractHumanTranslationService.GetTranslationService(service, CurrentSiteName); } bool langSupported = (humanService == null) || CheckLanguageSupport(humanService, settings); if (!langSupported) { return; } if ((machineService != null) || (humanService != null)) { var data = tree.SelectNodes() .CombineWithDefaultCulture(false) .Published(false) .Culture(settings.SourceLanguage) .WhereIn("NodeID", nodeIds) .OnSite(CurrentSiteName) .OrderBy("NodeLevel, NodeAliasPath") .Column("NodeID"); if (!DataHelper.DataSourceIsEmpty(data)) { var processedNodes = new List <int>(); // Translate the documents foreach (DataRow dr in data.Tables[0].Rows) { int nodeId = ValidationHelper.GetInteger(dr["NodeID"], 0); // Get document in source language var node = DocumentHelper.GetDocument(nodeId, settings.SourceLanguage, false, tree); if (node == null) { // Document doesn't exist in source culture, skip it continue; } var targetLanguages = GetTargetLanguages(settings.TargetLanguages, node).ToList(); if (!targetLanguages.Any()) { continue; } if ((submission == null) && (humanService != null)) { // Create new submission if not exists for human translation service submission = TranslationServiceHelper.CreateSubmissionInfo(settings, service, MembershipContext.AuthenticatedUser.UserID, SiteInfoProvider.GetSiteID(CurrentSiteName), node.GetDocumentName()); } // Handle duplicities if (processedNodes.Contains(nodeId)) { continue; } processedNodes.Add(nodeId); bool targetLanguageVersionCreated = false; bool logged = false; string encodedPath = HTMLHelper.HTMLEncode(node.NodeAliasPath); foreach (var targetLanguage in targetLanguages) { // Log only once per document if (!logged) { AddLog(String.Format(ResHelper.GetString("content.translating"), encodedPath, settings.SourceLanguage)); logged = true; } itemCount++; targetLanguageVersionCreated = true; if (humanService != null) { if (String.IsNullOrEmpty(submissionFileName)) { submissionFileName = node.NodeAlias; } var targetNode = TranslationServiceHelper.CreateTargetCultureNode(node, targetLanguage, true, false, !settings.TranslateAttachments); TranslationSubmissionItemInfo submissionItem; using (new CMSActionContext { TouchParent = false }) { // Do not touch parent because all updated information are saved after last item submissionItem = TranslationServiceHelper.CreateSubmissionItemInfo(settings, submission, node, targetNode.DocumentID, targetLanguage); } charCount += submissionItem.SubmissionItemCharCount; wordCount += submissionItem.SubmissionItemWordCount; } else { // Prepare local settings to translate per one target language var localSettings = settings.Clone(); localSettings.TargetLanguages.Clear(); localSettings.TargetLanguages.Add(targetLanguage); // Translate page via machine translator TranslationServiceHelper.Translate(machineService, localSettings, node); } } // Each page has own submission if human service is used if (!oneSubmission && (humanService != null)) { if (itemCount > 0) { SubmitSubmissionToService(itemCount, submission, charCount, wordCount, submissionFileName, humanService, true); // Reset counters itemCount = 0; charCount = 0; wordCount = 0; // Reset submission file name submissionFileName = null; // At least one submission was created separateSubmissionCreated = true; } else { // No documents were submitted to translation delete empty submission TranslationSubmissionInfoProvider.DeleteTranslationSubmissionInfo(submission); } // Reset submission to create new for next page submission = null; } if (targetLanguageVersionCreated) { // Check if at least one target language version was created pageCount++; } // Store parent ID to refresh UI refreshId = node.NodeParentID; } success = true; } else { AddError(ResHelper.GetString("TranslateDocument.NoSourceDocuments", parameters.UICulture)); } } else { AddError(ResHelper.GetString("TranslateDocument.TranslationServiceNotFound", parameters.UICulture)); } } catch (ThreadAbortException ex) { if (CMSThread.Stopped(ex)) { // When canceled AddError(ResHelper.GetString("TranslateDocument.TranslationCanceled", parameters.UICulture)); } else { // Log error LogExceptionToEventLog(ex, parameters.UICulture); } } catch (Exception ex) { // Log error LogExceptionToEventLog(ex, parameters.UICulture); } finally { var showAllAlreadyTranslatedError = false; if (itemCount > 0) { // All pages are submitted via only one submission or using machine service if ((humanService != null) && (submission != null)) { // Set submission name if more pages are translated if (pageCount > 1) { submission.SubmissionName += " " + string.Format(GetString("translationservices.submissionnamesuffix"), pageCount - 1); // Do not localize the file name submissionFileName += string.Format(" (and {0} more)", pageCount - 1); } SubmitSubmissionToService(itemCount, submission, charCount, wordCount, submissionFileName, humanService, success); } } else if (oneSubmission) { TranslationSubmissionInfoProvider.DeleteTranslationSubmissionInfo(submission); // Log error only if the translation was successfully processed if (success) { showAllAlreadyTranslatedError = true; } } else if (!separateSubmissionCreated) { // Separate submissions were used and no one was created showAllAlreadyTranslatedError = true; } if (showAllAlreadyTranslatedError) { AddError(ResHelper.GetString("TranslateDocument.DocumentsAlreadyTranslated", parameters.UICulture)); } if (parameters.IsDialog) { ctlAsyncLog.Parameter = "wopener.location.replace(wopener.location); CloseDialog(); if (wopener.RefreshTree) { wopener.RefreshTree(null, null);}"; } else { if (string.IsNullOrEmpty(CurrentError)) { // Overwrite refreshId variable if sub-levels are visible if (parameters.AllLevels && Parameters.ContainsKey("refreshnodeid")) { refreshId = ValidationHelper.GetInteger(Parameters["refreshnodeid"], 0); } // Refresh tree ctlAsyncLog.Parameter = "RefreshTree(" + refreshId + ", " + refreshId + "); \n" + "SelectNode(" + refreshId + ");"; } else { ctlAsyncLog.Parameter = "RefreshTree(null, null);"; } } } }
protected void Page_Load(object sender, EventArgs e) { if (StopProcessing) { // Do nothing return; } gridElem.IsLiveSite = IsLiveSite; gridElem.OnExternalDataBound += gridElem_OnExternalDataBound; gridElem.HideControlForZeroRows = false; currentUserInfo = CMSContext.CurrentUser; // Initialize strings string strDays = GetString("MyDesk.OutdatedDocuments.Days"); string strWeeks = GetString("MyDesk.OutdatedDocuments.Weeks"); string strMonths = GetString("MyDesk.OutdatedDocuments.Months"); string strYears = GetString("MyDesk.OutdatedDocuments.Years"); // Set proper XML for control type switch (ListingType) { case ListingTypeEnum.CheckedOut: gridElem.ZeroRowsText = GetString("mydesk.ui.nochecked"); gridElem.WhereCondition = "View_CMS_Tree_Joined.DocumentCheckedOutByUserID = @UserID"; break; case ListingTypeEnum.MyDocuments: gridElem.ZeroRowsText = GetString("general.nodatafound"); gridElem.WhereCondition = "View_CMS_Tree_Joined.NodeOwner = @UserID"; break; case ListingTypeEnum.RecentDocuments: gridElem.ZeroRowsText = GetString("general.nodatafound"); gridElem.WhereCondition = "((View_CMS_Tree_Joined.DocumentCreatedByUserID = @UserID OR View_CMS_Tree_Joined.DocumentModifiedByUserID = @UserID OR View_CMS_Tree_Joined.DocumentCheckedOutByUserID = @UserID))"; break; case ListingTypeEnum.PendingDocuments: gridElem.ZeroRowsText = GetString("mydesk.ui.nowaitingdocs"); gridElem.WhereCondition = WorkflowStepInfoProvider.GetWorkflowPendingStepsWhereCondition(currentUserInfo, SiteName); break; case ListingTypeEnum.OutdatedDocuments: // Initialize controls if (!RequestHelper.IsPostBack()) { // Fill the dropdown list drpFilter.Items.Add(strDays); drpFilter.Items.Add(strWeeks); drpFilter.Items.Add(strMonths); drpFilter.Items.Add(strYears); // Load default value txtFilter.Text = "1"; drpFilter.SelectedValue = strYears; // Bind dropdown lists BindDropDowns(); } gridElem.WhereCondition = "((DocumentCreatedByUserID = @UserID OR DocumentModifiedByUserID = @UserID OR DocumentCheckedOutByUserID = @UserID) AND " + SOURCE_MODIFIEDWHEN + "<=@OlderThan AND " + SOURCE_NODESITEID + "=@SiteID)"; // Add where condition if (!string.IsNullOrEmpty(txtDocumentName.Text)) { gridElem.WhereCondition = SqlHelperClass.AddWhereCondition(gridElem.WhereCondition, GetOutdatedWhereCondition(SOURCE_DOCUMENTNAME, drpDocumentName, txtDocumentName)); } if (!string.IsNullOrEmpty(txtDocumentType.Text)) { gridElem.WhereCondition = SqlHelperClass.AddWhereCondition(gridElem.WhereCondition, GetOutdatedWhereCondition(SOURCE_CLASSDISPLAYNAME, drpDocumentType, txtDocumentType)); } gridElem.ZeroRowsText = GetString("mydesk.ui.nooutdated"); // Show custom filter plcOutdatedFilter.Visible = true; break; case ListingTypeEnum.WorkflowDocuments: break; case ListingTypeEnum.PageTemplateDocuments: gridElem.ZeroRowsText = GetString("Administration-PageTemplate_Header.Documents.nodata"); break; case ListingTypeEnum.CategoryDocuments: gridElem.ZeroRowsText = GetString("Category_Edit.Documents.nodata"); break; case ListingTypeEnum.ProductDocuments: break; case ListingTypeEnum.TagDocuments: gridElem.ZeroRowsText = GetString("taggroup_edit.documents.nodata"); break; case ListingTypeEnum.DocTypeDocuments: gridElem.ZeroRowsText = GetString("DocumentType_Edit_General.Documents.nodata"); break; case ListingTypeEnum.All: gridElem.ZeroRowsText = GetString("mydesk.ui.nodata"); break; } // Page Size if (!RequestHelper.IsPostBack() && !String.IsNullOrEmpty(ItemsPerPage)) { gridElem.Pager.DefaultPageSize = ValidationHelper.GetInteger(ItemsPerPage, -1); } // Order switch (ListingType) { case ListingTypeEnum.WorkflowDocuments: case ListingTypeEnum.OutdatedDocuments: case ListingTypeEnum.PageTemplateDocuments: case ListingTypeEnum.CategoryDocuments: case ListingTypeEnum.TagDocuments: case ListingTypeEnum.ProductDocuments: case ListingTypeEnum.DocTypeDocuments: gridElem.OrderBy = SOURCE_DOCUMENTNAME; break; default: gridElem.OrderBy = OrderBy; break; } if (ListingType == ListingTypeEnum.All) { gridElem.WhereCondition = SqlHelperClass.AddWhereCondition(gridElem.WhereCondition, String.Format("(UserID1 = {0} OR UserID2 = {0} OR UserID3 = {0})", currentUserInfo.UserID)); } // Create query parameters QueryDataParameters parameters = new QueryDataParameters(); if (ListingType == ListingTypeEnum.OutdatedDocuments) { parameters.Add("@SiteID", CMSContext.CurrentSite.SiteID); DateTime olderThan = DateTime.Now; int dateTimeValue = ValidationHelper.GetInteger(txtFilter.Text, 0); if (drpFilter.SelectedValue == strDays) { olderThan = olderThan.AddDays(-dateTimeValue); } else if (drpFilter.SelectedValue == strWeeks) { olderThan = olderThan.AddDays(-dateTimeValue * 7); } else if (drpFilter.SelectedValue == strMonths) { olderThan = olderThan.AddMonths(-dateTimeValue); } else if (drpFilter.SelectedValue == strYears) { olderThan = olderThan.AddYears(-dateTimeValue); } parameters.Add("@OlderThan", olderThan); } // Initialize UserID query parameter int userID = currentUserInfo.UserID; if (ListingType == ListingTypeEnum.PendingDocuments) { parameters.Add("@SiteID", SiteInfoProvider.GetSiteID(SiteName)); if ((currentUserInfo.IsGlobalAdministrator) || (currentUserInfo.IsAuthorizedPerResource("CMS.Content", "manageworkflow"))) { userID = -1; } } parameters.Add("@UserID", userID); // Document Age if (DocumentAge != String.Empty) { string[] ages = DocumentAge.Split(';'); if (ages.Length == 2) { // Add from a to values to temp parameters int from = ValidationHelper.GetInteger(ages[1], 0); int to = ValidationHelper.GetInteger(ages[0], 0); if (from > 0) { gridElem.WhereCondition = SqlHelperClass.AddWhereCondition(gridElem.WhereCondition, SOURCE_MODIFIEDWHEN + " >= @FROM"); parameters.Add("@FROM", DateTime.Now.AddDays((-1) * from)); } if (to > 0) { gridElem.WhereCondition = SqlHelperClass.AddWhereCondition(gridElem.WhereCondition, SOURCE_MODIFIEDWHEN + " <= @TO"); parameters.Add("@TO", DateTime.Now.AddDays((-1) * to)); } } } // Site name if (!String.IsNullOrEmpty(SiteName) && (SiteName != UniGrid.ALL)) { SiteInfo site = SiteInfoProvider.GetSiteInfo(SiteName); if (site != null) { gridElem.WhereCondition = SqlHelperClass.AddWhereCondition(gridElem.WhereCondition, SOURCE_NODESITEID + " = " + site.SiteID); UniGrid.GridColumns.Columns.RemoveAll(c => (c.Source == SOURCE_SITENAME || c.Source == SOURCE_NODESITEID)); } } // Path filter if (Path != String.Empty) { if (ListingType == ListingTypeEnum.All) { gridElem.WhereCondition = SqlHelperClass.AddWhereCondition(gridElem.WhereCondition, SOURCE_DOCUMENTNAMEPATH + " LIKE N'" + CMSContext.ResolveCurrentPath(Path).Replace("'", "''") + "'"); } else { gridElem.WhereCondition = SqlHelperClass.AddWhereCondition(gridElem.WhereCondition, SOURCE_NODEALIASPATH + " LIKE N'" + CMSContext.ResolveCurrentPath(Path).Replace("'", "''") + "'"); } } // Document type filer if (!String.IsNullOrEmpty(DocumentType)) { string[] types = DocumentType.Split(';'); gridElem.WhereCondition = SqlHelperClass.AddWhereCondition(gridElem.WhereCondition, SqlHelperClass.GetWhereCondition <string>(SOURCE_CLASSNAME, types, true)); } // Document name filter if (DocumentName != String.Empty) { gridElem.WhereCondition = SqlHelperClass.AddWhereCondition(gridElem.WhereCondition, SOURCE_DOCUMENTNAME + " LIKE N'%" + SqlHelperClass.GetSafeQueryString(DocumentName, false) + "%'"); } // Site running filter if ((SiteName == UniGrid.ALL) && DisplayOnlyRunningSites) { gridElem.WhereCondition = SqlHelperClass.AddWhereCondition(gridElem.WhereCondition, "SiteName IN (SELECT SiteName FROM CMS_Site WHERE SiteStatus = 'RUNNING')"); } // Set parameters gridElem.QueryParameters = parameters; }
/// <summary> /// Reloads control. /// </summary> /// <param name="forceReload">Forces nested CMSForm to reload if true</param> public void ReloadData(bool forceReload) { if (!mFormLoaded || forceReload) { // Check License LicenseHelper.CheckFeatureAndRedirect(RequestContext.CurrentDomain, FeatureEnum.UserContributions); if (!StopProcessing) { // Set document manager mode if (NewDocument) { DocumentManager.Mode = FormModeEnum.Insert; DocumentManager.ParentNodeID = NodeID; DocumentManager.NewNodeClassID = ClassID; DocumentManager.CultureCode = CultureCode; DocumentManager.SiteName = SiteName; } else if (NewCulture) { DocumentManager.Mode = FormModeEnum.InsertNewCultureVersion; DocumentManager.NodeID = NodeID; DocumentManager.CultureCode = CultureCode; DocumentManager.SiteName = SiteName; DocumentManager.SourceDocumentID = CopyDefaultDataFromDocumentID; } else { DocumentManager.Mode = FormModeEnum.Update; DocumentManager.NodeID = NodeID; DocumentManager.SiteName = SiteName; DocumentManager.CultureCode = CultureCode; } ScriptHelper.RegisterDialogScript(Page); titleElem.TitleText = String.Empty; pnlSelectClass.Visible = false; pnlEdit.Visible = false; pnlInfo.Visible = false; pnlNewCulture.Visible = false; pnlDelete.Visible = false; // If node found, init the form if (NewDocument || (Node != null)) { // Delete action if (Delete) { // Delete document pnlDelete.Visible = true; titleElem.TitleText = GetString("Content.DeleteTitle"); chkAllCultures.Text = GetString("ContentDelete.AllCultures"); chkDestroy.Text = GetString("ContentDelete.Destroy"); lblQuestion.Text = GetString("ContentDelete.Question"); btnYes.Text = GetString("general.yes"); // Prevent button double-click btnYes.Attributes.Add("onclick", string.Format("document.getElementById('{0}').disabled=true;this.disabled=true;{1};", btnNo.ClientID, ControlsHelper.GetPostBackEventReference(btnYes, string.Empty, true, false))); btnNo.Text = GetString("general.no"); DataSet culturesDS = CultureSiteInfoProvider.GetSiteCultures(SiteName); if ((DataHelper.DataSourceIsEmpty(culturesDS)) || (culturesDS.Tables[0].Rows.Count <= 1)) { chkAllCultures.Visible = false; chkAllCultures.Checked = true; } if (Node.IsLink) { titleElem.TitleText = GetString("Content.DeleteTitleLink") + " \"" + HTMLHelper.HTMLEncode(Node.NodeName) + "\""; lblQuestion.Text = GetString("ContentDelete.QuestionLink"); chkAllCultures.Checked = true; plcCheck.Visible = false; } else { titleElem.TitleText = GetString("Content.DeleteTitle") + " \"" + HTMLHelper.HTMLEncode(Node.NodeName) + "\""; } } // New document or edit action else { if (NewDocument) { titleElem.TitleText = GetString("Content.NewTitle"); } // Document type selection if (NewDocument && (ClassID <= 0)) { // Use parent node TreeNode parentNode = DocumentManager.ParentNode; if (parentNode != null) { // Select document type pnlSelectClass.Visible = true; // Apply document type scope string whereCondition = DocumentTypeScopeInfoProvider.GetScopeClassWhereCondition(parentNode); var parentClassId = ValidationHelper.GetInteger(parentNode.GetValue("NodeClassID"), 0); var siteId = SiteInfoProvider.GetSiteID(SiteName); // Get the allowed child classes DataSet ds = AllowedChildClassInfoProvider.GetAllowedChildClasses(parentClassId, siteId) .Where(whereCondition) .OrderBy("ClassID") .Columns("ClassName", "ClassDisplayName", "ClassID"); ArrayList deleteRows = new ArrayList(); if (!DataHelper.DataSourceIsEmpty(ds)) { // Get the unwanted classes string allowed = AllowedChildClasses.Trim().ToLowerCSafe(); if (!string.IsNullOrEmpty(allowed)) { allowed = String.Format(";{0};", allowed); } var userInfo = MembershipContext.AuthenticatedUser; string className = null; // Check if the user has 'Create' permission per Content bool isAuthorizedToCreateInContent = userInfo.IsAuthorizedPerResource("CMS.Content", "Create"); bool hasNodeAllowCreate = (userInfo.IsAuthorizedPerTreeNode(parentNode, NodePermissionsEnum.Create) != AuthorizationResultEnum.Allowed); foreach (DataRow dr in ds.Tables[0].Rows) { className = ValidationHelper.GetString(DataHelper.GetDataRowValue(dr, "ClassName"), String.Empty).ToLowerCSafe(); // Document type is not allowed or user hasn't got permission, remove it from the data set if ((!string.IsNullOrEmpty(allowed) && (!allowed.Contains(";" + className + ";"))) || (CheckPermissions && CheckDocPermissionsForInsert && !isAuthorizedToCreateInContent && !userInfo.IsAuthorizedPerClassName(className, "Create") && (!userInfo.IsAuthorizedPerClassName(className, "CreateSpecific") || !hasNodeAllowCreate))) { deleteRows.Add(dr); } } // Remove the rows foreach (DataRow dr in deleteRows) { ds.Tables[0].Rows.Remove(dr); } } // Check if some classes are available if (!DataHelper.DataSourceIsEmpty(ds)) { // If number of classes is more than 1 display them in grid if (ds.Tables[0].Rows.Count > 1) { ds.Tables[0].DefaultView.Sort = "ClassDisplayName"; lblError.Visible = false; lblInfo.Visible = true; lblInfo.Text = GetString("Content.NewInfo"); DataSet sortedResult = new DataSet(); sortedResult.Tables.Add(ds.Tables[0].DefaultView.ToTable()); gridClass.DataSource = sortedResult; gridClass.ReloadData(); } // else show form of the only class else { ClassID = ValidationHelper.GetInteger(DataHelper.GetDataRowValue(ds.Tables[0].Rows[0], "ClassID"), 0); ReloadData(true); return; } } else { // Display error message lblError.Visible = true; lblError.Text = GetString("Content.NoAllowedChildDocuments"); lblInfo.Visible = false; gridClass.Visible = false; } } else { pnlInfo.Visible = true; lblFormInfo.Text = GetString("EditForm.DocumentNotFound"); } } // Insert or update of a document else { // Display the form pnlEdit.Visible = true; // Try to get GroupID if group context exists int currentGroupId = ModuleCommands.CommunityGetCurrentGroupID(); btnDelete.Attributes.Add("style", "display: none;"); btnRefresh.Attributes.Add("style", "display: none;"); // CMSForm initialization formElem.NodeID = Node.NodeID; formElem.SiteName = SiteName; formElem.CultureCode = CultureCode; formElem.ValidationErrorMessage = ValidationErrorMessage; formElem.IsLiveSite = IsLiveSite; // Set group ID if group context exists formElem.GroupID = currentGroupId; // External editing is allowed for live site only if the permissions are checked or user is global administrator or for group context - user is group administrator formElem.AllowExternalEditing = !IsLiveSite || CheckPermissions || MembershipContext.AuthenticatedUser.IsGlobalAdministrator || MembershipContext.AuthenticatedUser.IsGroupAdministrator(currentGroupId); // Set the form mode if (NewDocument) { ci = DataClassInfoProvider.GetDataClassInfo(ClassID); if (ci == null) { throw new Exception(String.Format("[CMSAdminControls/EditForm.aspx]: Class ID '{0}' not found.", ClassID)); } string classDisplayName = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(ci.ClassDisplayName)); titleElem.TitleText = GetString("Content.NewTitle") + ": " + classDisplayName; // Set default template ID formElem.DefaultPageTemplateID = TemplateID > 0 ? TemplateID : ci.ClassDefaultPageTemplateID; // Set document owner formElem.OwnerID = OwnerID; formElem.FormMode = FormModeEnum.Insert; string newClassName = ci.ClassName; string newFormName = newClassName + ".default"; if (!String.IsNullOrEmpty(AlternativeFormName)) { // Set the alternative form full name formElem.AlternativeFormFullName = GetAltFormFullName(ci.ClassName); } if (newFormName.ToLowerCSafe() != formElem.FormName.ToLowerCSafe()) { formElem.FormName = newFormName; } } else if (NewCulture) { formElem.FormMode = FormModeEnum.InsertNewCultureVersion; // Default data document ID formElem.CopyDefaultDataFromDocumentId = CopyDefaultDataFromDocumentID; ci = DataClassInfoProvider.GetDataClassInfo(Node.NodeClassName); formElem.FormName = Node.NodeClassName + ".default"; if (!String.IsNullOrEmpty(AlternativeFormName)) { // Set the alternative form full name formElem.AlternativeFormFullName = GetAltFormFullName(ci.ClassName); } } else { formElem.FormMode = FormModeEnum.Update; ci = DataClassInfoProvider.GetDataClassInfo(Node.NodeClassName); formElem.FormName = String.Empty; if (!String.IsNullOrEmpty(AlternativeFormName)) { // Set the alternative form full name formElem.AlternativeFormFullName = GetAltFormFullName(ci.ClassName); } } // Allow the CMSForm formElem.StopProcessing = false; ReloadForm(); formElem.LoadForm(true); } } } // New culture version else { // Switch to new culture version mode DocumentManager.Mode = FormModeEnum.InsertNewCultureVersion; DocumentManager.NodeID = NodeID; DocumentManager.CultureCode = CultureCode; DocumentManager.SiteName = SiteName; if (Node != null) { // Offer a new culture creation pnlNewCulture.Visible = true; titleElem.TitleText = GetString("Content.NewCultureVersionTitle") + " (" + HTMLHelper.HTMLEncode(MembershipContext.AuthenticatedUser.PreferredCultureCode) + ")"; lblNewCultureInfo.Text = GetString("ContentNewCultureVersion.Info"); radCopy.Text = GetString("ContentNewCultureVersion.Copy"); radEmpty.Text = GetString("ContentNewCultureVersion.Empty"); radCopy.Attributes.Add("onclick", "ShowSelection();"); radEmpty.Attributes.Add("onclick", "ShowSelection()"); AddScript( "function ShowSelection() { \n" + " if (document.getElementById('" + radCopy.ClientID + "').checked) { document.getElementById('divCultures').style.display = 'block'; } \n" + " else { document.getElementById('divCultures').style.display = 'none'; } \n" + "} \n" ); btnOk.Text = GetString("ContentNewCultureVersion.Create"); // Load culture versions SiteInfo si = SiteInfoProvider.GetSiteInfo(Node.NodeSiteID); if (si != null) { lstCultures.Items.Clear(); DataSet nodes = TreeProvider.SelectNodes(si.SiteName, Node.NodeAliasPath, TreeProvider.ALL_CULTURES, false, null, null, null, 1, false); foreach (DataRow nodeCulture in nodes.Tables[0].Rows) { ListItem li = new ListItem(); li.Text = CultureInfoProvider.GetCultureInfo(nodeCulture["DocumentCulture"].ToString()).CultureName; li.Value = nodeCulture["DocumentID"].ToString(); lstCultures.Items.Add(li); } if (lstCultures.Items.Count > 0) { lstCultures.SelectedIndex = 0; } } } else { pnlInfo.Visible = true; lblFormInfo.Text = GetString("EditForm.DocumentNotFound"); } } } // Set flag that the form is loaded mFormLoaded = true; } }
public bool IsAtSynchronizedSite(RelationshipNameInfo relationshipName) { var siteId = SiteInfoProvider.GetSiteID(Settings.Sitename); return(RelationshipNameSiteInfo.Provider.Get(relationshipName.RelationshipNameId, siteId) != null); }
/// <summary> /// PageLoad event handler. /// </summary> protected void Page_Load(object sender, EventArgs e) { UniGridRelationship.Attributes.Add("AllowedPageTypes", AllowedPageTypes); UniGridRelationship.Attributes.Add("DisplayNameFormat", DisplayNameFormat); UniGridRelationship.Attributes.Add("ToolTipFormat", ToolTipFormat); // Object type cannot be defined in xml definition -> it would ignore code behind configuration UniGridRelationship.ObjectType = (IsAdHocRelationship) ? RelationshipInfo.OBJECT_TYPE_ADHOC : RelationshipInfo.OBJECT_TYPE; //UniGridRelationship.ObjectType = RelationshipInfo.OBJECT_TYPE_ADHOC; if (StopProcessing) { UniGridRelationship.StopProcessing = StopProcessing; return; } // Set tree node from Form object if ((TreeNode == null) && (Form != null) && (Form.EditedObject != null)) { var node = Form.EditedObject as TreeNode; if ((node != null) && (Form.Mode == FormModeEnum.Update)) { TreeNode = node; } else { ShowInformation(GetString("relationship.editdocumenterror")); } } if (TreeNode != null) { //InitUniGrid(); int nodeId = TreeNode.NodeID; // Add relationship name condition var condition = new WhereCondition() .WhereIn("RelationshipNameID", new IDQuery <RelationshipNameInfo>().Where(GetRelationshipNameCondition())); // Switch sides is disabled condition.WhereEquals(DefaultSide ? "RightNodeID" : "LeftNodeID", nodeId); if (!string.IsNullOrWhiteSpace(RelatedNodeSiteName)) { condition.Where(string.Format("{0} in (Select NodeID from View_CMS_Tree_Joined where NodeSiteID = {1})", (DefaultSide ? "LeftNodeID" : "RightNodeID"), SiteInfoProvider.GetSiteID(RelatedNodeSiteName))); } InitFilterVisibility(); UniGridRelationship.WhereCondition = condition.ToString(true); } else { UniGridRelationship.StopProcessing = true; UniGridRelationship.Visible = false; } if (RequestHelper.IsPostBack()) { string target = Request[Page.postEventSourceID]; if ((target != pnlUpdate.ClientID) && (target != pnlUpdate.UniqueID)) { return; } string action = Request[Page.postEventArgumentID]; if (string.IsNullOrEmpty(action)) { return; } switch (action.ToLowerInvariant()) { // Insert from 'Select document' dialog case "insertfromselectdocument": SaveRelationship(); break; } } else { bool inserted = QueryHelper.GetBoolean("inserted", false); if (inserted) { ShowConfirmation(GetString("relationship.wasadded")); } } if ( (!string.IsNullOrWhiteSpace(RelatedNodeSiteName) && !RelatedNodeSiteName.Equals(SiteContext.CurrentSiteName, StringComparison.InvariantCultureIgnoreCase) || (string.IsNullOrWhiteSpace(RelatedNodeSiteName) && SiteInfo.Provider.Get().Count > 1)) ) { ltrStyleHide.Visible = true; } else { ltrStyleHide.Visible = false; } }
private void SetWhereCondition() { // Check existence of CMS.BookingEvent dataclass if (DataClassInfoProvider.GetDataClassInfo("CMS.BookingEvent") != null) { // Filter site name string siteName = SiteName; if (siteName == String.Empty) { siteName = SiteContext.CurrentSiteName; } // If not show all if (siteName != TreeProvider.ALL_SITES) { gridElem.WhereCondition = "(NodeLinkedNodeID IS NULL AND NodeSiteID = " + SiteInfoProvider.GetSiteID(siteName) + ")"; } else { gridElem.WhereCondition = "NodeLinkedNodeID IS NULL"; } // Filter time interval if (EventScope == "all") { return; } string conditionOperator = (EventScope == "upcoming") ? ">=" : "<="; gridElem.WhereCondition = SqlHelper.AddWhereCondition(gridElem.WhereCondition, String.Format("EventDate {0} @Date", conditionOperator)); QueryDataParameters parameters = new QueryDataParameters(); parameters.Add("@Date", DateTime.Now); gridElem.QueryParameters = parameters; } else { // Document type with code name 'CMS.BookingEvent' does not exist ShowError(GetString("Events_List.NoBookingEventClass")); } }
public bool IsAtSynchronizedSite(DataClassInfo contentType) { var siteId = SiteInfoProvider.GetSiteID(Settings.Sitename); return(ClassSiteInfo.Provider.Get(contentType.ClassID, siteId) != null); }
/// <summary> /// Initializes common properties used for processing image. /// </summary> private void baseImageEditor_InitializeProperties() { // Process media file if (baseImageEditor.ImageType == ImageHelper.ImageTypeEnum.MediaFile) { // Get mediafile mfi = MediaFileInfo.Provider.Get(mediafileGuid, SiteInfoProvider.GetSiteID(CurrentSiteName)); // If file is not null if (mfi != null) { MediaLibraryInfo mli = MediaLibraryInfo.Provider.Get(mfi.FileLibraryID); if ((mli != null) && (MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(mli, "filemodify"))) { // Load media file thumbnail if (isPreview) { PreviewPath = MediaFileInfoProvider.GetPreviewFilePath(mfi); if (PreviewPath != null) { OldPreviewExt = Path.GetExtension(PreviewPath); try { // Get file contents from file system previewFile = File.ReadAllBytes(PreviewPath); } catch (Exception ex) { Service.Resolve <IEventLogService>().LogException("ImageEditor", "GetPreviewFile", ex); } if (previewFile != null) { baseImageEditor.ImgHelper = new ImageHelper(previewFile); } else { baseImageEditor.LoadingFailed = true; baseImageEditor.ShowError(GetString("img.errors.loading")); } } else { baseImageEditor.LoadingFailed = true; baseImageEditor.ShowError(GetString("img.errors.loading")); } } // Load media file else { mfi.FileBinary = MediaFileInfoProvider.GetFile(mfi, mli.LibraryFolder, CurrentSiteName); // Ensure metafile binary data if (mfi.FileBinary != null) { baseImageEditor.ImgHelper = new ImageHelper(mfi.FileBinary); } else { baseImageEditor.LoadingFailed = true; baseImageEditor.ShowError(GetString("img.errors.loading")); } } } else { baseImageEditor.LoadingFailed = true; baseImageEditor.ShowError(GetString("img.errors.filemodify")); } } else { baseImageEditor.LoadingFailed = true; baseImageEditor.ShowError(GetString("img.errors.loading")); } } // Check that image is in supported formats if ((!baseImageEditor.LoadingFailed) && (baseImageEditor.ImgHelper.ImageFormatToString() == null)) { baseImageEditor.LoadingFailed = true; baseImageEditor.ShowError(GetString("img.errors.format")); } // Disable editor if loading failed if (baseImageEditor.LoadingFailed) { Enabled = false; } }
protected void SetupControl() { if (StopProcessing) { listElem.Visible = false; return; } disabledModuleInfo.KeyScope = DisabledModuleScope.Both; disabledModuleInfo.SettingsKeys = "CMSEnableOnlineMarketing;CMSCMActivitiesEnabled"; listElem.Visible = true; listElem.ShowContactNameColumn = true; listElem.OrderBy = "ActivityCreated DESC"; string where = null; if (!String.IsNullOrEmpty(ActivityType)) { where = SqlHelper.AddWhereCondition(where, "ActivityType='" + SqlHelper.GetSafeQueryString(ActivityType, true) + "'"); } // Get site ID from site name string siteName = (SiteName != null ? SiteName.ToLowerCSafe() : ""); int siteId = -1; switch (siteName) { case "##all##": break; case "##currentsite##": siteId = SiteContext.CurrentSiteID; break; default: siteId = SiteInfoProvider.GetSiteID(siteName); break; } if (siteId != -1) { where = SqlHelper.AddWhereCondition(where, "ActivitySiteID=" + siteId); } // Get correct time interval int days = ValidationHelper.GetInteger(DateInterval, 0); DateTime dt = DateTimeHelper.GetDayStart(DateTime.Now); switch (days) { case -1: dt = DateTimeHelper.GetWeekStart(dt, CultureHelper.DefaultUICultureCode); break; case -2: dt = DateTimeHelper.GetMonthStart(dt); break; default: dt = dt.AddDays(-days); break; } where = SqlHelper.AddWhereCondition(where, "ActivityCreated >= '" + dt.ToString("s") + "'"); // "s" - ISO format (supported by DB regardless of culture) listElem.ShowSiteNameColumn = (siteId == -1); // Show site name column if activities from all sites are listed listElem.WhereCondition = where; if (!RequestHelper.IsPostBack()) { // Init page size for the first time only listElem.PageSize = PageSize; } }
/// <summary> /// Convert given status name to its ID for specified site. /// </summary> /// <param name="name">Code name of the internal status to be converted.</param> /// <param name="siteName">Name of the site to translate code name for.</param> protected override int GetID(string name, string siteName) { InternalStatusInfo status = InternalStatusInfo.Provider.Get(name, SiteInfoProvider.GetSiteID(siteName)); return((status != null) ? status.InternalStatusID : 0); }
/// <summary> /// Saves modified image data. /// </summary> /// <param name="name">Image name</param> /// <param name="extension">Image extension</param> /// <param name="mimetype">Image mimetype</param> /// <param name="title">Image title</param> /// <param name="description">Image description</param> /// <param name="binary">Image binary data</param> /// <param name="width">Image width</param> /// <param name="height">Image height</param> private void SaveImage(string name, string extension, string mimetype, string title, string description, byte[] binary, int width, int height) { // Process media file if (mfi == null) { mfi = MediaFileInfo.Provider.Get(mediafileGuid, SiteInfoProvider.GetSiteID(CurrentSiteName)); } if (mfi == null) { return; } var mli = MediaLibraryInfo.Provider.Get(mfi.FileLibraryID); if (mli == null) { return; } string path = Path.GetDirectoryName(DirectoryHelper.CombinePath(MediaLibraryInfoProvider.GetMediaLibraryFolderPath(mli.LibraryID), mfi.FilePath)); bool permissionsOK = DirectoryHelper.CheckPermissions(path, false, true, true, true); // Check file write permissions FileInfo file = FileInfo.New(MediaFileInfoProvider.GetMediaFilePath(mfi.FileLibraryID, mfi.FilePath)); if (file != null) { permissionsOK = permissionsOK && !file.IsReadOnly; } if (!permissionsOK) { baseImageEditor.ShowError(GetString("img.errors.filesystempermissions")); SavingFailed = true; return; } MediaFileInfo originalMfi = mfi.Clone(true); try { var site = SiteInfo.Provider.Get(mfi.FileSiteID); if (site == null) { throw new NullReferenceException("Site of media file not specified."); } // Ensure object version SynchronizationHelper.EnsureObjectVersion(mfi); if (isPreview && !String.IsNullOrEmpty(PreviewPath)) { // Save preview file only if it was modified if (binary != null) { string previewExt = !String.IsNullOrEmpty(extension) && (extension != OldPreviewExt) ? extension : OldPreviewExt; string previewName = Path.GetFileNameWithoutExtension(PreviewPath); string previewFolder = Path.EnsureForwardSlashes(DirectoryHelper.CombinePath(Path.GetDirectoryName(mfi.FilePath).TrimEnd('/'), MediaLibraryHelper.GetMediaFileHiddenFolder(site.SiteName))); // Delete old preview files with thumbnails MediaFileInfoProvider.DeleteMediaFilePreview(SiteContext.CurrentSiteName, mli.LibraryID, mfi.FilePath); MediaFileInfoProvider.DeleteMediaFilePreviewThumbnails(mfi); // Save preview file MediaFileInfoProvider.SaveFileToDisk(site.SiteName, mli.LibraryFolder, previewFolder, previewName, previewExt, mfi.FileGUID, binary, false, false); SynchronizationHelper.LogObjectChange(mfi, TaskTypeEnum.UpdateObject); } } else { if (!String.IsNullOrEmpty(mimetype)) { mfi.FileMimeType = mimetype; } mfi.FileTitle = title; mfi.FileDescription = description; if (width > 0) { mfi.FileImageWidth = width; } if (height > 0) { mfi.FileImageHeight = height; } if (binary != null) { mfi.FileBinary = binary; mfi.FileSize = binary.Length; } string newExt = null; string newName = null; if (!String.IsNullOrEmpty(extension)) { newExt = extension; } if (!String.IsNullOrEmpty(name)) { newName = name; } // If file name or extension changed move preview file and remove all ald thumbnails if (NameOrExtensionWasModified(newName, newExt)) { string fileName = (newName ?? mfi.FileName); string fileExt = (newExt ?? mfi.FileExtension); string newPath = MediaFileInfoProvider.GetMediaFilePath(mfi.FileLibraryID, DirectoryHelper.CombinePath(Path.GetDirectoryName(mfi.FilePath), fileName) + fileExt); // Rename file only if file with same name does not exsists if (File.Exists(newPath)) { baseImageEditor.ShowError(GetString("img.errors.fileexists")); SavingFailed = true; return; } // Ensure max length of file path if (newPath.Length >= 260) { throw new IOExceptions.PathTooLongException(); } // Remove old thumbnails MediaFileInfoProvider.DeleteMediaFileThumbnails(mfi); MediaFileInfoProvider.DeleteMediaFilePreviewThumbnails(mfi); // Move media file MediaFileInfoProvider.MoveMediaFile(site.SiteName, mli.LibraryID, mfi.FilePath, DirectoryHelper.CombinePath(Path.GetDirectoryName(mfi.FilePath), fileName) + fileExt); // Set new file name or extension mfi.FileName = fileName; mfi.FileExtension = fileExt; mfi.FileMimeType = MimeTypeHelper.GetMimetype(fileExt); // Ensure new binary if (binary != null) { mfi.FileBinary = binary; mfi.FileSize = binary.Length; } } else { // Remove original media file before save if the image was modified if (binary != null) { // Remove old thumbnails MediaFileInfoProvider.DeleteMediaFileThumbnails(mfi); string filePath = MediaFileInfoProvider.GetMediaFilePath(mfi.FileLibraryID, mfi.FilePath); if (File.Exists(filePath)) { File.Delete(filePath); } } } // Save new data mfi.EnsureUniqueFileName(false); MediaFileInfo.Provider.Set(mfi); } } catch (Exception e) { // Log exception Service.Resolve <IEventLogService>().LogException("ImageEditor", "Save file", e); baseImageEditor.ShowError(GetString("img.errors.processing"), tooltipText: e.Message); SavingFailed = true; // Save original media file info originalMfi.EnsureUniqueFileName(false); MediaFileInfo.Provider.Set(originalMfi); } }
/// <summary> /// Returns complete WHERE condition. /// </summary> protected WhereCondition GetCompleteWhereCondition() { string allRecords = UniSelector.US_ALL_RECORDS.ToString(); string customWhere = ValidationHelper.GetString(GetValue("WhereCondition"), ""); var where = new WhereCondition(); // Do not select product options and select only enabled products where.WhereNull("SKUOptionCategoryID").And().WhereTrue("SKUEnabled"); // Get products only with specified public status if (!string.IsNullOrEmpty(ProductPublicStatusName) && (ProductPublicStatusName != allRecords)) { int pStatusSiteID = ECommerceSettings.UseGlobalPublicStatus(SiteName) ? 0 : SiteInfoProvider.GetSiteID(SiteName); where.WhereEquals("SKUPublicStatusID", new IDQuery <PublicStatusInfo>("PublicStatusID").Where("ISNULL(PublicStatusSiteID, 0) = " + pStatusSiteID).And().WhereEquals("PublicStatusName", ProductPublicStatusName).TopN(1)); } // Get products only with specified internal status if (!string.IsNullOrEmpty(ProductInternalStatusName) && (ProductInternalStatusName != allRecords)) { int iStatusSiteID = ECommerceSettings.UseGlobalInternalStatus(SiteName) ? 0 : SiteInfoProvider.GetSiteID(SiteName); where.WhereEquals("SKUInternalStatusID", new IDQuery <InternalStatusInfo>("InternalStatusID").Where("ISNULL(InternalStatusSiteID, 0) = " + iStatusSiteID).And().WhereEquals("InternalStatusName", ProductInternalStatusName).TopN(1)); } // Get products only from specified department if (!string.IsNullOrEmpty(ProductDepartmentName) && (ProductDepartmentName != allRecords)) { DepartmentInfo dept = DepartmentInfoProvider.GetDepartmentInfo(ProductDepartmentName, SiteName); int departmentID = (dept != null) ? dept.DepartmentID : 0; where.WhereEquals("SKUDepartmentID", departmentID); } // Include user custom WHERE condition if (customWhere.Trim() != "") { where.Where(customWhere); } return(where); }