/// <summary> /// Click Event which will save a category /// // Creates a new page of the "CMS.MenuItem" page type /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnSave_Save(object sender, EventArgs e) { string categoryName = txtName.Text; string categroyDes = txtDescription.Text; try { if (!string.IsNullOrEmpty(categoryName)) { TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser); CMS.DocumentEngine.TreeNode parentPage = tree.SelectNodes().Path(folderpath).OnCurrentSite().Culture(DocumentContext.CurrentDocument.DocumentCulture).FirstObject; if (parentPage != null) { CMS.DocumentEngine.TreeNode newPage = CMS.DocumentEngine.TreeNode.New("KDA.ProductCategory", tree); newPage.DocumentName = categoryName; newPage.DocumentCulture = DocumentContext.CurrentDocument.DocumentCulture; newPage.SetValue("ProductCategoryTitle", categoryName); newPage.SetValue("ProductCategoryDescription", categroyDes); newPage.SetValue("Status", ValidationHelper.GetBoolean(ddlStatus.SelectedValue, false)); newPage.Insert(parentPage); lblSuccessMsg.Visible = true; lblFailureText.Visible = false; Response.Cookies["status"].Value = QueryStringStatus.Added; Response.Cookies["status"].HttpOnly = false; URLHelper.Redirect($"{CurrentDocument.Parent.DocumentUrlPath}?status={QueryStringStatus.Added}"); } else { lblFailureText.Visible = true; } } } catch (Exception ex) { EventLogProvider.LogException("CategroyCreateForm", "EXCEPTION", ex); } }
/// <summary> /// Binding programs based on campaign /// </summary> private void BindPrograms() { try { var campaign = CampaignProvider.GetCampaigns().Columns("CampaignID").WhereEquals("OpenCampaign", true).WhereEquals("NodeSiteID", CurrentSite.SiteID).FirstOrDefault(); if (ValidationHelper.GetInteger(campaign.GetValue("CampaignID"), default(int)) != default(int)) { var programs = ProgramProvider.GetPrograms().WhereEquals("NodeSiteID", CurrentSite.SiteID).WhereEquals("CampaignID", ValidationHelper.GetInteger(campaign.GetValue("CampaignID"), default(int))).Columns("ProgramName,ProgramID").Select(x => new Program { ProgramID = x.ProgramID, ProgramName = x.ProgramName }).ToList().OrderBy(y => y.ProgramName); if (programs != null) { ddlPrograms.DataSource = programs; ddlPrograms.DataTextField = "ProgramName"; ddlPrograms.DataValueField = "ProgramID"; ddlPrograms.DataBind(); } } } catch (Exception ex) { EventLogProvider.LogException("CMSWebParts_Kadena_Catalog_PrebuyProductsFilter", ex.Message, ex); } }
/// <summary> /// Appends the object property /// </summary> /// <param name="root">Root node</param> /// <param name="isPriorityTree">Flag indicating if the tree is a priority tree</param> /// <param name="hc">Object</param> /// <param name="col">Property name</param> private void AddProperty(TreeNode root, bool isPriorityTree, IHierarchicalObject hc, string col) { // Add the property try { // Disable license error when macro evaluation tries to load objects that are not included in current license using (new CMSActionContext { EmptyDataForInvalidLicense = true }) { EvaluationResult result = ContextResolver.GetObjectValue(hc, col, new EvaluationContext(ContextResolver, "")); // Append the child value AppendChild(root, col, result.Result, false, isPriorityTree); } } catch (Exception ex) { EventLogProvider.LogException("MacroTree", "EXPAND", ex); // Append the exception as child value AppendChild(root, col, ex, false, isPriorityTree); } }
public static string RegisterComponent(ContentType contentType, string fileName, int order = -1) { if (fileName.IsEmpty()) { return(string.Empty); } var assetLink = string.Empty; var dictionary = GetAssetDict(contentType); lock (dictionary) { if (dictionary.ContainsKey(fileName)) { return(string.Empty); } var staticAsset = CreateStaticAsset(fileName, order); if (string.IsNullOrWhiteSpace(staticAsset.Path)) { EventLogProvider.LogException("Frontend", "ASSETNOTFOUND", new Exception($"Entry point \"{fileName}\" not found!")); return(string.Empty); } dictionary.Add(fileName, staticAsset); if (contentType == ContentType.CSS) { assetLink = IsSameAssetsCacheCookie() ? string.Format(CssPatternRegular, staticAsset.Path) : InlineCSS(fileName); } if (contentType == ContentType.Svg) { assetLink = InlineSVG(fileName); } } return(assetLink); }
public void btnGetToken(Object sender, EventArgs e) { //Short term token gotten from front end login & approvals string token = hfToken.Value; string uri = "https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&fb_exchange_token=" + token + "&client_secret=" + FacebookClientSecret + "&redirect_uri=" + FacebookRedirectURI + "&client_id=" + FacebookAppID + "&code=" + FacebookAppID + "|" + FacebookClientSecret; JavaScriptSerializer ser = new JavaScriptSerializer(); try{ string long_token = GET(uri); tbLong.Text = long_token; //get the code using the long term token //string code_uri = "https://graph.facebook.com/oauth/client_code?" + long_token + "&client_secret=" + FacebookClientSecret + "&redirect_uri=" + FacebookRedirectURI + "&client_id=" + FacebookAppID; //string code_token_resp = GET(code_uri); //dynamic jresponse = ser.Deserialize<dynamic>(code_token_resp); //JObject jresponse = JObject.Parse(code_token_resp); //var code_token = jresponse["code"]; //tbCode.Text = code_token.ToString(); //Exchange for another long term token //string long2_uri = "https://graph.facebook.com/oauth/access_token?code=" + code_token.ToString() + "&client_id=" + FacebookAppID + "&redirect_uri=" + FacebookRedirectURI; //string long2_token_resp = GET(long2_uri); //JObject jresponse2 = JObject.Parse(long2_token_resp); //tbLong2.Text = jresponse2["access_token"].ToString(); } catch (Exception ex) { EventLogProvider.LogException("GetFacebookAccessToken", "btnGetToken ", ex); } }
protected void btnUpdateCRN_Click(object sender, EventArgs e) { try { int rCount = 0; var products = SKUInfoProvider.GetSKUs() .WhereEquals("SKUSiteID", SiteContext.CurrentSiteID); foreach (SKUInfo modifyProduct in products) { if (String.IsNullOrEmpty(modifyProduct.GetValue("SKUProductCustomerReferenceNumber", string.Empty))) { modifyProduct.SetValue("SKUProductCustomerReferenceNumber", modifyProduct.SKUNumber); SKUInfoProvider.SetSKUInfo(modifyProduct); rCount++; } } EventLogProvider.LogEvent(EventType.INFORMATION, "SKU Update", "UPDATECRN", eventDescription: "Update CRN with SKU"); lblUpdatedCRN.Text = string.Format("{0} Records moved to CRN", rCount); } catch (Exception ex) { EventLogProvider.LogException("ProductsSKUUpdate", "UpdateCRNRecords", ex, CurrentSite.SiteID, ex.Message); } }
protected void btnCheckout_Click(object sender, EventArgs e) { try { // Check permissions if (!WorkflowManager.CheckStepPermissions(Node, WorkflowActionEnum.Approve)) { DisableForm(); return; } VersionManager.EnsureVersion(Node, Node.IsPublished); // Check out the document VersionManager.CheckOut(Node); // Refresh tree if icon checked out should be displayed if (DocumentUIHelper.IsIconUsed(IconType.CheckedOut, SiteContext.CurrentSiteName)) { AddAfterActionScript(); } ReloadData(); versionsElem.ReloadData(); } catch (WorkflowException) { ShowError(GetString("EditContent.DocumentCannotCheckOut")); } catch (Exception ex) { // Log exception EventLogProvider.LogException("Content", "CHECKOUT", ex); ShowError(ex.Message); } }
/// <summary> /// Saves metadata and file name of metafile. /// </summary> /// <param name="newFileName">New metafile file name</param> /// <returns>Returns True if metafile was succesfully saved.</returns> private bool SaveMetaFile(string newFileName) { bool saved = false; MetaFileInfo metaFileInfo = InfoObject as MetaFileInfo; if (metaFileInfo != null) { try { // Set title and description metaFileInfo.MetaFileTitle = ObjectTitle; metaFileInfo.MetaFileDescription = ObjectDescription; // Set new file name if (!string.IsNullOrEmpty(newFileName)) { metaFileInfo.MetaFileName = newFileName + ObjectExtension; } // Save new metadata metaFileInfo.AllowPartialUpdate = true; MetaFileInfoProvider.SetMetaFileInfo(metaFileInfo); saved = true; LtlScript.Text = ScriptHelper.GetScript("RefreshMetaFile();"); } catch (Exception ex) { lblError.Text = GetString("metadata.errors.processing"); EventLogProvider.LogException("Metadata editor", "SAVEMETAFILE", ex); } } return(saved); }
/// <summary> /// Binds actions for admin /// </summary> /// <param name="initiated"></param> /// <param name="openCampaign"></param> /// <param name="closeCampaign"></param> /// <param name="gAdminNotified"></param> /// <param name="gAdminNotifiedAll"></param> /// <param name="productsExist"></param> /// <param name="program"></param> public void BindActionsForAdmin(bool initiated, bool openCampaign, bool closeCampaign, bool gAdminNotified, bool gAdminNotifiedAll, bool productsExist, Program program) { try { if (!initiated) { btnNotifyAdmin.Visible = true; btnNotifyAdmin.Enabled = false;; btnNotifyAdmin.CssClass = "disable btn-action"; btnNewProduct.Visible = true; btnNewProduct.Enabled = false; btnNewProduct.CssClass = "disable btn-action"; } else if (initiated && !openCampaign) { AdminActionsAfterCampaignInitiation(program, productsExist, gAdminNotified); } else if (openCampaign && !closeCampaign) { AdminActionsAfterCampaignOpen(program, productsExist, gAdminNotified, gAdminNotifiedAll); } else if (closeCampaign) { btnNotifyAdmin.Visible = true; btnNotifyAdmin.Enabled = false; btnNotifyAdmin.CssClass = "disable btn-action"; btnNewProduct.Visible = true; btnNewProduct.Enabled = false; btnNewProduct.CssClass = "disable btn-action"; } } catch (Exception ex) { EventLogProvider.LogException("CMSWebParts_Kadena_Campaign_Web_Form_CampaignProductsFilter", "BindActionsForAdmin", ex, CurrentSite.SiteID, ex.Message); } }
/// <summary> /// Saving the updated values in database /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnSave_Edit(object sender, EventArgs e) { string campaignName = Name.Text; string campaignDes = Description.Text; try { if (!string.IsNullOrEmpty(campaignName)) { var editPage = DIContainer.Resolve <IKenticoCampaignsProvider>().GetCampaign(campaignId); if (editPage != null) { editPage.DocumentName = campaignName; editPage.DocumentCulture = DocumentContext.CurrentDocument.DocumentCulture; editPage.SetValue("Name", campaignName); editPage.SetValue("Description", campaignDes); editPage.SetValue("StartDate", ValidationHelper.GetDate(txtStartDate.Text, DateTime.Now.Date)); editPage.SetValue("EndDate", ValidationHelper.GetDate(txtEndDate.Text, DateTime.Now.Date)); editPage.SetValue("FiscalYear", ddlFiscalYear.SelectedValue); editPage.SetValue("Status", ValidationHelper.GetString(ddlStatus.SelectedValue, "1") == "1" ? true : false); editPage.Update(); Response.Cookies["status"].Value = QueryStringStatus.Updated; Response.Cookies["status"].HttpOnly = false; URLHelper.Redirect($"{CurrentDocument.Parent.DocumentUrlPath}?status={QueryStringStatus.Updated}"); } else { lblFailureText.Visible = true; } } } catch (Exception ex) { EventLogProvider.LogException("CampaignCreateFormEdit", "EXCEPTION", ex); } }
private static ImageModel GetImageModel(Guid id) { try { var mediaFile = MediaFileInfoProvider.GetMediaFileInfo(id, SiteContext.CurrentSiteName); var url = MediaFileURLProvider.GetMediaFileUrl(mediaFile?.FileGUID ?? Guid.Empty, $"{mediaFile?.FileName}{mediaFile?.FileExtension}"); return(new ImageModel { Id = id, Title = mediaFile?.FileDescription.IfEmpty(mediaFile.FileName) ?? mediaFile?.FileDescription, Url = url, FileName = $"{mediaFile?.FileName}{mediaFile?.FileExtension}", FileExtension = mediaFile?.FileExtension.Replace(".", string.Empty), UploadDate = mediaFile?.FileCreatedWhen }); } catch (Exception ex) { EventLogProvider.LogException("MediaExtensions", "EXCEPTION", ex); return(null); } }
/// <summary> /// Gets where condition. /// </summary> public override string GetWhereCondition() { string tempVal = ValidationHelper.GetString(Value, null); // Only boolean value if (string.IsNullOrEmpty(tempVal) || !ValidationHelper.IsBoolean(tempVal)) { return(null); } try { string value = ValidationHelper.GetBoolean(tempVal, false) ? "1" : "0"; // Format where condition return(string.Format(WhereConditionFormat, FieldInfo.Name, value, "=")); } catch (Exception ex) { // Log exception EventLogProvider.LogException("BooleanFilter", "GetWhereCondition", ex); } return(null); }
/// <summary> /// Inserts user related business units /// </summary> /// <param name="BusinessUnits">all busieness units</param> /// <param name="UserID">user id</param> private void BindBusinessUnitsToUser(string BusinessUnits, int UserID) { try { DeleteUserBusinessUnits(UserID); var delimitBuinessUnits = BusinessUnits.Split(';'); foreach (var businessUnitID in delimitBuinessUnits) { if (!string.IsNullOrEmpty(businessUnitID) && IsBusinessUnitExisted(ValidationHelper.GetInteger(businessUnitID, 0), UserID)) { UserBusinessUnitsItem newBu = new UserBusinessUnitsItem() { UserID = UserID, BusinessUnitID = ValidationHelper.GetInteger(businessUnitID, 0) }; newBu.Insert(); } } } catch (Exception ex) { EventLogProvider.LogException("UsersList.ascx.cs", "BindBusinessUnitsToUser()", ex); } }
/// <summary> /// Binding brands based on program /// </summary> /// <param name="programID"></param> private void BindBrands(String programID = "0") { try { { var brand = CustomTableItemProvider.GetItems(BrandItem.CLASS_NAME) .Columns("BrandName,ItemID") .Select(x => new BrandItem { ItemID = x.Field <int>("ItemID"), BrandName = x.Field <string>("BrandName") }) .OrderBy(x => x.BrandName) .ToList(); ddlBrands.DataSource = brand; ddlBrands.DataTextField = "BrandName"; ddlBrands.DataValueField = "ItemID"; ddlBrands.DataBind(); ddlBrands.Items.Insert(0, new ListItem(ResHelper.GetString("Kadena.Catalog.SelectBrandText"), "0")); } } catch (Exception ex) { EventLogProvider.LogException("Binding brands based on program", ex.Message, ex); } }
/// <summary> /// Getting programs based on open campaign /// </summary> /// <param name="campaignID"></param> /// <returns></returns> public List <int> GetProgramIDs(int campaignID) { try { List <int> programIds = new List <int>(); var programs = ProgramProvider.GetPrograms() .WhereEquals("CampaignID", OpenCampaign.CampaignID) .Columns("ProgramID") .ToList(); if (!DataHelper.DataSourceIsEmpty(programs)) { foreach (var program in programs) { programIds.Add(program.ProgramID); } } return(programIds); } catch (Exception ex) { EventLogProvider.LogException("get program based on open campaign", ex.Message, ex); return(default(List <int>)); } }
/// <summary> /// Procedures which automatically imports the upgrade export package with all WebParts, Widgets, Reports and TimeZones. /// </summary> private static void UpgradeImportPackage() { // Import try { RequestStockHelper.Remove("CurrentDomain", true); var importSettings = new SiteImportSettings(MembershipContext.AuthenticatedUser) { DefaultProcessObjectType = ProcessObjectEnum.All, SourceFilePath = mUpgradePackagePath, WebsitePath = mWebsitePath }; using (var context = new CMSActionContext()) { context.DisableLogging(); context.CreateVersion = false; context.LogIntegration = false; ImportProvider.ImportObjectsData(importSettings); // Regenerate time zones TimeZoneInfoProvider.GenerateTimeZoneRules(); // Delete the files for separable modules which are not install and therefore not needed DeleteWebPartsOfUninstalledModules(); ImportMetaFiles(Path.Combine(mWebsitePath, "App_Data\\CMSTemp\\Upgrade")); } } catch (Exception ex) { EventLogProvider.LogException(EventLogSource, "IMPORT", ex); } }
/// <summary> /// deletes the address related brands /// </summary> /// <param name="addressID"></param> private void DeleteAddressBrands(int addressID) { try { if (addressID != default(int)) { var items = CustomTableItemProvider.GetItems <AddressBrandsItem>() .WhereEquals("AddressID", addressID) .Columns("BrandID,ItemID") .ToList(); if (items != null && items.Count > 0) { foreach (var item in items) { item.Delete(); } } } } catch (Exception ex) { EventLogProvider.LogException("CreateAddress.ascx.cs", "DeleteAddressBrands()", ex); } }
/// <summary> /// Restart windows services. /// </summary> protected void RestartServices(object sender = null, EventArgs args = null) { if (StopProcessing) { return; } // Resets values of counters try { WinServiceHelper.RestartService(null); // Log event EventLogProvider.LogEvent(EventType.INFORMATION, "System", "RESTARTWINSERVICES", GetString("Administration-System.WinServicesRestarted")); } catch (Exception ex) { EventLogProvider.LogException("WinServiceHelper", "RestartService", ex); } string url = URLHelper.UpdateParameterInUrl(RequestContext.CurrentURL, "lastaction", "WinServicesRestarted"); URLHelper.Redirect(url); }
/// <summary> /// Adds items to the cart /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void lnkAddToCart_Command(object sender, CommandEventArgs e) { try { ProductSKUID = ValidationHelper.GetInteger(e.CommandArgument, default(int)); hdnClickSKU.Value = ProductSKUID.ToString(); SKUInfo product = SKUInfoProvider.GetSKUInfo(ProductSKUID); if (product != null && ProductType == (int)ProductsType.GeneralInventory && (string.IsNullOrWhiteSpace(product.SKUNumber) || product.SKUNumber.Equals("00000"))) { Response.Cookies["status"].Value = QueryStringStatus.InvalidProduct; Response.Cookies["status"].HttpOnly = false; return; } dialog_Add_To_Cart.Attributes.Add("class", "dialog active"); btnClose.InnerText = CartCloseText; lblPopUpHeader.Text = ResHelper.GetString("KDA.AddToCart.Popup.HeaderText"); var hasBusinessUnit = CheckPersonHasBusinessUnit(); if (!DataHelper.DataSourceIsEmpty(product)) { switch (ProductType) { case (int)ProductsType.GeneralInventory: BindGeneralInventory(product, hasBusinessUnit); break; case (int)ProductsType.PreBuy: BindPreBuy(product, hasBusinessUnit); break; } } } catch (Exception ex) { EventLogProvider.LogException("Add items to cart", "lnkAddToCart_Click()", ex, CurrentSite.SiteID, ex.Message); } }
protected void btnDelete_Click(object sender, EventArgs e) { try { if (mErasureConfigurationControl.IsValid()) { IDictionary <string, object> configuration = new Dictionary <string, object>(StringComparer.InvariantCultureIgnoreCase); configuration = mErasureConfigurationControl.GetConfiguration(configuration); var identities = IdentityCollectorRegister.Instance.CollectIdentities(mDataSubjectIdentifiersFilter); PersonalDataEraserRegister.Instance.EraseData(identities, configuration); ShowConfirmation(GetString("dataprotection.app.deletedata.success"), true); } } catch (CheckDependenciesException ex) { var dependenciesCount = 10; var dependencyNames = ex.Object.GetDependenciesNames(topN: dependenciesCount); var formatString = GetString("dataprotection.app.deletedata.objecthasdependencies"); var message = String.Format(formatString, ex.Object.ObjectDisplayName, dependenciesCount); var description = String.Format( "{0}<br/>{1}", GetString("unigrid.objectlist"), dependencyNames.Select(item => ResHelper.LocalizeString(item, null, true)).Join("<br/>")); EventLogProvider.LogException("Data protection", "DELETEPERSONALDATA", ex); ShowError(message, description); } catch (Exception ex) { EventLogProvider.LogException("Data protection", "DELETEPERSONALDATA", ex); ShowError(GetString("dataprotection.app.deletedata.fail")); } }
protected void btnSearch_Click(object sender, EventArgs e) { try { if (mDataSubjectIdentifiersFilterControl.IsValid()) { IDictionary <string, object> dataSubjectIdentifiersFilter = new Dictionary <string, object>(StringComparer.InvariantCultureIgnoreCase); dataSubjectIdentifiersFilter = mDataSubjectIdentifiersFilterControl.GetFilter(dataSubjectIdentifiersFilter); var personalData = GetPersonalData(dataSubjectIdentifiersFilter); RenderPersonalData(personalData); mDataSubjectIdentifiersFilter = JsonConvert.SerializeObject(dataSubjectIdentifiersFilter, new JsonSerializerSettings { StringEscapeHandling = StringEscapeHandling.EscapeHtml }); } } catch (Exception ex) { EventLogProvider.LogException("Data protection", "COLLECTDATA", ex); ShowError(ex.Message); } }
private void LoadDataSubjectIdentifiersFilterControl() { string virtualPath = DataProtectionControlsRegister.Instance.GetDataSubjectIdentifiersFilterControl(); try { if (virtualPath != null) { mDataSubjectIdentifiersFilterControl = (DataSubjectIdentifiersFilterControl)Page.LoadUserControl(virtualPath); mDataSubjectIdentifiersFilterControl.EnableViewState = true; mDataSubjectIdentifiersFilterControl.ID = "dataSubjectIdentifiersFilter"; mDataSubjectIdentifiersFilterControl.ShortID = "dsif"; plcDataSubjectIdentifiersFilter.Controls.Add(mDataSubjectIdentifiersFilterControl); } } catch (Exception ex) { btnSearch.Visible = false; EventLogProvider.LogException("Data protection", "FILTERCONTROLLOAD", ex, additionalMessage: $"Could not load control '{virtualPath}'."); ShowError($"Could not load control '{virtualPath}'. Please see the Event log for more details."); } }
/// <summary> /// Method to log exceptions to event log. /// </summary> /// <param name="eventCode">Code of event during which exception occurred</param> /// <param name="ex">Exception</param> private void LogException(string eventCode, Exception ex) { // Log exception to event log EventLogProvider.LogException("Object recycle bin", eventCode, ex); }
/// <summary> /// Tests SharePoint connection using configuration currently filled in the form. /// </summary> private void TestConnection() { try { ISharePointSiteService siteService = SharePointServices.GetService <ISharePointSiteService>(GetConnectionData()); siteService.GetSiteUrl(); DisplayConnectionStatus(GetString("sharepoint.testconnection.success")); } catch (SharePointServiceFactoryNotSupportedException) { // No service factory for given SharePoint version DisplayConnectionStatus(GetString("sharepoint.versionnotsupported"), false); } catch (SharePointServiceNotSupportedException) { // No ISiteService implementation for SharePoint version DisplayConnectionStatus(GetString("sharepoint.testconnectionnotsupported"), false); } catch (SharePointConnectionNotSupportedException) { // The ISiteService implementation rejected connection data DisplayConnectionStatus(GetString("sharepoint.invalidconfiguration"), false); } catch (SharePointCCSDKException ex) { var message = string.Format(GetString("sharepoint.ccsdk.idcrl.msoidclilerror"), DocumentationHelper.GetDocumentationTopicUrl("sharepoint_online_connecting")); DisplayConnectionStatus(message, false, true); EventLogProvider.LogException("SharePoint", "TESTCONNECTION", ex); } catch (WebException ex) { if (ex.Status == WebExceptionStatus.ProtocolError) { // Connection established, but response indicates error condition if (ex.Message.Contains("401")) { // Unauthorized. DisplayConnectionStatus(GetString("sharepoint.protocolerror.unauthorized"), false); } else if (ex.Message.Contains("404")) { // SharePoint instance not found on given URL DisplayConnectionStatus(GetString("sharepoint.protocolerror.notfound"), false); } else { // Some other protocol error DisplayConnectionStatus(GetString("sharepoint.protocolerror"), false); } } else if (ex.Status == WebExceptionStatus.NameResolutionFailure) { // Given site URL does not have a resolution DisplayConnectionStatus(GetString("sharepoint.nameresolutionfailure"), false); } else { DisplayConnectionStatus(GetString("sharepoint.unknownerror"), false); EventLogProvider.LogException("SharePoint", "TESTCONNECTION", ex); } } catch (Exception ex) { DisplayConnectionStatus(GetString("sharepoint.unknownerror"), false); EventLogProvider.LogException("SharePoint", "TESTCONNECTION", ex); } }
/// <summary> /// Deletes variants is asynchronous control. /// </summary> protected void Delete(object parameters) { bool variantWasDisabled = false; try { // Use special action contexts to turn off unnecessary actions using (ECommerceActionContext eCommerceContext = new ECommerceActionContext()) { eCommerceContext.TouchParent = false; eCommerceContext.SetLowestPriceToParent = false; // Delete all variants if ((WhatEnum)ValidationHelper.GetInteger(drpWhat.SelectedIndex, -1) == WhatEnum.AllVariants) { var variants = VariantHelper.GetVariants(ProductID); foreach (SKUInfo variant in variants) { // Set flag when variant was disabled due to dependencies variantWasDisabled |= !DeleteVariant(variant); } } // Delete selected variants else { List <string> variantsToDelete = ugVariants.SelectedItems; foreach (string variantId in variantsToDelete) { var variantInfo = SKUInfoProvider.GetSKUInfo(ValidationHelper.GetInteger(variantId, 0)); if ((variantInfo != null) && (variantInfo.SKUParentSKUID == ProductID)) { // Set flag when variant was disabled due to dependencies variantWasDisabled |= !DeleteVariant(variantInfo); } } } } // Save variant to update parent SKULastModified a SKUPrice properties DataSet productVariants = VariantHelper.GetVariants(ProductID); if (!DataHelper.DataSourceIsEmpty(productVariants)) { SKUInfo variantInfo = new SKUInfo(productVariants.Tables[0].Rows[0]); variantInfo.Generalized.SetObject(); } } catch (Exception ex) { CurrentError = GetString("com.product.deleteerror"); EventLogProvider.LogException("Variant listing", "DELETEVARIANT", ex); } ugVariants.ClearSelectedItems(); if (variantWasDisabled) { CurrentWarning = GetString("com.product.edit.disablevariant"); } }
/// <summary> /// OK click handler (Proceed registration). /// </summary> protected void btnOK_Click(object sender, EventArgs e) { if (PortalContext.IsDesignMode(PortalContext.ViewMode) || (HideOnCurrentPage) || (!IsVisible)) { // Do not process } else { String siteName = SiteContext.CurrentSiteName; #region "Banned IPs" // Ban IP addresses which are blocked for registration if (!BannedIPInfoProvider.IsAllowed(siteName, BanControlEnum.Registration)) { ShowError(GetString("banip.ipisbannedregistration")); return; } #endregion #region "Check Email & password" string[] siteList = { siteName }; // If AssignToSites field set if (!String.IsNullOrEmpty(AssignToSites)) { siteList = AssignToSites.Split(';'); } // Check whether another user with this user name (which is effectively email) does not exist UserInfo ui = UserInfoProvider.GetUserInfo(txtEmail.Text); SiteInfo si = SiteContext.CurrentSite; UserInfo siteui = UserInfoProvider.GetUserInfo(UserInfoProvider.EnsureSitePrefixUserName(txtEmail.Text, si)); if ((ui != null) || (siteui != null)) { ShowError(GetString("Webparts_Membership_RegistrationForm.UserAlreadyExists").Replace("%%name%%", HTMLHelper.HTMLEncode(txtEmail.Text))); return; } // Check whether password is same if (passStrength.Text != txtConfirmPassword.Text) { ShowError(GetString("Webparts_Membership_RegistrationForm.PassworDoNotMatch")); return; } if ((PasswordMinLength > 0) && (passStrength.Text.Length < PasswordMinLength)) { ShowError(String.Format(GetString("Webparts_Membership_RegistrationForm.PasswordMinLength"), PasswordMinLength)); return; } if (!passStrength.IsValid()) { ShowError(AuthenticationHelper.GetPolicyViolationMessage(SiteContext.CurrentSiteName)); return; } if ((!txtEmail.IsValid()) || (txtEmail.Text.Length > EMAIL_MAX_LENGTH)) { ShowError(String.Format(GetString("Webparts_Membership_RegistrationForm.EmailIsNotValid"), EMAIL_MAX_LENGTH)); return; } #endregion #region "Captcha" // Check if captcha is required and verify captcha text if (DisplayCaptcha && !scCaptcha.IsValid()) { // Display error message if catcha text is not valid ShowError(GetString("Webparts_Membership_RegistrationForm.captchaError")); return; } #endregion #region "User properties" var userEmail = txtEmail.Text.Trim(); ui = new UserInfo(); ui.PreferredCultureCode = ""; ui.Email = userEmail; ui.FirstName = txtFirstName.Text.Trim(); ui.LastName = txtLastName.Text.Trim(); ui.FullName = UserInfoProvider.GetFullName(ui.FirstName, String.Empty, ui.LastName); ui.MiddleName = ""; ui.UserMFRequired = chkUseMultiFactorAutentization.Checked; // User name as put by user (no site prefix included) var plainUserName = userEmail; ui.UserName = plainUserName; // Check if the given email can be used as user name if (!ValidationHelper.IsUserName(plainUserName)) { ShowError(String.Format(GetString("Webparts_Membership_RegistrationForm.UserNameNotValid"), HTMLHelper.HTMLEncode(plainUserName))); return; } // Ensure site prefixes if (UserInfoProvider.UserNameSitePrefixEnabled(siteName)) { ui.UserName = UserInfoProvider.EnsureSitePrefixUserName(plainUserName, si); } ui.Enabled = EnableUserAfterRegistration; ui.UserURLReferrer = CookieHelper.GetValue(CookieName.UrlReferrer); ui.UserCampaign = Service <ICampaignService> .Entry().CampaignCode; ui.SiteIndependentPrivilegeLevel = UserPrivilegeLevelEnum.None; ui.UserSettings.UserRegistrationInfo.IPAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; ui.UserSettings.UserRegistrationInfo.Agent = HttpContext.Current.Request.UserAgent; // Check whether confirmation is required bool requiresConfirmation = SettingsKeyInfoProvider.GetBoolValue(siteName + ".CMSRegistrationEmailConfirmation"); bool requiresAdminApprove = false; if (!requiresConfirmation) { // If confirmation is not required check whether administration approval is required requiresAdminApprove = SettingsKeyInfoProvider.GetBoolValue(siteName + ".CMSRegistrationAdministratorApproval"); if (requiresAdminApprove) { ui.Enabled = false; ui.UserSettings.UserWaitingForApproval = true; } } else { // EnableUserAfterRegistration is overridden by requiresConfirmation - user needs to be confirmed before enable ui.Enabled = false; } // Set user's starting alias path if (!String.IsNullOrEmpty(StartingAliasPath)) { ui.UserStartingAliasPath = MacroResolver.ResolveCurrentPath(StartingAliasPath); } #endregion #region "Reserved names" // Check for reserved user names like administrator, sysadmin, ... if (UserInfoProvider.NameIsReserved(siteName, plainUserName)) { ShowError(GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(Functions.GetFormattedUserName(ui.UserName, true)))); return; } if (UserInfoProvider.NameIsReserved(siteName, ui.UserNickName)) { ShowError(GetString("Webparts_Membership_RegistrationForm.UserNameReserved").Replace("%%name%%", HTMLHelper.HTMLEncode(ui.UserNickName))); return; } #endregion #region "License limitations" string errorMessage = String.Empty; UserInfoProvider.CheckLicenseLimitation(ui, ref errorMessage); if (!String.IsNullOrEmpty(errorMessage)) { ShowError(errorMessage); return; } #endregion // Check whether email is unique if it is required if (!UserInfoProvider.IsEmailUnique(userEmail, siteList, 0)) { ShowError(GetString("UserInfo.EmailAlreadyExist")); return; } // Set password UserInfoProvider.SetPassword(ui, passStrength.Text); #region "Welcome Emails (confirmation, waiting for approval)" bool error = false; EmailTemplateInfo template = null; string emailSubject = null; // Send welcome message with username and password, with confirmation link, user must confirm registration if (requiresConfirmation) { template = EmailTemplateProvider.GetEmailTemplate("RegistrationConfirmation", siteName); emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.RegistrationConfirmationEmailSubject")); } // Send welcome message with username and password, with information that user must be approved by administrator else if (SendWelcomeEmail) { if (requiresAdminApprove) { template = EmailTemplateProvider.GetEmailTemplate("Membership.RegistrationWaitingForApproval", siteName); emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.RegistrationWaitingForApprovalSubject")); } // Send welcome message with username and password, user can logon directly else { template = EmailTemplateProvider.GetEmailTemplate("Membership.Registration", siteName); emailSubject = EmailHelper.GetSubject(template, GetString("RegistrationForm.RegistrationSubject")); } } if (template != null) { // Create relation between contact and user. This ensures that contact will be correctly recognized when user approves registration (if approval is required) int contactId = ModuleCommands.OnlineMarketingGetCurrentContactID(); if (contactId > 0) { ModuleCommands.OnlineMarketingCreateRelation(ui.UserID, MembershipType.CMS_USER, contactId); } // Email message EmailMessage email = new EmailMessage(); email.EmailFormat = EmailFormatEnum.Default; email.Recipients = ui.Email; email.From = SettingsKeyInfoProvider.GetValue(siteName + ".CMSNoreplyEmailAddress"); email.Subject = emailSubject; try { var resolver = MembershipResolvers.GetMembershipRegistrationResolver(ui, AuthenticationHelper.GetRegistrationApprovalUrl(ApprovalPage, ui.UserGUID, siteName, NotifyAdministrator)); EmailSender.SendEmailWithTemplateText(siteName, email, template, resolver, true); } catch (Exception ex) { EventLogProvider.LogException("E", "RegistrationForm - SendEmail", ex); error = true; } } // If there was some error, user must be deleted if (error) { ShowError(GetString("RegistrationForm.UserWasNotCreated")); // Email was not send, user can't be approved - delete it UserInfoProvider.DeleteUser(ui); return; } #endregion #region "Administrator notification email" // Notify administrator if enabled and e-mail confirmation is not required if (!requiresConfirmation && NotifyAdministrator && (FromAddress != String.Empty) && (ToAddress != String.Empty)) { EmailTemplateInfo mEmailTemplate; if (SettingsKeyInfoProvider.GetBoolValue(siteName + ".CMSRegistrationAdministratorApproval")) { mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.Approve", siteName); } else { mEmailTemplate = EmailTemplateProvider.GetEmailTemplate("Registration.New", siteName); } if (mEmailTemplate == null) { // Log missing e-mail template EventLogProvider.LogEvent(EventType.ERROR, "RegistrationForm", "GetEmailTemplate", eventUrl: RequestContext.RawURL); } else { EmailMessage message = new EmailMessage(); message.EmailFormat = EmailFormatEnum.Default; message.From = EmailHelper.GetSender(mEmailTemplate, FromAddress); message.Recipients = ToAddress; message.Subject = GetString("RegistrationForm.EmailSubject"); try { MacroResolver resolver = MembershipResolvers.GetRegistrationResolver(ui); EmailSender.SendEmailWithTemplateText(siteName, message, mEmailTemplate, resolver, false); } catch { EventLogProvider.LogEvent(EventType.ERROR, "Membership", "RegistrationEmail"); } } } #endregion #region "Web analytics" // Track successful registration conversion if (TrackConversionName != String.Empty) { if (AnalyticsHelper.AnalyticsEnabled(siteName) && !AnalyticsHelper.IsIPExcluded(siteName, RequestContext.UserHostAddress)) { // Log conversion HitLogProvider.LogConversions(siteName, LocalizationContext.PreferredCultureCode, TrackConversionName, 0, ConversionValue); } } // Log registered user if confirmation is not required if (!requiresConfirmation) { AnalyticsHelper.LogRegisteredUser(siteName, ui); } #endregion #region "On-line marketing - activity" // Log registered user if confirmation is not required if (!requiresConfirmation) { MembershipActivityLogger.LogRegistration(ui.UserName, DocumentContext.CurrentDocument); // Log login activity if (ui.Enabled) { MembershipActivityLogger.LogLogin(ui.UserName, DocumentContext.CurrentDocument); } } #endregion #region "Roles & authentication" string[] roleList = AssignRoles.Split(';'); foreach (string sn in siteList) { // Add new user to the current site UserInfoProvider.AddUserToSite(ui.UserName, sn); foreach (string roleName in roleList) { if (!String.IsNullOrEmpty(roleName)) { String s = roleName.StartsWith(".", StringComparison.Ordinal) ? "" : sn; // Add user to desired roles if (RoleInfoProvider.RoleExists(roleName, s)) { UserInfoProvider.AddUserToRole(ui.UserName, roleName, s); } } } } if (DisplayMessage.Trim() != String.Empty) { pnlForm.Visible = false; lblText.Visible = true; lblText.Text = DisplayMessage; } else { if (ui.Enabled) { AuthenticationHelper.AuthenticateUser(ui.UserName, true); } if (RedirectToURL != String.Empty) { URLHelper.Redirect(UrlResolver.ResolveUrl(RedirectToURL)); } else if (QueryHelper.GetString("ReturnURL", "") != String.Empty) { string url = QueryHelper.GetString("ReturnURL", ""); // Do url decode url = Server.UrlDecode(url); // Check that url is relative path or hash is ok if (url.StartsWith("~", StringComparison.Ordinal) || url.StartsWith("/", StringComparison.Ordinal) || QueryHelper.ValidateHash("hash", "aliaspath")) { URLHelper.Redirect(UrlResolver.ResolveUrl(url)); } // Absolute path with wrong hash else { URLHelper.Redirect(AdministrationUrlHelper.GetErrorPageUrl("dialogs.badhashtitle", "dialogs.badhashtext")); } } } #endregion lblError.Visible = false; } }
/// <summary> /// This function will send the email via SendGrid. /// </summary> /// <param name="kMessage">MailMessage - Message object to send</param> protected void SendSendGridEmail(MailMessage kMessage) { try { StringBuilder sb = new StringBuilder(); sb.Append("Date:"); sb.AppendLine(); sb.Append(DateTime.Now.ToString()); sb.AppendLine(); // Create the email object first, then add the properties. var sgMessage = new SendGridMessage(); // Add the message properties. sgMessage.From = new MailAddress(kMessage.From.ToString()); sb.Append("From:"); sb.AppendLine(); sb.Append(sgMessage.From.Address); sb.AppendLine(); // Add multiple addresses to the To field. sb.Append("To:"); sb.AppendLine(); foreach (MailAddress address in kMessage.To) { sgMessage.AddTo(address.Address); sb.Append(address.Address + ";"); } sb.AppendLine(); sgMessage.Subject = kMessage.Subject; sb.Append("Subject:"); sb.AppendLine(); sb.Append(sgMessage.Subject); sb.AppendLine(); // HTML & plain-text if (kMessage.AlternateViews.Count > 0) { foreach (AlternateView view in kMessage.AlternateViews) { // Position must be reset first if (view.ContentStream.CanSeek) { view.ContentStream.Position = 0; } using (StreamWrapper wrappedStream = StreamWrapper.New(view.ContentStream)) { using (StreamReader reader = StreamReader.New(wrappedStream)) { if (view.ContentType.MediaType == MediaTypeNames.Text.Html) { sgMessage.Html = reader.ReadToEnd(); } else if (view.ContentType.MediaType == MediaTypeNames.Text.Plain) { sgMessage.Text = reader.ReadToEnd(); } } } } } sb.Append("Body:"); if (ValidationHelper.GetString(sgMessage.Html, "") != "") { sb.Append(sgMessage.Html); } else { sb.Append(sgMessage.Text); } sb.AppendLine(); //Handle any attachments sb.Append("Attachments:"); sb.AppendLine(); foreach (Attachment attachment in kMessage.Attachments) { sgMessage.AddAttachment(attachment.ContentStream, attachment.Name); sb.Append(attachment.Name); sb.AppendLine(); } //Enable click tracking sgMessage.EnableClickTracking(true); // Create credentials, specifying your user name and password. var credentials = new NetworkCredential("[SendGridLogin]", "[SendGridPassword]"); // Create an Web transport for sending email. var transportWeb = new Web(credentials); // Send the email. transportWeb.Deliver(sgMessage); //Log the email details to the Event Log EventLogProvider.LogInformation("SendSendGridEmail", "EMAIL SENT", ValidationHelper.GetString(sb, "")); } catch (Exception ex) { EventLogProvider.LogException("SendSendGridEmail", "EXCEPTION", ex); } }
private void HandleError(Exception exception) { SalesForceError.Report(exception); EventLogProvider.LogException("Salesforce.com Connector", "MappingEditorPage", exception); }
/// <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) { LoadInfos(); // Save image data depending to image type switch (baseImageEditor.ImageType) { // Process attachment case ImageHelper.ImageTypeEnum.Attachment: if (ai != null) { // Save new data try { // Get the node TreeNode node = DocumentHelper.GetDocument(ai.AttachmentDocumentID, baseImageEditor.Tree); // Check Create permission when saving temporary attachment, check Modify permission else NodePermissionsEnum permissionToCheck = (ai.AttachmentFormGUID == Guid.Empty) ? NodePermissionsEnum.Modify : NodePermissionsEnum.Create; // Check permission if (MembershipContext.AuthenticatedUser.IsAuthorizedPerDocument(node, permissionToCheck) != AuthorizationResultEnum.Allowed) { baseImageEditor.ShowError(GetString("attach.actiondenied")); SavingFailed = true; return; } if (!IsNameUnique(name, extension)) { baseImageEditor.ShowError(GetString("img.namenotunique")); SavingFailed = true; return; } // Ensure automatic check-in/ check-out bool useWorkflow = false; bool autoCheck = false; WorkflowManager workflowMan = WorkflowManager.GetInstance(baseImageEditor.Tree); if (node != null) { // Get workflow info WorkflowInfo wi = workflowMan.GetNodeWorkflow(node); // Check if the document uses workflow if (wi != null) { useWorkflow = true; autoCheck = !wi.UseCheckInCheckOut(CurrentSiteName); } // Check out the document if (autoCheck) { VersionManager.CheckOut(node, node.IsPublished, true); VersionHistoryID = node.DocumentCheckedOutVersionHistoryID; } // Workflow has been lost, get published attachment if (useWorkflow && (VersionHistoryID == 0)) { ai = AttachmentInfoProvider.GetAttachmentInfo(ai.AttachmentGUID, CurrentSiteName); } // If extension changed update CMS.File extension if ((node.NodeClassName.ToLowerCSafe() == "cms.file") && (node.DocumentExtensions != extension)) { // Update document extensions if no custom are used if (!node.DocumentUseCustomExtensions) { node.DocumentExtensions = extension; } node.SetValue("DocumentType", extension); DocumentHelper.UpdateDocument(node, baseImageEditor.Tree); } } if (ai != null) { // Test all parameters to empty values and update new value if available if (name != "") { if (!name.EndsWithCSafe(extension)) { ai.AttachmentName = name + extension; } else { ai.AttachmentName = name; } } if (extension != "") { ai.AttachmentExtension = extension; } if (mimetype != "") { ai.AttachmentMimeType = mimetype; } ai.AttachmentTitle = title; ai.AttachmentDescription = description; if (binary != null) { ai.AttachmentBinary = binary; ai.AttachmentSize = binary.Length; } if (width > 0) { ai.AttachmentImageWidth = width; } if (height > 0) { ai.AttachmentImageHeight = height; } // Ensure object ai.MakeComplete(true); if (VersionHistoryID > 0) { VersionManager.SaveAttachmentVersion(ai, VersionHistoryID); } else { AttachmentInfoProvider.SetAttachmentInfo(ai); // Log the synchronization and search task for the document if (node != null) { // Update search index for given document if (DocumentHelper.IsSearchTaskCreationAllowed(node)) { SearchTaskInfoProvider.CreateTask(SearchTaskTypeEnum.Update, TreeNode.OBJECT_TYPE, SearchFieldsConstants.ID, node.GetSearchID(), node.DocumentID); } DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, baseImageEditor.Tree); } } // Check in the document if ((autoCheck) && (VersionManager != null) && (VersionHistoryID > 0) && (node != null)) { VersionManager.CheckIn(node, null); } } } catch (Exception ex) { baseImageEditor.ShowError(GetString("img.errors.processing"), tooltipText: ex.Message); EventLogProvider.LogException("Image editor", "SAVEIMAGE", ex); SavingFailed = true; } } break; case ImageHelper.ImageTypeEnum.PhysicalFile: if (!String.IsNullOrEmpty(filePath)) { var currentUser = MembershipContext.AuthenticatedUser; if ((currentUser != null) && currentUser.IsGlobalAdministrator) { try { string physicalPath = Server.MapPath(filePath); string newPath = physicalPath; // Write binary data to the disk File.WriteAllBytes(physicalPath, binary); // Handle rename of the file if (!String.IsNullOrEmpty(name)) { newPath = DirectoryHelper.CombinePath(Path.GetDirectoryName(physicalPath), name); } if (!String.IsNullOrEmpty(extension)) { string oldExt = Path.GetExtension(physicalPath); newPath = newPath.Substring(0, newPath.Length - oldExt.Length) + extension; } // Move the file if (newPath != physicalPath) { File.Move(physicalPath, newPath); } } catch (Exception ex) { baseImageEditor.ShowError(GetString("img.errors.processing"), tooltipText: ex.Message); EventLogProvider.LogException("Image editor", "SAVEIMAGE", ex); SavingFailed = true; } } else { baseImageEditor.ShowError(GetString("img.errors.rights")); SavingFailed = true; } } break; // Process metafile case ImageHelper.ImageTypeEnum.Metafile: if (mf != null) { if (UserInfoProvider.IsAuthorizedPerObject(mf.MetaFileObjectType, mf.MetaFileObjectID, PermissionsEnum.Modify, CurrentSiteName, MembershipContext.AuthenticatedUser)) { try { // Test all parameters to empty values and update new value if available if (name.CompareToCSafe("") != 0) { if (!name.EndsWithCSafe(extension)) { mf.MetaFileName = name + extension; } else { mf.MetaFileName = name; } } if (extension.CompareToCSafe("") != 0) { mf.MetaFileExtension = extension; } if (mimetype.CompareToCSafe("") != 0) { mf.MetaFileMimeType = mimetype; } mf.MetaFileTitle = title; mf.MetaFileDescription = description; if (binary != null) { mf.MetaFileBinary = binary; mf.MetaFileSize = binary.Length; } if (width > 0) { mf.MetaFileImageWidth = width; } if (height > 0) { mf.MetaFileImageHeight = height; } // Save new data MetaFileInfoProvider.SetMetaFileInfo(mf); if (RefreshAfterAction) { if (String.IsNullOrEmpty(externalControlID)) { baseImageEditor.LtlScript.Text = ScriptHelper.GetScript("Refresh();"); } else { baseImageEditor.LtlScript.Text = ScriptHelper.GetScript(String.Format("InitRefresh({0}, false, false, '{1}', 'refresh')", ScriptHelper.GetString(externalControlID), mf.MetaFileGUID)); } } } catch (Exception ex) { baseImageEditor.ShowError(GetString("img.errors.processing"), tooltipText: ex.Message); EventLogProvider.LogException("Image editor", "SAVEIMAGE", ex); SavingFailed = true; } } else { baseImageEditor.ShowError(GetString("img.errors.rights")); SavingFailed = true; } } break; } }
/// <summary> /// Reload data. /// </summary> public override void ReloadData(bool forceLoad) { // Load value info object ReportValueInfo rvi = ValueInfo; if (rvi == null) { return; } ri = ReportInfoProvider.GetReportInfo(rvi.ValueReportID); if (ri == null) { return; } // Check security settings if (!(CheckReportAccess(ri) && CheckEmailModeSubscription(ri, ValidationHelper.GetBoolean(ValueInfo.ValueSettings["SubscriptionEnabled"], true)))) { Visible = false; return; } // Prepare query attributes QueryIsStoredProcedure = rvi.ValueQueryIsStoredProcedure; QueryText = rvi.ValueQuery; // Init parameters InitParameters(ri.ReportParameters); // Init macro resolver InitResolver(); DataSet ds = null; // Ensure report item name for caching if (String.IsNullOrEmpty(ReportItemName)) { ReportItemName = String.Format("{0};{1}", ri.ReportName, rvi.ValueName); } try { // Load data ds = LoadData(); } catch (Exception ex) { // Display error message, if data load fail lblError.Visible = true; lblError.Text = "Error loading the data: " + ex.Message; EventLogProvider.LogException("Report value", "E", ex); } string value; // If data source or result is empty, send an empty dataset if (DataHelper.DataSourceIsEmpty(ds) || string.IsNullOrEmpty(value = GetReportValue(ds, rvi))) { if (EmailMode && SendOnlyNonEmptyDataSource) { Visible = false; } return; } if (EmailMode) { ltlEmail.Text = HTMLHelper.HTMLEncode(ResolveMacros(value)); ltlEmail.Visible = true; menuCont.Visible = false; } else { lblValue.Text = HTMLHelper.HTMLEncode(ResolveMacros(value)); } }