protected void Page_Load(object sender, EventArgs e)
    {
        // Check the site
        if (CurrentSiteName == "")
        {
            throw new Exception("[GetSharePointFile.aspx]: Site not running.");
        }

        int cacheMinutes = CacheMinutes;

        // Try to get data from cache
        using (var cs = new CachedSection<CMSOutputSharePointFile>(ref outputFile, cacheMinutes, true, null, "getsharepointfile", Request.QueryString))
        {
            if (cs.LoadData)
            {
                // Process the file
                ProcessAttachment();

                // Ensure the cache settings
                if (cs.Cached)
                {
                    // Check the file size for caching
                    if ((outputFile != null) && (outputFile.OutputData != null))
                    {
                        // Do not cache if too big file which would be stored in memory
                        if (!CacheHelper.CacheImageAllowed(CurrentSiteName, outputFile.OutputData.Length))
                        {
                            cacheMinutes = largeFilesCacheMinutes;
                        }
                    }

                    // Cache the data
                    cs.CacheMinutes = cacheMinutes;
                }

                cs.Data = outputFile;
            }
        }

        // Send the data
        SendFile(outputFile);
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        // Check the site
        if (string.IsNullOrEmpty(CurrentSiteName))
        {
            throw new Exception("[GetCSS.aspx]: Site not running.");
        }

        newsletterTemplateName = QueryHelper.GetString("newslettertemplatename", string.Empty);
        string cacheKey = string.Format("getnewslettercss|{0}|{1}", SiteContext.CurrentSiteName, newsletterTemplateName);

        // Try to get data from cache
        using (var cs = new CachedSection<CMSOutputResource>(ref outputFile, CacheMinutes, true, cacheKey))
        {
            if (cs.LoadData)
            {
                // Process the file
                ProcessStylesheet();

                // Ensure the cache settings
                if ((outputFile != null) && cs.Cached)
                {
                    // Add cache dependency
                    var cd = CacheHelper.GetCacheDependency(new[] { "newsletter.emailtemplate|byname|" + newsletterTemplateName.ToLowerCSafe() });

                    // Cache the data
                    cs.CacheDependency = cd;
                }

                cs.Data = outputFile;
            }
        }

        if (outputFile != null)
        {
            // Send the data
            SendFile(outputFile);
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        DebugHelper.SetContext("GetAvatar");

        // Prepare the cache key
        fileGuid = QueryHelper.GetGuid("avatarguid", Guid.Empty);

        // Try get guid from routed URL
        if (fileGuid == Guid.Empty)
        {
            fileGuid = ValidationHelper.GetGuid(RouteData.Values["avatarGuid"], Guid.Empty);
            if (fileGuid != Guid.Empty)
            {
                MaxSideSize = ValidationHelper.GetInteger(RouteData.Values["maxSideSize"], 0);
            }
        }

        int cacheMinutes = CacheMinutes;

        // Try to get data from cache
        using (var cs = new CachedSection<CMSOutputAvatar>(ref outputFile, cacheMinutes, true, null, "getavatar", GetBaseCacheKey(), Request.QueryString))
        {
            if (cs.LoadData)
            {
                // Process the file
                ProcessFile();

                // Ensure the cache settings
                if (cs.Cached)
                {
                    // Add cache dependency
                    CMSCacheDependency cd = null;
                    if (outputFile != null)
                    {
                        if (outputFile.Avatar != null)
                        {
                            cd = CacheHelper.GetCacheDependency(outputFile.Avatar.GetDependencyCacheKeys());

                            // Do not cache if too big file which would be stored in memory
                            if ((outputFile.Avatar != null) && !CacheHelper.CacheImageAllowed(CurrentSiteName, outputFile.Avatar.AvatarFileSize) && !AvatarInfoProvider.StoreFilesInFileSystem())
                            {
                                cacheMinutes = largeFilesCacheMinutes;
                            }
                        }
                    }

                    if ((cd == null) && (cacheMinutes > 0))
                    {
                        // Set default dependency based on GUID
                        cd = GetCacheDependency(new List<string> { "avatarfile|" + fileGuid.ToString().ToLowerCSafe() });
                    }

                    // Cache the data
                    cs.CacheMinutes = cacheMinutes;
                    cs.CacheDependency = cd;
                }

                cs.Data = outputFile;
            }
        }

        // Send the data
        SendFile(outputFile);

        DebugHelper.ReleaseContext();
    }
    /// <summary>
    /// Processes the specified file and returns the data to the output stream.
    /// </summary>
    /// <param name="attachmentGuid">Attachment guid</param>
    protected void ProcessFile(Guid attachmentGuid)
    {
        AttachmentInfo atInfo = null;

        bool requiresData = true;

        // Check if it is necessary to load the file data
        if (useClientCache && IsLiveSite && AllowClientCache)
        {
            // If possibly cached by client, do not load data (may not be sent)
            string ifModifiedString = Request.Headers["If-Modified-Since"];
            if (ifModifiedString != null)
            {
                requiresData = false;
            }
        }

        // If output data available from cache, do not require loading the data
        byte[] cachedData = GetCachedOutputData();
        if (cachedData != null)
        {
            requiresData = false;
        }

        // Get AttachmentInfo object
        if (!IsLiveSite)
        {
            // Not livesite mode - get latest version
            if (node != null)
            {
                atInfo = DocumentHelper.GetAttachment(node, attachmentGuid, TreeProvider, true);
            }
            else
            {
                atInfo = DocumentHelper.GetAttachment(attachmentGuid, TreeProvider, CurrentSiteName);
            }
        }
        else
        {
            if (!requiresData || AttachmentInfoProvider.StoreFilesInFileSystem(CurrentSiteName))
            {
                // Do not require data from DB - Not necessary or available from file system
                atInfo = AttachmentInfoProvider.GetAttachmentInfoWithoutBinary(attachmentGuid, CurrentSiteName);
            }
            else
            {
                // Require data from DB - Stored in DB
                atInfo = AttachmentInfoProvider.GetAttachmentInfo(attachmentGuid, CurrentSiteName);
            }

            // If attachment not found,
            if (allowLatestVersion && ((atInfo == null) || (latestForHistoryId > 0) || (atInfo.AttachmentDocumentID == latestForDocumentId)))
            {
                // Get latest version
                if (node != null)
                {
                    atInfo = DocumentHelper.GetAttachment(node, attachmentGuid, TreeProvider, true);
                }
                else
                {
                    atInfo = DocumentHelper.GetAttachment(attachmentGuid, TreeProvider, CurrentSiteName);
                }

                // If not attachment for the required document, do not return
                if ((atInfo.AttachmentDocumentID != latestForDocumentId) && (latestForHistoryId == 0))
                {
                    atInfo = null;
                }
                else
                {
                    mIsLatestVersion = true;
                }
            }
        }

        if (atInfo != null)
        {
            // Temporary attachment is always latest version
            if (atInfo.AttachmentFormGUID != Guid.Empty)
            {
                mIsLatestVersion = true;
            }

            // Check if current mimetype is allowed
            if (!CheckRequiredMimeType(atInfo))
            {
                return;
            }

            bool checkPublishedFiles = AttachmentInfoProvider.CheckPublishedFiles(CurrentSiteName);
            bool checkFilesPermissions = AttachmentInfoProvider.CheckFilesPermissions(CurrentSiteName);

            // Get the document node
            if ((node == null) && (checkPublishedFiles || checkFilesPermissions))
            {
                // Try to get data from cache
                using (CachedSection<TreeNode> cs = new CachedSection<TreeNode>(ref node, CacheMinutes, !allowLatestVersion, null, "getfilenodebydocumentid", atInfo.AttachmentDocumentID))
                {
                    if (cs.LoadData)
                    {
                        // Get the document
                        node = TreeProvider.SelectSingleDocument(atInfo.AttachmentDocumentID, false);

                        // Cache the document
                        CacheNode(cs, node);
                    }
                }
            }

            bool secured = false;
            if ((node != null) && checkFilesPermissions)
            {
                secured = (node.IsSecuredNode == 1);

                // Check secured pages
                if (secured)
                {
                    URLRewriter.CheckSecuredAreas(CurrentSiteName, false, ViewMode);
                }
                if (node.RequiresSSL == 1)
                {
                    URLRewriter.RequestSecurePage(false, node.RequiresSSL, ViewMode, CurrentSiteName);
                }

                // Check permissions
                bool checkPermissions = false;
                switch (URLRewriter.CheckPagePermissions(CurrentSiteName))
                {
                    case PageLocationEnum.All:
                        checkPermissions = true;
                        break;

                    case PageLocationEnum.SecuredAreas:
                        checkPermissions = secured;
                        break;
                }

                // Check the read permission for the page
                if (checkPermissions)
                {
                    if (CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Read) == AuthorizationResultEnum.Denied)
                    {
                        URLHelper.Redirect(URLRewriter.AccessDeniedPageURL(CurrentSiteName));
                    }
                }
            }

            bool resizeImage = (ImageHelper.IsImage(atInfo.AttachmentExtension) && AttachmentInfoProvider.CanResizeImage(atInfo, Width, Height, MaxSideSize));

            // If the file should be redirected, redirect the file
            if (!mIsLatestVersion && IsLiveSite && SettingsKeyProvider.GetBoolValue(CurrentSiteName + ".CMSRedirectFilesToDisk"))
            {
                if (AttachmentInfoProvider.StoreFilesInFileSystem(CurrentSiteName))
                {
                    string path = null;
                    if (!resizeImage)
                    {
                        path = AttachmentInfoProvider.GetFilePhysicalURL(CurrentSiteName, atInfo.AttachmentGUID.ToString(), atInfo.AttachmentExtension);
                    }
                    else
                    {
                        int[] newDim = ImageHelper.EnsureImageDimensions(Width, Height, MaxSideSize, atInfo.AttachmentImageWidth, atInfo.AttachmentImageHeight);
                        path = AttachmentInfoProvider.GetFilePhysicalURL(CurrentSiteName, atInfo.AttachmentGUID.ToString(), atInfo.AttachmentExtension, newDim[0], newDim[1]);
                    }

                    // If path is valid, redirect
                    if (path != null)
                    {
                        // Check if file exists
                        string filePath = Server.MapPath(path);
                        if (File.Exists(filePath))
                        {
                            outputFile = NewOutputFile();
                            outputFile.IsSecured = secured;
                            outputFile.RedirectTo = path;
                            outputFile.Attachment = atInfo;
                        }
                    }
                }
            }

            // Get the data
            if ((outputFile == null) || (outputFile.Attachment == null))
            {
                outputFile = NewOutputFile(atInfo, null);
                outputFile.Width = Width;
                outputFile.Height = Height;
                outputFile.MaxSideSize = MaxSideSize;
                outputFile.SiteName = CurrentSiteName;
                outputFile.Resized = resizeImage;

                // Load the data if required
                if (requiresData)
                {
                    // Try to get the physical file, if not latest version
                    if (!mIsLatestVersion)
                    {
                        EnsurePhysicalFile(outputFile);
                    }
                    bool loadData = string.IsNullOrEmpty(outputFile.PhysicalFile);

                    // Load data if necessary
                    if (loadData)
                    {
                        if (atInfo.AttachmentBinary != null)
                        {
                            // Load from the attachment
                            outputFile.LoadData(atInfo.AttachmentBinary);
                        }
                        else
                        {
                            // Load from the disk
                            byte[] data = AttachmentInfoProvider.GetFile(atInfo, CurrentSiteName);
                            outputFile.LoadData(data);
                        }

                        // Save data to the cache, if not latest version
                        if (!mIsLatestVersion && (CacheMinutes > 0))
                        {
                            SaveOutputDataToCache(outputFile.OutputData, GetOutputDataDependency(outputFile.Attachment));
                        }
                    }
                }
                else if (cachedData != null)
                {
                    // Load the cached data if available
                    outputFile.OutputData = cachedData;
                }
            }

            if (outputFile != null)
            {
                outputFile.IsSecured = secured;

                // Add node data
                if (node != null)
                {
                    outputFile.AliasPath = node.NodeAliasPath;
                    outputFile.CultureCode = node.DocumentCulture;
                    outputFile.FileNode = node;

                    // Set the file validity
                    if (IsLiveSite && !mIsLatestVersion && checkPublishedFiles)
                    {
                        outputFile.ValidFrom = ValidationHelper.GetDateTime(node.GetValue("DocumentPublishFrom"), DateTime.MinValue);
                        outputFile.ValidTo = ValidationHelper.GetDateTime(node.GetValue("DocumentPublishTo"), DateTime.MaxValue);

                        // Set the published flag
                        outputFile.IsPublished = node.IsPublished;
                    }
                }
            }
        }
    }
    /// <summary>
    /// Handles the document caching actions.
    /// </summary>
    /// <param name="cs">Cached section</param>
    /// <param name="node">Document node</param>
    protected void CacheNode(CachedSection<TreeNode> cs, TreeNode node)
    {
        if (node != null)
        {
            // Load the security settings
            EnsureSecuritySettings(node);

            // Save to the cache
            if (cs.Cached)
            {
                cs.CacheDependency = GetNodeDependency(node);
            }
        }
        else
        {
            // Do not cache in case not cached
            cs.CacheMinutes = 0;
        }

        cs.Data = node;
    }
Ejemplo n.º 6
0
    protected void InitNewsletterSelector()
    {
        // Show/hide newsletter list
        plcNwsList.Visible = NewsletterName.EqualsCSafe("nwsletuserchoose", true);

        if (plcNwsList.Visible)
        {
            chooseMode = true;

            if ((!ExternalUse || !RequestHelper.IsPostBack()) && (chklNewsletters.Items.Count == 0))
            {
                DataSet ds = null;

                // Try to get data from cache
                using (var cs = new CachedSection<DataSet>(ref ds, CacheMinutes, true, CacheItemName, "newslettersubscription", SiteContext.CurrentSiteName))
                {
                    if (cs.LoadData)
                    {
                        // Get the data
                        ds = NewsletterInfoProvider.GetNewslettersForSite(SiteContext.CurrentSiteID).OrderBy("NewsletterDisplayName").Columns("NewsletterDisplayName", "NewsletterName");

                        // Add data to the cache
                        if (cs.Cached)
                        {
                            // Prepare cache dependency
                            cs.CacheDependency = CacheHelper.GetCacheDependency("newsletter.newsletter|all");
                        }

                        cs.Data = ds;
                    }
                }

                if (!DataHelper.DataSourceIsEmpty(ds))
                {
                    ListItem li = null;
                    string displayName = null;

                    // Fill checkbox list with newsletters
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        // Get localized string
                        displayName = ResHelper.LocalizeString(ValidationHelper.GetString(dr["NewsletterDisplayName"], string.Empty));

                        li = new ListItem(HTMLHelper.HTMLEncode(displayName), ValidationHelper.GetString(dr["NewsletterName"], string.Empty));
                        chklNewsletters.Items.Add(li);
                    }
                }
            }
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        DebugHelper.SetContext("GetMediaFile");

        // Load the site name
        LoadSiteName();

        // Check the site
        if (string.IsNullOrEmpty(CurrentSiteName))
        {
            throw new Exception("[GetMediaFile.aspx]: Site not running.");
        }

        int cacheMinutes = CacheMinutes;

        // Try to get data from cache
        using (CachedSection<CMSOutputMediaFile> cs = new CachedSection<CMSOutputMediaFile>(ref outputFile, cacheMinutes, true, null, "getmediafile", CurrentSiteName, CacheHelper.GetBaseCacheKey(true, false), Request.QueryString))
        {
            if (cs.LoadData)
            {
                // Process the file
                ProcessFile();

                // Ensure the cache settings
                if (cs.Cached)
                {
                    // Prepare the cache dependency
                    CacheDependency cd = null;
                    if (outputFile != null)
                    {
                        if (outputFile.MediaFile != null)
                        {
                            // Do not cache too big files
                            if ((outputFile.MediaFile != null) && !CacheHelper.CacheImageAllowed(CurrentSiteName, (int)outputFile.MediaFile.FileSize))
                            {
                                cacheMinutes = largeFilesCacheMinutes;
                            }

                            // Set dependency on this particular file
                            if (cacheMinutes > 0)
                            {
                                string[] dependencies = MediaFileInfoProvider.GetDependencyCacheKeys(outputFile.MediaFile, Preview);
                                cd = CacheHelper.GetCacheDependency(dependencies);
                            }
                        }
                    }

                    if ((cd == null) && (cacheMinutes > 0))
                    {
                        // Set default cache dependency by file GUID
                        cd = CacheHelper.GetCacheDependency(new string[] { "mediafile|" + fileGuid.ToString().ToLower(), "mediafilepreview|" + fileGuid.ToString().ToLower() });
                    }

                    // Cache the data
                    cs.CacheMinutes = cacheMinutes;
                    cs.CacheDependency = cd;
                    cs.Data = outputFile;
                }
            }
        }

        // Send the data
        SendFile(outputFile);

        DebugHelper.ReleaseContext();
    }
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            if (!String.IsNullOrEmpty(TransformationName))
            {
                repTopContributors.ItemTemplate = CMSAbstractDataProperties.LoadTransformation(this, TransformationName);
                repTopContributors.HideControlForZeroRows = HideControlForZeroRows;
                repTopContributors.ZeroRowsText = ZeroRowsText;

                DataSet ds = null;

                // Try to get data from cache
                using (var cs = new CachedSection<DataSet>(ref ds, CacheMinutes, true, CacheItemName, "forumtopcontributors", SiteContext.CurrentSiteName, WhereCondition, SelectTopN))
                {
                    if (cs.LoadData)
                    {
                        // Get the data
                        ds = GetData();

                        // Save to the cache
                        if (cs.Cached)
                        {
                            // Save to the cache
                            cs.CacheDependency = GetCacheDependency();
                        }

                        cs.Data = ds;
                    }
                }

                repTopContributors.DataSource = ds;

                if (!DataHelper.DataSourceIsEmpty(repTopContributors.DataSource))
                {
                    repTopContributors.DataBind();
                }
            }
        }
    }
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            mLayoutSeparator = DisplayLayout.ToLower() == "vertical" ? "<br />" : " ";

            DataSet ds = null;

            // Try to get data from cache
            using (CachedSection<DataSet> cs = new CachedSection<DataSet>(ref ds, this.CacheMinutes, true, this.CacheItemName, "languageselection", CMSContext.CurrentSiteName))
            {
                if (cs.LoadData)
                {
                    // Get the data
                    ds = CultureInfoProvider.GetSiteCultures(CMSContext.CurrentSiteName);

                    // Save to the cache
                    if (cs.Cached)
                    {
                        cs.CacheDependency = CacheHelper.GetCacheDependency(new string[] { "cms.culturesite|all", "cms.culture|all" });
                        cs.Data = ds;
                    }
                }
            }

            if (!DataHelper.DataSourceIsEmpty(ds) && (ds.Tables[0].Rows.Count > 1))
            {
                // Collection of available documents in culture
                Dictionary<string, string> documentCultures = null;
                // Check whether hiding is required or URLs should be generated with lang prefix
                if (this.HideUnavailableCultures || this.UseURLsWithLangPrefix)
                {
                    string cacheItemName = this.CacheItemName;
                    if (!String.IsNullOrEmpty(cacheItemName))
                    {
                        cacheItemName += "prefix";
                    }

                    // Current page info
                    PageInfo currentPageInfo = CMSContext.CurrentPageInfo;

                    // Try to get data from cache
                    using (CachedSection<Dictionary<string, string>> cs = new CachedSection<Dictionary<string, string>>(ref documentCultures, this.CacheMinutes, true, cacheItemName, "languageselectionprefix", CMSContext.CurrentSiteName, currentPageInfo.NodeAliasPath.ToLower()))
                    {
                        if (cs.LoadData)
                        {
                            // Initialize tree provider object
                            TreeProvider tp = new TreeProvider(CMSContext.CurrentUser);
                            tp.FilterOutDuplicates = false;
                            tp.CombineWithDefaultCulture = false;

                            // Get all language versions
                            DataSet culturesDs = tp.SelectNodes(CMSContext.CurrentSiteName, "/%", TreeProvider.ALL_CULTURES, false, null, "NodeID = " + currentPageInfo.NodeId, null, -1, true, 0, "DocumentCulture, DocumentUrlPath");

                            // Create culture/UrlPath collection
                            if (!DataHelper.DataSourceIsEmpty(culturesDs))
                            {
                                documentCultures = new Dictionary<string, string>();
                                foreach (DataRow dr in culturesDs.Tables[0].Rows)
                                {
                                    string docCulture = ValidationHelper.GetString(dr["DocumentCulture"], String.Empty).ToLower();
                                    string urlPath = ValidationHelper.GetString(dr["DocumentUrlPath"], String.Empty);
                                    documentCultures.Add(docCulture, urlPath);
                                }
                            }

                            // Add to the cache
                            if (cs.Cached)
                            {
                                cs.CacheDependency = this.GetCacheDependency();
                                cs.Data = documentCultures;
                            }
                        }
                    }
                }

                // Render the cultures
                ltlHyperlinks.Text = "";

                int count = 0;
                int rows = ds.Tables[0].Rows.Count;

                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    string cultureCode = dr["CultureCode"].ToString();
                    string cultureShortName = dr["CultureShortName"].ToString();
                    string cultureAlias = Convert.ToString(dr["CultureAlias"]);

                    bool documentCultureExists = true;

                    // Check whether exists document in specified culture
                    if ((documentCultures != null) && (this.HideUnavailableCultures))
                    {
                        documentCultureExists = documentCultures.ContainsKey(cultureCode.ToLower());
                    }

                    if (documentCultureExists)
                    {
                        if (!((HideCurrentCulture) && (String.Compare(CMSContext.CurrentDocument.DocumentCulture, cultureCode, true) == 0)))
                        {
                            // Get flag icon URL
                            imgFlagIcon = UIHelper.GetFlagIconUrl(this.Page, cultureCode, "16x16");

                            string url = null;
                            string lang = cultureCode;
                            // Check whether culture alias is defined and if so use it
                            if (!String.IsNullOrEmpty(cultureAlias))
                            {
                                lang = cultureAlias;
                            }

                            // Get specific url with language prefix
                            if (this.UseURLsWithLangPrefix && documentCultures != null)
                            {
                                string urlPath = String.Empty;
                                if (documentCultures.ContainsKey(cultureCode.ToLower()))
                                {
                                    urlPath = documentCultures[cultureCode.ToLower()];
                                }
                                url = TreePathUtils.GetUrl(CMSContext.CurrentAliasPath, urlPath, CMSContext.CurrentSiteName, lang);
                                url += URLHelper.GetQuery(URLHelper.CurrentURL);
                                url = URLHelper.RemoveParameterFromUrl(url, URLHelper.LanguageParameterName);
                                url = URLHelper.RemoveParameterFromUrl(url, URLHelper.AliasPathParameterName);
                            }
                            // Get URL with lang parameter
                            else
                            {
                                // Build current URL
                                url = URLHelper.CurrentURL;
                                url = URLHelper.RemoveParameterFromUrl(url, URLHelper.LanguageParameterName);
                                url = URLHelper.RemoveParameterFromUrl(url, URLHelper.AliasPathParameterName);
                                url = URLHelper.AddParameterToUrl(url, URLHelper.LanguageParameterName, lang);
                            }

                            if (ShowCultureNames)
                            {
                                // Add flag icon before the link text
                                ltlHyperlinks.Text += "<img src=\"" + imgFlagIcon + "\" alt=\"" + HTMLHelper.HTMLEncode(cultureShortName) + "\" />";
                                ltlHyperlinks.Text += "<a href=\"" + url + "\">";
                                ltlHyperlinks.Text += HTMLHelper.HTMLEncode(cultureShortName);

                                // Set surrounding div css class
                                selectionClass = "languageSelectionWithCultures";
                            }
                            else
                            {
                                ltlHyperlinks.Text += "<a href=\"" + url + "\">" + "<img src=\"" + imgFlagIcon + "\" alt=\"" + HTMLHelper.HTMLEncode(cultureShortName) + "\" />";

                                // Set surrounding div css class
                                selectionClass = "languageSelection";
                            }

                            count++;

                            // Check last item
                            if (count == rows)
                            {
                                ltlHyperlinks.Text += "</a>";
                            }
                            else
                            {
                                ltlHyperlinks.Text += "</a>" + Separator + mLayoutSeparator;
                            }
                        }
                    }
                }
            }
            else
            {
                // Hide if less than two cultures
                Visible = false;
            }

            if (string.IsNullOrEmpty(selectionClass))
            {
                ltrDivOpen.Text = "<div>";
            }
            else
            {
                ltrDivOpen.Text = "<div class=\"" + selectionClass + "\">";
            }
            ltrDivClose.Text = "</div>";

            // Check if RTL hack must be applied
            if (CultureHelper.IsPreferredCultureRTL())
            {
                ltrDivOpen.Text += "<span style=\"visibility:hidden;\">a</span>";
            }
        }
    }
Ejemplo n.º 10
0
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do not process
        }
        else
        {
            string culture = CMSContext.PreferredCultureCode;

            mSeparator = DisplayLayout.ToLower() == "vertical" ? "<br />" : " ";

            DataSet ds = null;

            // Try to get data from cache
            using (CachedSection <DataSet> cs = new CachedSection <DataSet>(ref ds, this.CacheMinutes, true, this.CacheItemName, "languageselection", CMSContext.CurrentSiteName))
            {
                if (cs.LoadData)
                {
                    // Get the data
                    ds = CultureInfoProvider.GetSiteCultures(CMSContext.CurrentSiteName);

                    // Add to the cache
                    if (cs.Cached)
                    {
                        cs.CacheDependency = this.GetCacheDependency();
                        cs.Data            = ds;
                    }
                }
            }

            if (!DataHelper.DataSourceIsEmpty(ds) && (ds.Tables[0].Rows.Count > 1))
            {
                // Collection of available documents in culture
                Dictionary <string, string> documentCultures = null;
                // Check whether hiding is required or URLs should be generated with lang prefix
                if (this.HideUnavailableCultures || this.UseURLsWithLangPrefix)
                {
                    string cacheItemName = this.CacheItemName;
                    if (!String.IsNullOrEmpty(cacheItemName))
                    {
                        cacheItemName += "prefix";
                    }

                    // Current page info
                    PageInfo currentPageInfo = CMSContext.CurrentPageInfo;

                    // Try to get data from cache
                    using (CachedSection <Dictionary <string, string> > cs = new CachedSection <Dictionary <string, string> >(ref documentCultures, this.CacheMinutes, true, cacheItemName, "languageselectionprefix", CMSContext.CurrentSiteName, currentPageInfo.NodeAliasPath.ToLower()))
                    {
                        if (cs.LoadData)
                        {
                            // Initialize tree provider object
                            TreeProvider tp = new TreeProvider(CMSContext.CurrentUser);
                            tp.FilterOutDuplicates       = false;
                            tp.CombineWithDefaultCulture = false;

                            // Get all language versions
                            DataSet culturesDs = tp.SelectNodes(CMSContext.CurrentSiteName, "/%", TreeProvider.ALL_CULTURES, false, null, "NodeID = " + currentPageInfo.NodeId, null, -1, true, 0, "DocumentCulture, DocumentUrlPath");

                            // Create culture/UrlPath collection
                            if (!DataHelper.DataSourceIsEmpty(culturesDs))
                            {
                                documentCultures = new Dictionary <string, string>();
                                foreach (DataRow dr in culturesDs.Tables[0].Rows)
                                {
                                    string docCulture = ValidationHelper.GetString(dr["DocumentCulture"], String.Empty).ToLower();
                                    string urlPath    = ValidationHelper.GetString(dr["DocumentUrlPath"], String.Empty);
                                    documentCultures.Add(docCulture, urlPath);
                                }
                            }

                            // Add to the cache
                            if (cs.Cached)
                            {
                                cs.CacheDependency = CacheHelper.GetCacheDependency(new string[] { "cms.culturesite|all", "cms.culture|all", "node|" + CurrentSiteName.ToLower() + "|" + currentPageInfo.NodeAliasPath.ToLower() });
                                cs.Data            = documentCultures;
                            }
                        }
                    }
                }

                // Render the cultures
                ltlHyperlinks.Text = "";
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    string cultureCode      = Convert.ToString(dr["CultureCode"]);
                    string cultureAlias     = Convert.ToString(dr["CultureAlias"]);
                    string cultureShortName = Convert.ToString(dr["CultureShortName"]);
                    // Indicates whether exists document in specific culture
                    bool documentCultureExists = true;

                    // Check whether exists document in specified culture
                    if ((documentCultures != null) && (this.HideUnavailableCultures))
                    {
                        documentCultureExists = documentCultures.ContainsKey(cultureCode.ToLower());
                    }

                    if (documentCultureExists)
                    {
                        if (!(HideCurrentCulture && (String.Compare(CMSContext.CurrentDocument.DocumentCulture, cultureCode, true) == 0)))
                        {
                            if (String.Compare(culture, cultureCode, StringComparison.InvariantCultureIgnoreCase) != 0)
                            {
                                string url  = null;
                                string lang = cultureCode;
                                // Check whether culture alias is defined and if so use it
                                if (!String.IsNullOrEmpty(cultureAlias))
                                {
                                    lang = cultureAlias;
                                }

                                // Get specific url with language prefix
                                if (this.UseURLsWithLangPrefix && documentCultures != null)
                                {
                                    string urlPath = String.Empty;
                                    if (documentCultures.ContainsKey(cultureCode.ToLower()))
                                    {
                                        urlPath = documentCultures[cultureCode.ToLower()];
                                    }
                                    url  = TreePathUtils.GetUrl(CMSContext.CurrentAliasPath, urlPath, CMSContext.CurrentSiteName, lang);
                                    url += URLHelper.GetQuery(URLHelper.CurrentURL);
                                    url  = URLHelper.RemoveParameterFromUrl(url, URLHelper.LanguageParameterName);
                                    url  = URLHelper.RemoveParameterFromUrl(url, URLHelper.AliasPathParameterName);
                                }
                                // Get URL with lang parameter
                                else
                                {
                                    // Build current URL
                                    url = URLHelper.CurrentURL;
                                    url = URLHelper.RemoveParameterFromUrl(url, URLHelper.LanguageParameterName);
                                    url = URLHelper.RemoveParameterFromUrl(url, URLHelper.AliasPathParameterName);
                                    url = URLHelper.AddParameterToUrl(url, URLHelper.LanguageParameterName, lang);
                                }



                                ltlHyperlinks.Text += "<a href=\"" + url + "\">" + HTMLHelper.HTMLEncode(cultureShortName) + "</a>";
                            }
                            else
                            {
                                ltlHyperlinks.Text += cultureShortName;
                            }
                            ltlHyperlinks.Text += mSeparator;
                        }
                    }
                }
            }
            else
            {
                Visible = false;
            }
        }
    }
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            return;
        }

        // Hide info label of the captcha control because the newsletter subscription web part has its own
        scCaptcha.ShowInfoLabel = false;

        lblFirstName.Text         = FirstNameText;
        lblLastName.Text          = LastNameText;
        lblEmail.Text             = EmailText;
        lblCaptcha.ResourceString = CaptchaText;
        plcCaptcha.Visible        = DisplayCaptcha;

        if ((UseImageButton) && (!String.IsNullOrEmpty(ImageButtonURL)))
        {
            pnlButtonSubmit.Visible = false;
            pnlImageSubmit.Visible  = true;
            btnImageSubmit.ImageUrl = ImageButtonURL;
        }
        else
        {
            pnlButtonSubmit.Visible = true;
            pnlImageSubmit.Visible  = false;
            btnSubmit.Text          = ButtonText;
        }

        // Display labels only if user is logged in and property AllowUserSubscribers is set to true
        if (AllowUserSubscribers && AuthenticationHelper.IsAuthenticated())
        {
            visibleFirstName = false;
            visibleLastName  = false;
            visibleEmail     = false;
        }
        // Otherwise display text-boxes
        else
        {
            visibleFirstName = true;
            visibleLastName  = true;
            visibleEmail     = true;
        }

        // Hide first name field if not required
        if (!DisplayFirstName)
        {
            visibleFirstName = false;
        }
        // Hide last name field if not required
        if (!DisplayLastName)
        {
            visibleLastName = false;
        }

        // Show/hide newsletter list
        plcNwsList.Visible = NewsletterName.EqualsCSafe("nwsletuserchoose", true);
        if (plcNwsList.Visible)
        {
            chooseMode = true;

            if ((!ExternalUse || !RequestHelper.IsPostBack()) && (chklNewsletters.Items.Count == 0))
            {
                DataSet ds = null;

                // Try to get data from cache
                using (var cs = new CachedSection <DataSet>(ref ds, CacheMinutes, true, CacheItemName, "newslettersubscription", SiteContext.CurrentSiteName))
                {
                    if (cs.LoadData)
                    {
                        // Get the data
                        ds = NewsletterInfoProvider.GetNewslettersForSite(SiteContext.CurrentSiteID).WhereEquals("NewsletterType", (int)EmailCommunicationTypeEnum.Newsletter).OrderBy("NewsletterDisplayName").Columns("NewsletterDisplayName", "NewsletterName");

                        // Add data to the cache
                        if (cs.Cached)
                        {
                            // Prepare cache dependency
                            cs.CacheDependency = CacheHelper.GetCacheDependency("newsletter.newsletter|all");
                        }

                        cs.Data = ds;
                    }
                }

                if (!DataHelper.DataSourceIsEmpty(ds))
                {
                    ListItem li          = null;
                    string   displayName = null;

                    // Fill checkbox list with newsletters
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        displayName = ValidationHelper.GetString(dr["NewsletterDisplayName"], string.Empty);

                        li = new ListItem(HTMLHelper.HTMLEncode(displayName), ValidationHelper.GetString(dr["NewsletterName"], string.Empty));
                        chklNewsletters.Items.Add(li);
                    }
                }
            }
        }

        // Set SkinID properties
        if (!StandAlone && (PageCycle < PageCycleEnum.Initialized) && (string.IsNullOrEmpty(ValidationHelper.GetString(Page.StyleSheetTheme, string.Empty))))
        {
            string skinId = SkinID;
            if (!string.IsNullOrEmpty(skinId))
            {
                lblFirstName.SkinID = skinId;
                lblLastName.SkinID  = skinId;
                lblEmail.SkinID     = skinId;
                txtFirstName.SkinID = skinId;
                txtLastName.SkinID  = skinId;
                txtEmail.SkinID     = skinId;
                btnSubmit.SkinID    = skinId;
            }
        }
    }
Ejemplo n.º 12
0
        public decimal GetPrice(Delivery delivery, string currencyCode)
        {
            decimal decRate = 0;

            try
            {
                ServiceType stType = new ServiceType();
                switch (delivery.ShippingOption.ShippingOptionName)
                {
                case "FedExPriorityOvernight":
                    stType = ServiceType.PRIORITY_OVERNIGHT;
                    break;

                case "FedExStandardOvernight":
                    stType = ServiceType.STANDARD_OVERNIGHT;
                    break;
                }

                CurrentUserInfo uinfo = MembershipContext.AuthenticatedUser;

                RateReply reply = new RateReply();
                // Cache the data for 10 minutes with a key
                using (CachedSection <RateReply> cs = new CachedSection <RateReply>(ref reply, 60, true, null, "FexExRatesAPI-" + stType.ToString().Replace(" ", "-") + uinfo.UserID + "-" + delivery.DeliveryAddress.AddressZip + "-" + ValidationHelper.GetString(delivery.Weight, "")))
                {
                    if (cs.LoadData)
                    {
                        //Create the request
                        RateRequest request = CreateRateRequest(delivery, stType);
                        //Create the service
                        RateService service = new RateService();
                        // Call the web service passing in a RateRequest and returning a RateReply
                        reply   = service.getRates(request);
                        cs.Data = reply;
                    }
                    reply = cs.Data;
                }

                if (reply.HighestSeverity == NotificationSeverityType.SUCCESS)
                {
                    foreach (RateReplyDetail repDetail in reply.RateReplyDetails)
                    {
                        foreach (RatedShipmentDetail rsd in repDetail.RatedShipmentDetails)
                        {
                            //Add an offset to handle the differencse in the testing envinronment
                            decRate = ValidationHelper.GetDecimal(rsd.ShipmentRateDetail.TotalNetFedExCharge.Amount * 1.08m, 0);
                        }
                    }
                }
                else
                {
                    //Clean up the cached value so the next time the value is pulled again
                    CacheHelper.ClearCache("FexExRatesAPI-" + stType.ToString().Replace(" ", "-") + uinfo.UserID + "-" + delivery.DeliveryAddress.AddressZip + "-" + ValidationHelper.GetString(delivery.Weight, ""));
                }
            }
            catch (Exception ex)
            {
                //Log the error
                EventLogProvider.LogException("FedExCarrier - GetPrice", "EXCEPTION", ex);
                //Set some base rate for the shipping
                decRate = 10;
            }
            return(decRate);
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        fileGuid = QueryHelper.GetGuid("fileguid", Guid.Empty);

        DebugHelper.SetContext("GetForumAttachment");

        int cacheMinutes = CacheMinutes;

        // Try to get data from cache
        using (CachedSection <CMSOutputForumAttachment> cs = new CachedSection <CMSOutputForumAttachment>(ref outputFile, cacheMinutes, true, null, "getforumattachment", CurrentSiteName, GetBaseCacheKey(), Request.QueryString))
        {
            if (cs.LoadData)
            {
                // Disable caching before check permissions
                cs.CacheMinutes = 0;

                // Process the file
                ProcessFile();

                // Keep original cache minutes if permissions are ok
                cs.CacheMinutes = cacheMinutes;

                // Ensure the cache settings
                if (cs.Cached)
                {
                    // Prepare the cache dependency
                    CacheDependency cd = null;
                    if (outputFile != null)
                    {
                        if (outputFile.ForumAttachment != null)
                        {
                            cd = CacheHelper.GetCacheDependency(outputFile.ForumAttachment.GetDependencyCacheKeys());

                            // Do not cache if too big file which would be stored in memory
                            if (!CacheHelper.CacheImageAllowed(CurrentSiteName, outputFile.ForumAttachment.AttachmentFileSize) && !ForumAttachmentInfoProvider.StoreFilesInFileSystem(CurrentSiteName))
                            {
                                cacheMinutes = largeFilesCacheMinutes;
                            }
                        }
                    }

                    if ((cd == null) && (CurrentSite != null) && (outputFile != null))
                    {
                        // Get the current forum id
                        int forumId = 0;
                        if (outputFile.ForumAttachment != null)
                        {
                            forumId = outputFile.ForumAttachment.AttachmentForumID;
                        }

                        // Set default dependency based on GUID
                        cd = GetCacheDependency(new List <string>()
                        {
                            "forumattachment|" + fileGuid.ToString().ToLowerCSafe() + "|" + CurrentSite.SiteID, "forumattachment|" + forumId
                        });
                    }

                    // Cache the data
                    cs.CacheMinutes    = cacheMinutes;
                    cs.CacheDependency = cd;
                }

                cs.Data = outputFile;
            }
        }

        // Send the data
        SendFile(outputFile);

        DebugHelper.ReleaseContext();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        DebugHelper.SetContext("GetMediaFile");

        // Load the site name
        LoadSiteName();

        // Check the site
        if (string.IsNullOrEmpty(CurrentSiteName))
        {
            throw new Exception("[GetMediaFile.aspx]: Site not running.");
        }

        int cacheMinutes = CacheMinutes;

        // Try to get data from cache
        using (CachedSection <CMSOutputMediaFile> cs = new CachedSection <CMSOutputMediaFile>(ref outputFile, cacheMinutes, true, null, "getmediafile", CurrentSiteName, GetBaseCacheKey(), Request.QueryString))
        {
            if (cs.LoadData)
            {
                // Process the file
                ProcessFile();

                // Ensure the cache settings
                if (cs.Cached)
                {
                    // Prepare the cache dependency
                    CacheDependency cd = null;
                    if (outputFile != null)
                    {
                        if (outputFile.MediaFile != null)
                        {
                            // Do not cache too big files
                            if ((outputFile.MediaFile != null) && !CacheHelper.CacheImageAllowed(CurrentSiteName, (int)outputFile.MediaFile.FileSize))
                            {
                                cacheMinutes = largeFilesCacheMinutes;
                            }

                            // Set dependency on this particular file
                            if (cacheMinutes > 0)
                            {
                                List <string> dependencies = new List <string>();
                                dependencies.AddRange(MediaFileInfoProvider.GetDependencyCacheKeys(outputFile.MediaFile, Preview));
                                cd = GetCacheDependency(dependencies);
                            }
                        }
                    }

                    if ((cd == null) && (cacheMinutes > 0))
                    {
                        // Set default cache dependency by file GUID
                        cd = CacheHelper.GetCacheDependency(new string[] { "mediafile|" + fileGuid.ToString().ToLowerCSafe(), "mediafilepreview|" + fileGuid.ToString().ToLowerCSafe() });
                    }

                    // Cache the data
                    cs.CacheMinutes    = cacheMinutes;
                    cs.CacheDependency = cd;
                }

                cs.Data = outputFile;
            }
        }

        // Send the data
        SendFile(outputFile);

        DebugHelper.ReleaseContext();
    }
    /// <summary>
    /// Loads product options.
    /// </summary>
    private void LoadProductOptions()
    {
        DataSet dsCategories = null;

        if (IsLiveSite)
        {
            // Get cache minutes
            int cacheMinutes = SettingsKeyProvider.GetIntValue(CMSContext.CurrentSiteName + ".CMSCacheMinutes");

            // Try to get data from cache
            using (CachedSection <DataSet> cs = new CachedSection <DataSet>(ref dsCategories, cacheMinutes, true, null, "skuoptioncategories", SKUID))
            {
                if (cs.LoadData)
                {
                    // Get the data
                    dsCategories = OptionCategoryInfoProvider.GetSKUOptionCategories(SKUID, true);

                    // Save to the cache
                    if (cs.Cached)
                    {
                        // Get dependencies
                        List <string> dependencies = new List <string>();
                        dependencies.Add("ecommerce.sku|byid|" + SKUID);
                        dependencies.Add("ecommerce.optioncategory|all");

                        // Set dependencies
                        cs.CacheDependency = CacheHelper.GetCacheDependency(dependencies);
                    }

                    cs.Data = dsCategories;
                }
            }
        }
        else
        {
            // Get the data
            dsCategories = OptionCategoryInfoProvider.GetSKUOptionCategories(SKUID, true);
        }

        // Initialize product option selectors
        if (!DataHelper.DataSourceIsEmpty(dsCategories))
        {
            mProductOptions = new Hashtable();

            foreach (DataRow dr in dsCategories.Tables[0].Rows)
            {
                try
                {
                    // Load control for selection product options
                    ProductOptionSelector selector = (ProductOptionSelector)LoadUserControl("~/CMSModules/Ecommerce/Controls/ProductOptions/ProductOptionSelector.ascx");

                    // Add control to the collection
                    selector.ID = "opt" + ValidationHelper.GetInteger(dr["CategoryID"], 0);

                    // Init selector
                    selector.LocalShoppingCartObj  = ShoppingCart;
                    selector.ShowPriceIncludingTax = ShowPriceIncludingTax;
                    selector.IsLiveSite            = IsLiveSite;
                    selector.SKUID          = SKUID;
                    selector.OptionCategory = new OptionCategoryInfo(dr);

                    // Load all product options
                    foreach (DictionaryEntry entry in selector.ProductOptions)
                    {
                        mProductOptions[entry.Key] = entry.Value;
                    }

                    if (AlwaysShowTotalPrice || ShowTotalPrice)
                    {
                        ListControl lc = selector.SelectionControl as ListControl;
                        if (lc != null)
                        {
                            // Add Index change handler
                            lc.AutoPostBack          = true;
                            lc.SelectedIndexChanged += new EventHandler(Selector_SelectedIndexChanged);
                        }
                    }

                    pnlSelectors.Controls.Add(selector);
                }
                catch
                {
                }
            }
        }
    }
Ejemplo n.º 16
0
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            //Do nothing
            rptPostArchive.StopProcessing = true;
        }
        else
        {
            rptPostArchive.ControlContext = ControlContext;

            // Get current page info
            PageInfo currentPage = DocumentContext.CurrentPageInfo;

            // Select only publish is depend on view mode
            bool selectOnlyPublished = (PageManager.ViewMode.IsLiveSite());

            TreeNode blogNode = null;
            // Try to get data from cache
            using (var cs = new CachedSection<TreeNode>(ref blogNode, CacheMinutes, true, CacheItemName, "postarchivenode", currentPage.NodeAliasPath, SiteContext.CurrentSiteName, selectOnlyPublished))
            {
                if (cs.LoadData)
                {
                    blogNode = BlogHelper.GetParentBlog(currentPage.NodeAliasPath, SiteContext.CurrentSiteName, selectOnlyPublished);

                    // Save to cache
                    if (cs.Cached)
                    {
                        cs.CacheDependency = GetCacheDependency();
                    }

                    cs.Data = blogNode;
                }
            }

            // Set repeater path in accordance to blog node alias path
            if (blogNode != null)
            {
                rptPostArchive.Path = blogNode.NodeAliasPath + "/%";
            }
            else
            {
                rptPostArchive.Path = currentPage.NodeAliasPath + "/%";
            }

            // Set repeater properties
            rptPostArchive.TransformationName = TransformationName;
            rptPostArchive.SelectTopN = SelectTopN;
            rptPostArchive.HideControlForZeroRows = HideControlForZeroRows;
            rptPostArchive.ZeroRowsText = ZeroRowsText;
            rptPostArchive.CacheItemName = CacheItemName;
            rptPostArchive.CacheDependencies = CacheDependencies;
            rptPostArchive.CacheMinutes = CacheMinutes;
        }
    }
    /// <summary>
    /// Returns product total tax in site main currency.
    /// </summary>
    /// <param name="skuPrice">SKU price</param>
    /// <param name="skuId">SKU ID</param>
    /// <param name="stateId">Customer billing address state ID</param>
    /// <param name="countryId">Customer billing addres country ID</param>
    /// <param name="isTaxIDSupplied">Indicates if customer tax registration ID is supplied</param>    
    private static double GetSKUTotalTax(double skuPrice, int skuId, int stateId, int countryId, bool isTaxIDSupplied)
    {
        double totalTax = 0;
        int cacheMinutes = 0;

        // Try to get data from cache
        using (CachedSection<double> cs = new CachedSection<double>(ref totalTax, cacheMinutes, true, null, "skutotaltax|", skuId, skuPrice, stateId, countryId, isTaxIDSupplied))
        {
            if (cs.LoadData)
            {
                // Get all the taxes and their values which are applied to the specified product
                DataSet ds = TaxClassInfoProvider.GetTaxes(skuId, countryId, stateId, null);
                if (!DataHelper.DataSourceIsEmpty(ds))
                {
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        bool zeroTax = ValidationHelper.GetBoolean(dr["TaxClassZeroIfIDSupplied"], false);
                        if (!(isTaxIDSupplied && zeroTax))
                        {
                            double taxValue = ValidationHelper.GetDouble(dr["TaxValue"], 0);
                            bool isFlat = ValidationHelper.GetBoolean(dr["TaxIsFlat"], false);

                            // Add tax value
                            totalTax += TaxClassInfoProvider.GetTaxValue(skuPrice, taxValue, isFlat);
                        }
                    }
                }

                // Cache the data
                cs.Data = totalTax;
            }
        }

        return totalTax;
    }
Ejemplo n.º 18
0
    protected void Page_Load(object sender, EventArgs e)
    {
        DebugHelper.SetContext("GetMetaFile");

        // Load the site name
        LoadSiteName();

        int cacheMinutes = this.CacheMinutes;

        // Try to get data from cache
        using (CachedSection <CMSOutputMetaFile> cs = new CachedSection <CMSOutputMetaFile>(ref outputFile, cacheMinutes, true, null, "getmetafile", this.CurrentSiteName, Request.QueryString))
        {
            if (cs.LoadData)
            {
                // Process the file
                ProcessFile();

                if (cs.Cached)
                {
                    // Do not cache if too big file which would be stored in memory
                    if ((outputFile != null) &&
                        (outputFile.MetaFile != null) &&
                        !CacheHelper.CacheImageAllowed(CurrentSiteName, outputFile.MetaFile.MetaFileSize) &&
                        !AttachmentManager.StoreFilesInFileSystem(CurrentSiteName))
                    {
                        cacheMinutes = largeFilesCacheMinutes;
                    }

                    if (cacheMinutes > 0)
                    {
                        // Prepare the cache dependency
                        CacheDependency cd = null;
                        if (outputFile != null)
                        {
                            if (outputFile.MetaFile != null)
                            {
                                // Add dependency on this particular meta file
                                cd = CacheHelper.GetCacheDependency(outputFile.MetaFile.GetDependencyCacheKeys());
                            }
                        }

                        if (cd == null)
                        {
                            // Set default dependency based on GUID
                            cd = CacheHelper.GetCacheDependency(new string[] { "metafile|" + fileGuid.ToString().ToLower() });
                        }

                        cs.CacheDependency = cd;
                    }

                    // Cache the data
                    cs.CacheMinutes = cacheMinutes;
                    cs.Data         = outputFile;
                }
            }
        }

        // Send the data
        SendFile(outputFile);

        DebugHelper.ReleaseContext();
    }
    /// <summary>
    /// Setups control properties.
    /// </summary>
    protected void SetupControl()
    {
        // Check StopProcessing property
        if (StopProcessing)
        {
            Visible = false;
        }
        else
        {
            SetContext();

            DataSet users = null;
            bool transLoaded = false;

            // Load transformation
            if (!string.IsNullOrEmpty(TransformationName))
            {
                repUsers.ItemTemplate = CMSAbstractDataProperties.LoadTransformation(this, TransformationName);
                transLoaded = true;
            }

            if ((transLoaded) || (!String.IsNullOrEmpty(Path)))
            {
                // Try to get data from cache
                using (var cs = new CachedSection<DataSet>(ref users, CacheMinutes, true, CacheItemName, "onlineusers", SiteContext.CurrentSiteName, SelectTopN, Columns, Path))
                {
                    if (cs.LoadData)
                    {
                        // Get the data
                        users = SessionManager.GetOnlineUsers(null, null, SelectTopN, Columns, MacroResolver.ResolveCurrentPath(Path), SiteContext.CurrentSiteName, false, false);

                        // Prepare the cache dependency
                        if (cs.Cached)
                        {
                            cs.CacheDependency = GetCacheDependency();
                        }

                        cs.Data = users;
                    }
                }

                // Data bind
                if (!DataHelper.DataSourceIsEmpty(users))
                {
                    // Set to repeater
                    repUsers.DataSource = users;
                    repUsers.DataBind();
                }
            }

            int authenticated = 0;
            int publicUsers = 0;

            string numbers = string.Empty;

            // Get or generate cache item name
            string cacheItemNameNumbers = CacheItemName;
            if (!string.IsNullOrEmpty(cacheItemNameNumbers))
            {
                cacheItemNameNumbers += "Number";
            }

            // Try to get data from cache
            using (var cs = new CachedSection<string>(ref numbers, CacheMinutes, true, cacheItemNameNumbers, "onlineusersnumber", SiteContext.CurrentSiteName, Path))
            {
                if (cs.LoadData)
                {
                    // Get the data
                    SessionManager.GetUsersNumber(CurrentSiteName, MacroResolver.ResolveCurrentPath(Path), false, false, out publicUsers, out authenticated);

                    // Save to the cache
                    if (cs.Cached)
                    {
                        cs.CacheDependency = GetCacheDependency();
                    }

                    cs.Data = publicUsers.ToString() + ";" + authenticated.ToString();
                }
                else if (!String.IsNullOrEmpty(numbers))
                {
                    // Retrieved from cache
                    string[] nums = numbers.Split(';');

                    publicUsers = ValidationHelper.GetInteger(nums[0], 0);
                    authenticated = ValidationHelper.GetInteger(nums[1], 0);
                }
            }

            // Check if at least one user is online
            if ((publicUsers + authenticated) == 0)
            {
                ltrAdditionaInfos.Text = NoUsersOnlineText;
            }
            else
            {
                ltrAdditionaInfos.Text = string.Format(AdditionalInfoText, publicUsers + authenticated, publicUsers, authenticated);
            }
        }

        ReleaseContext();
    }
Ejemplo n.º 20
0
    protected void Page_Load(object sender, EventArgs e)
    {
        DebugHelper.SetContext("GetAvatar");

        // Prepare the cache key
        fileGuid = QueryHelper.GetGuid("avatarguid", Guid.Empty);

        // Try get guid from routed URL
        if (fileGuid == Guid.Empty)
        {
            fileGuid = ValidationHelper.GetGuid(RouteData.Values["avatarGuid"], Guid.Empty);
            if (fileGuid != Guid.Empty)
            {
                MaxSideSize = ValidationHelper.GetInteger(RouteData.Values["maxSideSize"], 0);
            }
        }

        int cacheMinutes = CacheMinutes;

        // Try to get data from cache
        using (var cs = new CachedSection <CMSOutputAvatar>(ref outputFile, cacheMinutes, true, null, "getavatar", GetBaseCacheKey(), Request.QueryString))
        {
            if (cs.LoadData)
            {
                // Process the file
                ProcessFile();

                // Ensure the cache settings
                if (cs.Cached)
                {
                    // Add cache dependency
                    CMSCacheDependency cd = null;
                    if (outputFile != null)
                    {
                        if (outputFile.Avatar != null)
                        {
                            cd = CacheHelper.GetCacheDependency(outputFile.Avatar.GetDependencyCacheKeys());

                            // Do not cache if too big file which would be stored in memory
                            if ((outputFile.Avatar != null) && !CacheHelper.CacheImageAllowed(CurrentSiteName, outputFile.Avatar.AvatarFileSize) && !AvatarInfoProvider.StoreFilesInFileSystem())
                            {
                                cacheMinutes = largeFilesCacheMinutes;
                            }
                        }
                    }

                    if ((cd == null) && (cacheMinutes > 0))
                    {
                        // Set default dependency based on GUID
                        cd = GetCacheDependency(new List <string>()
                        {
                            "avatarfile|" + fileGuid.ToString().ToLowerCSafe()
                        });
                    }

                    // Cache the data
                    cs.CacheMinutes    = cacheMinutes;
                    cs.CacheDependency = cd;
                }

                cs.Data = outputFile;
            }
        }

        // Send the data
        SendFile(outputFile);

        DebugHelper.ReleaseContext();
    }
    /// <summary>
    /// Bind data to repeater.
    /// </summary>
    private void BindData()
    {
        if (MembershipContext.AuthenticatedUser != null)
        {
            int userId = MembershipContext.AuthenticatedUser.UserID;
            int siteId = SiteContext.CurrentSiteID;

            // If sitename was specified
            if (SiteName != String.Empty)
            {
                // Get site ID
                SiteInfo si = SiteInfoProvider.GetSiteInfo(SiteName);
                if (si != null)
                {
                    siteId = si.SiteID;
                }
            }

            // Get user favorites
            DataSet ds = null;

            // Try to get data from cache
            using (var cs = new CachedSection<DataSet>(ref ds, CacheMinutes, true, CacheItemName, "forumfavorites", userId, siteId))
            {
                if (cs.LoadData)
                {
                    // Get the data
                    ds = ForumUserFavoritesInfoProvider.GetFavorites(userId, siteId);

                    // Save to the cache
                    if (cs.Cached)
                    {
                        // Save to the cache
                        cs.CacheDependency = GetCacheDependency();
                    }

                    cs.Data = ds;
                }
            }

            // Bind data, even empty dataset - delete of last item
            rptFavorites.DataSource = ds;
            rptFavorites.DataBind();

            // Hide control if no data
            if (DataHelper.DataSourceIsEmpty(ds))
            {
                if (HideControlForZeroRows)
                {
                    Visible = false;
                }
                else
                {
                    plcEmptyDSTagEnd.Visible = true;
                    plcEmptyDSTagBegin.Visible = true;
                }
            }
            else
            {
                plcEmptyDSTagEnd.Visible = false;
                plcEmptyDSTagBegin.Visible = false;
            }
        }
    }
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (this.StopProcessing)
        {
            // Do nothing
        }
        else
        {
            string siteName = CMSContext.CurrentSiteName;

            // If there is only one culture on site and hiding is enabled hide webpart
            if (HideIfOneCulture && !CultureInfoProvider.IsSiteMultilignual(siteName))
            {
                this.Visible = false;
                return;
            }

            DataSet ds = null;

            // Try to get data from cache
            using (CachedSection<DataSet> cs = new CachedSection<DataSet>(ref ds, this.CacheMinutes, true, this.CacheItemName, "languageselection", siteName))
            {
                if (cs.LoadData)
                {
                    // Get the data
                    ds = CultureInfoProvider.GetSiteCultures(siteName);

                    // Save to the cache
                    if (cs.Cached)
                    {
                        cs.CacheDependency = CacheHelper.GetCacheDependency(new string[] { "cms.culturesite|all", "cms.culture|all" });
                        cs.Data = ds;
                    }
                }
            }

            // Add CSS Stylesheet
            string cssUrl = URLHelper.ResolveUrl("~/CMSWebparts/General/languageselectiondropdown_files/langselector.css");
            this.Page.Header.Controls.Add(new LiteralControl("<link href=\"" + cssUrl + "\" type=\"text/css\" rel=\"stylesheet\" />"));

            // Build current URL
            string url = URLHelper.CurrentURL;
            url = URLHelper.RemoveParameterFromUrl(url, URLHelper.LanguageParameterName);
            url = URLHelper.RemoveParameterFromUrl(url, URLHelper.AliasPathParameterName);

            string imgFlagIcon = "";

            StringBuilder result = new StringBuilder();
            result.Append("<ul class=\"langselector\">");

            // Current language
            CultureInfo culture = CultureInfoProvider.GetCultureInfo(CMSContext.CurrentUser.PreferredCultureCode);
            if (culture != null)
            {
                // Drop down imitating icon
                string dropIcon = ResolveUrl("~/CMSWebparts/General/languageselectiondropdown_files/dd_arrow.gif");

                // Current language
                imgFlagIcon = this.GetImageUrl("Flags/16x16/" + HTMLHelper.HTMLEncode(culture.CultureCode) + ".png");

                string currentCultureShortName = "";
                if (this.ShowCultureNames)
                {
                    currentCultureShortName = HTMLHelper.HTMLEncode(culture.CultureShortName);
                }

                result.AppendFormat("<li class=\"lifirst\" style=\"background-image:url('{0}'); background-repeat: no-repeat\"><a class=\"first\" style=\"background-image:url({1}); background-repeat: no-repeat\" href=\"{2}\">{3}</a>",
                    dropIcon, imgFlagIcon, HTMLHelper.HTMLEncode(URLHelper.AddParameterToUrl(url, URLHelper.LanguageParameterName, culture.CultureCode)), currentCultureShortName);
            }

            // List of languages
            if (!DataHelper.DataSourceIsEmpty(ds) && (ds.Tables[0].Rows.Count > 1))
            {
                // Collection of available documents in culture
                Dictionary<string, string> documentCultures = null;
                // Check whether hiding is required or URLs should be generated with lang prefix
                if (this.HideUnavailableCultures || this.UseURLsWithLangPrefix)
                {
                    string cacheItemName = this.CacheItemName;
                    if (!String.IsNullOrEmpty(cacheItemName))
                    {
                        cacheItemName += "prefix";
                    }

                    // Current page info
                    PageInfo currentPageInfo = CMSContext.CurrentPageInfo;

                    if (currentPageInfo != null)
                    {
                        // Try to get data from cache
                        using (CachedSection<Dictionary<string, string>> cs = new CachedSection<Dictionary<string, string>>(ref documentCultures, this.CacheMinutes, true, cacheItemName, "languageselectionprefix", siteName, currentPageInfo.NodeAliasPath.ToLower()))
                        {
                            if (cs.LoadData)
                            {
                                // Initialize tree provider object
                                TreeProvider tp = new TreeProvider(CMSContext.CurrentUser);
                                tp.FilterOutDuplicates = false;
                                tp.CombineWithDefaultCulture = false;

                                // Get all language versions
                                DataSet culturesDs = tp.SelectNodes(siteName, "/%", TreeProvider.ALL_CULTURES, false, null, "NodeID = " + currentPageInfo.NodeId, null, -1, true, 0, "DocumentCulture, DocumentUrlPath");

                                // Create culture/UrlPath collection
                                if (!DataHelper.DataSourceIsEmpty(culturesDs))
                                {
                                    documentCultures = new Dictionary<string, string>();
                                    foreach (DataRow dr in culturesDs.Tables[0].Rows)
                                    {
                                        string docCulture = ValidationHelper.GetString(dr["DocumentCulture"], String.Empty).ToLower();
                                        string urlPath = ValidationHelper.GetString(dr["DocumentUrlPath"], String.Empty);
                                        documentCultures.Add(docCulture, urlPath);
                                    }
                                }

                                // Add to the cache
                                if (cs.Cached)
                                {
                                    cs.CacheDependency = this.GetCacheDependency();
                                    cs.Data = documentCultures;
                                }
                            }
                        }
                    }
                }

                result.Append("<ul>");

                // Create options for other culture
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    string cultureCode = dr["CultureCode"].ToString();
                    string cultureShortName = dr["CultureShortName"].ToString();
                    string cultureAlias = dr["CultureAlias"].ToString();

                    bool documentCultureExists = true;

                    // Check whether exists document in specified culture
                    if ((documentCultures != null) && (this.HideUnavailableCultures))
                    {
                        documentCultureExists = documentCultures.ContainsKey(cultureCode.ToLower());
                    }

                    if (documentCultureExists)
                    {
                        if (CMSContext.CurrentDocument != null && !string.IsNullOrEmpty(CMSContext.CurrentDocument.DocumentCulture) && !((HideCurrentCulture) && (String.Compare(CMSContext.CurrentDocument.DocumentCulture, cultureCode, true) == 0)))
                        {
                            url = null;
                            string lang = cultureCode;
                            // Check whether culture alias is defined and if so use it
                            if (!String.IsNullOrEmpty(cultureAlias))
                            {
                                lang = cultureAlias;
                            }

                            // Get specific url with language prefix
                            if (this.UseURLsWithLangPrefix && documentCultures != null)
                            {
                                string urlPath = String.Empty;
                                if (documentCultures.ContainsKey(cultureCode.ToLower()))
                                {
                                    urlPath = documentCultures[cultureCode.ToLower()];
                                }
                                url = TreePathUtils.GetUrl(CMSContext.CurrentAliasPath, urlPath, siteName, lang);
                                url += URLHelper.GetQuery(URLHelper.CurrentURL);
                                url = URLHelper.RemoveParameterFromUrl(url, URLHelper.LanguageParameterName);
                                url = URLHelper.RemoveParameterFromUrl(url, URLHelper.AliasPathParameterName);
                            }
                            // Get URL with lang parameter
                            else
                            {
                                // Build current URL
                                url = URLHelper.CurrentURL;
                                url = URLHelper.RemoveParameterFromUrl(url, URLHelper.LanguageParameterName);
                                url = URLHelper.RemoveParameterFromUrl(url, URLHelper.AliasPathParameterName);
                                url = URLHelper.AddParameterToUrl(url, URLHelper.LanguageParameterName, lang);
                            }

                            // Language icon
                            imgFlagIcon = this.GetImageUrl("Flags/16x16/" + HTMLHelper.HTMLEncode(cultureCode) + ".png");

                            if (this.ShowCultureNames)
                            {
                                cultureShortName = HTMLHelper.HTMLEncode(cultureShortName);
                            }
                            else
                            {
                                cultureShortName = "";
                            }
                            result.AppendFormat("<li><a style=\"background-image:url({0}); background-repeat: no-repeat\" href=\"{1}\">{2}</a></li>\r\n",
                                imgFlagIcon, HTMLHelper.HTMLEncode(URLHelper.ResolveUrl(url)), cultureShortName);
                        }
                    }
                }
                result.Append("</ul>");
            }
            result.Append("</li></ul>");
            ltlLanguages.Text = result.ToString();
        }
    }
Ejemplo n.º 23
0
        public decimal GetFedExRate(Rates objRates, CurrentUserInfo uinfo, Delivery delivery, string strShippingOptionName)
        {
            decimal decRate = 0;

            try
            {
                // Cache the data for 10 minutes with a key
                using (CachedSection <Rates> cs = new CachedSection <Rates>(ref objRates, 60, true, null, "FexExRates-" + uinfo.UserID + "-" + delivery.DeliveryAddress.AddressZip + "-" + ValidationHelper.GetString(delivery.Weight, "")))
                {
                    if (cs.LoadData)
                    {
                        //Get real-time shipping rates from FedEx using dotNETShip
                        Ship objShip = new Ship();
                        objShip.FedExLogin    = strFedExLogin; // "Account number, meter number, key, password"
                        objShip.FedExURLTest  = SettingsKeyInfoProvider.GetBoolValue("MultiCarrierTestMode");
                        objShip.OrigZipPostal = SettingsKeyInfoProvider.GetValue("SourceZip", "90001");
                        string[]    strCountryState = SettingsKeyInfoProvider.GetValue("SourceCountryState", "US").Split(';');
                        CountryInfo ci = CountryInfoProvider.GetCountryInfo(ValidationHelper.GetString(strCountryState[0], "USA"));
                        objShip.OrigCountry = ci.CountryTwoLetterCode;
                        StateInfo si = StateInfoProvider.GetStateInfo(ValidationHelper.GetString(strCountryState[1], "California"));
                        objShip.OrigStateProvince = si.StateCode;

                        objShip.DestZipPostal     = delivery.DeliveryAddress.AddressZip;
                        objShip.DestCountry       = delivery.DeliveryAddress.GetCountryTwoLetterCode();
                        objShip.DestStateProvince = delivery.DeliveryAddress.GetStateCode();

                        objShip.Weight = (float)delivery.Weight;

                        objShip.Rate("FedEx");

                        cs.Data = objShip.Rates;
                    }

                    objRates = cs.Data;
                }
                if (objRates.Count > 0)
                {
                    foreach (Rate rate in objRates)
                    {
                        if (rate.Name.ToLower() == strShippingOptionName.ToLower())
                        {
                            decRate = ValidationHelper.GetDecimal(rate.Charge, 0) * 1.08m;
                            break;
                        }
                    }
                }
                else
                {
                    CacheHelper.ClearCache("FexExRates-" + uinfo.UserID + "-" + delivery.DeliveryAddress.AddressZip + "-" + ValidationHelper.GetString(delivery.Weight, ""));
                }
            }
            catch (Exception ex)
            {
                //Log the error
                EventLogProvider.LogException("MultiCarrier - GetFedExRate", "EXCEPTION", ex);
                //Set some base rate for the shipping
                decRate = 10;
            }

            return(decRate);
        }
    /// <summary>
    /// Processes a request for a file.
    /// </summary>
    /// <param name="context">An HTTPContext object that provides references to the intrinsic server objects used to service HTTP requests</param>
    /// <param name="url">File URL</param>
    /// <param name="fileExtension">File extension to check against (to prevent serving unauthorized content)</param>
    /// <param name="minificationEnabled">True, if the data should be minified, otherwise false</param>
    /// <param name="useCache">If true, cache is allowed to be used</param>
    private static void ProcessPhysicalFileRequest(HttpContext context, string url, string fileExtension, bool minificationEnabled, bool useCache)
    {
        // Get physical path
        string path = URLHelper.GetPhysicalPath(URLHelper.GetVirtualPath(url));

        // If this is revalidation request, try quick revalidation check before reading the file
        CheckRevalidation(context, path);

        CMSOutputResource resource = null;

        // Try to get data from cache (or store them if not found)
        using (CachedSection<CMSOutputResource> cs = new CachedSection<CMSOutputResource>(ref resource, PhysicalFilesCacheMinutes, useCache, null, "getresource", path, URLHelper.IsSSL))
        {
            // Not found in cache; load the data
            if (cs.LoadData)
            {
                // Check the image extension
                switch (fileExtension)
                {
                    case IMAGE_FILE_EXTENSION:
                    case FILE_EXTENSION:
                        {
                            // Extension sets
                            string fileExt = Path.GetExtension(path);

                            if ((fileExtension == IMAGE_FILE_EXTENSION) && ImageHelper.IsImage(fileExt))
                            {
                                // Image file
                                fileExtension = fileExt;
                            }
                            else if ((fileExtension == FILE_EXTENSION) && mAllowedFileExtensions.Contains(fileExt.ToLowerCSafe()))
                            {
                                // General file
                                fileExtension = fileExt;
                            }

                            resource = GetFile(new CMSItem(url), fileExtension, false, true);
                        }
                        break;

                    default:
                        {
                            // Retrieve the file resource, rebase client URLs and wrap it in output container
                            resource = GetFile(new CMSItem(url), fileExtension, false, false);

                            MinifyResource(resource, new JavaScriptMinifier(), minificationEnabled, true);
                        }
                        break;

                }

                // Cache the file
                if ((resource != null) && cs.Cached)
                {
                    path = StorageHelper.GetRealFilePath(path);

                    if (File.Exists(path))
                    {
                        cs.CacheDependency = new CMSCacheDependency(path);
                    }
                }

                cs.Data = resource;
            }
        }

        // Send response if there's something to send
        if (resource != null)
        {
            bool allowCache = CacheHelper.AlwaysCacheResources;

            SendResponse(context, resource, allowCache, minificationEnabled, PhysicalFilesCacheMinutes, true);
        }
        else
        {
            SendNotFoundResponse(context);
        }
    }
Ejemplo n.º 25
0
    /// <summary>
    /// Processes the specified document node.
    /// </summary>
    /// <param name="currentNodeGuid">Node GUID</param>
    protected void ProcessNode(Guid currentNodeGuid)
    {
        // Load the document node
        string columnName = QueryHelper.GetString("columnName", String.Empty);
        if (node == null)
        {
            // Try to get data from cache
            using (CachedSection<TreeNode> cs = new CachedSection<TreeNode>(ref node, CacheMinutes, !allowLatestVersion, null, "getfilenodebyguid|", CurrentSiteName, CacheHelper.GetBaseCacheKey(false, true), currentNodeGuid))
            {
                if (cs.LoadData)
                {
                    // Get the document
                    bool combineWithDefaultCulture = SettingsKeyProvider.GetBoolValue(CurrentSiteName + ".CMSCombineImagesWithDefaultCulture");
                    string culture = CultureCode;
                    string where = "NodeGUID = '" + currentNodeGuid + "'";

                    // Get the document
                    string className = null;
                    if (columnName == "")
                    {
                        // CMS.File
                        className = "CMS.File";
                    }
                    else
                    {
                        // Other document types
                        TreeNode srcNode = TreeProvider.SelectSingleNode(currentNodeGuid, CultureCode, CurrentSiteName);
                        if (srcNode != null)
                        {
                            className = srcNode.NodeClassName;
                        }
                    }

                    // Get the document data
                    if (!IsLiveSite || allowLatestVersion)
                    {
                        node = DocumentHelper.GetDocument(CurrentSiteName, null, culture, combineWithDefaultCulture, className, where, null, -1, false, null, TreeProvider);
                    }
                    else
                    {
                        node = TreeProvider.SelectSingleNode(CurrentSiteName, null, culture, combineWithDefaultCulture, className, where, null, -1, false, null);

                        // Documents should be combined with default culture
                        if ((node != null) && combineWithDefaultCulture && !node.IsPublished)
                        {
                            // Try to find published document in default culture
                            string defaultCulture = CultureHelper.GetDefaultCulture(CurrentSiteName);
                            TreeNode cultureNode = TreeProvider.SelectSingleNode(CurrentSiteName, null, defaultCulture, false, className, where, null, -1, false, null);
                            if ((cultureNode != null) && cultureNode.IsPublished)
                            {
                                node = cultureNode;
                            }
                        }
                    }

                    // Cache the document
                    CacheNode(cs, node);
                }
            }
        }

        // Process the document node
        ProcessNode(node, columnName, null);
    }
    /// <summary>
    /// Processes a request for a QR code
    /// </summary>
    /// <param name="context">An HTTPContext object that provides references to the intrinsic server objects used to service HTTP requests</param>
    private static void ProcessQRCodeRequest(HttpContext context)
    {
        string code = QueryHelper.GetString(QR_CODE_ARGUMENT, string.Empty);

        string correction = QueryHelper.GetString("ec", "M");
        string encoding = QueryHelper.GetString("e", "B");

        int size = QueryHelper.GetInteger("s", 4);
        int version = QueryHelper.GetInteger("v", 4);
        int maxSideSize = QueryHelper.GetInteger("maxsidesize", 0);

        Color fgColor = QueryHelper.GetColor("fc", Color.Black);
        Color bgColor = QueryHelper.GetColor("bc", Color.White);

        CMSOutputResource resource = null;

        // Try to get data from cache (or store them if not found)
        using (CachedSection<CMSOutputResource> cs = new CachedSection<CMSOutputResource>(ref resource, PhysicalFilesCacheMinutes, true, null, "getresource|qrcode|", code, encoding, size, version, correction, maxSideSize, fgColor, bgColor, URLHelper.IsSSL))
        {
            // Not found in cache; load the data
            if (cs.LoadData)
            {
                // Validate the request hash
                if (QueryHelper.ValidateHash("hash", null, false))
                {
                    // Prepare the QR code response
                    resource = GetQRCode(code, encoding, size, version, correction, maxSideSize, fgColor, bgColor);
                }

                cs.Data = resource;
            }
        }

        // Send response if there's something to send
        if (resource != null)
        {
            bool allowCache = CacheHelper.AlwaysCacheResources;

            SendResponse(context, resource, allowCache, false, PhysicalFilesCacheMinutes, true);
        }
        else
        {
            SendNotFoundResponse(context);
        }
    }
Ejemplo n.º 27
0
    protected void Page_Load(object sender, EventArgs e)
    {
        DebugHelper.SetContext("GetFile");

        // Load the site name
        LoadSiteName();

        // Check the site
        if (CurrentSiteName == "")
        {
            throw new Exception("[GetFile.aspx]: Site not running.");
        }

        ValidateCulture();

        // Set campaign
        if (IsLiveSite)
        {
            // Store campaign name if present
            string campaign = AnalyticsHelper.CurrentCampaign(CurrentSiteName);
            if (!String.IsNullOrEmpty(campaign))
            {
                // Log campaign
                if ((CMSContext.CurrentPageInfo != null) && AnalyticsHelper.SetCampaign(campaign, CurrentSiteName, CMSContext.CurrentPageInfo.NodeAliasPath))
                {
                    CMSContext.Campaign = campaign;
                }
            }
        }

        int cacheMinutes = CacheMinutes;

        // Try to get data from cache
        using (CachedSection<CMSOutputFile> cs = new CachedSection<CMSOutputFile>(ref outputFile, cacheMinutes, true, null, "getfile", CurrentSiteName, GetBaseCacheKey(), Request.QueryString))
        {
            if (cs.LoadData)
            {
                // Store current value and temporary disable caching
                bool cached = cs.Cached;
                cs.Cached = false;

                // Process the file
                ProcessAttachment();

                // Restore cache settings - data were loaded
                cs.Cached = cached;

                if (cs.Cached)
                {
                    // Do not cache if too big file which would be stored in memory
                    if ((outputFile != null) &&
                        (outputFile.Attachment != null) &&
                        !CacheHelper.CacheImageAllowed(CurrentSiteName, outputFile.Attachment.AttachmentSize) &&
                        !AttachmentInfoProvider.StoreFilesInFileSystem(CurrentSiteName))
                    {
                        cacheMinutes = largeFilesCacheMinutes;
                    }

                    if (cacheMinutes > 0)
                    {
                        // Prepare the cache dependency
                        CacheDependency cd = null;
                        if (outputFile != null)
                        {
                            List<string> dependencies = new List<string>()
                                                        {
                                                            "node|" + CurrentSiteName.ToLowerCSafe() + "|" + outputFile.AliasPath.ToLowerCSafe(),
                                                            ""
                                                        };

                            // Do not cache if too big file which would be stored in memory
                            if (outputFile.Attachment != null)
                            {
                                if (!CacheHelper.CacheImageAllowed(CurrentSiteName, outputFile.Attachment.AttachmentSize) && !AttachmentInfoProvider.StoreFilesInFileSystem(CurrentSiteName))
                                {
                                    cacheMinutes = largeFilesCacheMinutes;
                                }

                                dependencies.Add("attachment|" + outputFile.Attachment.AttachmentGUID.ToString().ToLowerCSafe());
                            }

                            cd = GetCacheDependency(dependencies);
                        }

                        if (cd == null)
                        {
                            // Set default dependency
                            if (guid != Guid.Empty)
                            {
                                // By attachment GUID
                                cd = CacheHelper.GetCacheDependency(new string[] { "attachment|" + guid.ToString().ToLowerCSafe() });
                            }
                            else if (nodeGuid != Guid.Empty)
                            {
                                // By node GUID
                                cd = CacheHelper.GetCacheDependency(new string[] { "nodeguid|" + CurrentSiteName.ToLowerCSafe() + "|" + nodeGuid.ToString().ToLowerCSafe() });
                            }
                            else if (aliasPath != null)
                            {
                                // By node alias path
                                cd = CacheHelper.GetCacheDependency(new string[] { "node|" + CurrentSiteName.ToLowerCSafe() + "|" + aliasPath.ToLowerCSafe() });
                            }
                        }

                        cs.CacheDependency = cd;
                    }

                    // Cache the data
                    cs.CacheMinutes = cacheMinutes;
                }

                cs.Data = outputFile;
            }
        }

        // Do not cache images in the browser if cache is not allowed
        if (LatestVersion)
        {
            useClientCache = false;
        }

        // Send the data
        SendFile(outputFile);

        DebugHelper.ReleaseContext();
    }
    /// <summary>
    /// Processes the given request.
    /// </summary>
    /// <param name="context">Http context</param>
    /// <param name="settings">CSS Settings</param>
    private static void ProcessRequest(HttpContext context, CMSCssSettings settings)
    {
        CMSOutputResource resource = null;

        // Get cache setting for physical files
        int cacheMinutes = PhysicalFilesCacheMinutes;
        int clientCacheMinutes = cacheMinutes;

        bool hasVirtualContent = settings.HasVirtualContent();
        if (hasVirtualContent)
        {
            // Use specific cache settings if DB resources are requested
            cacheMinutes = CacheMinutes;
            clientCacheMinutes = ClientCacheMinutes;
        }

        // Try to get data from cache (or store them if not found)
        using (CachedSection<CMSOutputResource> cs = new CachedSection<CMSOutputResource>(ref resource, cacheMinutes, true, null, "getresource", CMSContext.CurrentSiteName, context.Request.QueryString, URLHelper.IsSSL))
        {
            // Not found in cache; load the data
            if (cs.LoadData)
            {
                // Load the data
                resource = GetResource(settings, URLHelper.Url.ToString(), cs.Cached);

                // Cache the file
                if ((resource != null) && cs.Cached)
                {
                    cs.CacheDependency = resource.CacheDependency;
                }

                cs.Data = resource;
            }
        }

        // Send response if there's something to send
        if (resource != null)
        {
            bool allowCache = (!hasVirtualContent || ClientCacheEnabled) && CacheHelper.AlwaysCacheResources;
            SendResponse(context, resource, allowCache, CSSHelper.StylesheetMinificationEnabled, clientCacheMinutes, false);
        }
        else
        {
            SendNotFoundResponse(context);
        }
    }
Ejemplo n.º 29
0
    /// <summary>
    /// Processes the specified document node.
    /// </summary>
    /// <param name="currentAliasPath">Alias path</param>
    /// <param name="currentFileName">File name</param>
    protected void ProcessNode(string currentAliasPath, string currentFileName)
    {
        // Load the document node
        if (node == null)
        {
            // Try to get data from cache
            using (CachedSection<TreeNode> cs = new CachedSection<TreeNode>(ref node, CacheMinutes, !allowLatestVersion, null, "getfilenodebyaliaspath|", CurrentSiteName, CacheHelper.GetBaseCacheKey(false, true), currentAliasPath))
            {
                if (cs.LoadData)
                {
                    // Get the document
                    string className = null;
                    bool combineWithDefaultCulture = SettingsKeyProvider.GetBoolValue(CurrentSiteName + ".CMSCombineImagesWithDefaultCulture");
                    string culture = CultureCode;

                    // Get the document
                    if (currentFileName == null)
                    {
                        // CMS.File
                        className = "CMS.File";
                    }

                    // Get the document data
                    if (!IsLiveSite)
                    {
                        node = DocumentHelper.GetDocument(CurrentSiteName, currentAliasPath, culture, combineWithDefaultCulture, className, null, null, -1, false, null, TreeProvider);
                    }
                    else
                    {
                        node = TreeProvider.SelectSingleNode(CurrentSiteName, currentAliasPath, culture, combineWithDefaultCulture, className, null, null, -1, false, null);

                        // Documents should be combined with default culture
                        if ((node != null) && combineWithDefaultCulture && !node.IsPublished)
                        {
                            // Try to find published document in default culture
                            string defaultCulture = CultureHelper.GetDefaultCulture(CurrentSiteName);
                            TreeNode cultureNode = TreeProvider.SelectSingleNode(CurrentSiteName, currentAliasPath, defaultCulture, false, className, null, null, -1, false, null);
                            if ((cultureNode != null) && cultureNode.IsPublished)
                            {
                                node = cultureNode;
                            }
                        }
                    }

                    // Try to find node using the document aliases
                    if (node == null)
                    {
                        DataSet ds = DocumentAliasInfoProvider.GetDocumentAliases("AliasURLPath='" + SqlHelperClass.GetSafeQueryString(currentAliasPath, false) + "'", "AliasCulture DESC", 1, "AliasNodeID, AliasCulture");
                        if (!DataHelper.DataSourceIsEmpty(ds))
                        {
                            DataRow dr = ds.Tables[0].Rows[0];
                            int nodeId = (int)dr["AliasNodeID"];
                            string nodeCulture = ValidationHelper.GetString(DataHelper.GetDataRowValue(dr, "AliasCulture"), null);
                            if (!IsLiveSite)
                            {
                                node = DocumentHelper.GetDocument(nodeId, nodeCulture, combineWithDefaultCulture, TreeProvider);
                            }
                            else
                            {
                                node = TreeProvider.SelectSingleNode(nodeId, nodeCulture, combineWithDefaultCulture);

                                // Documents should be combined with default culture
                                if ((node != null) && combineWithDefaultCulture && !node.IsPublished)
                                {
                                    // Try to find published document in default culture
                                    string defaultCulture = CultureHelper.GetDefaultCulture(CurrentSiteName);
                                    TreeNode cultureNode = TreeProvider.SelectSingleNode(nodeId, defaultCulture, false);
                                    if ((cultureNode != null) && cultureNode.IsPublished)
                                    {
                                        node = cultureNode;
                                    }
                                }
                            }
                        }
                    }

                    // Cache the document
                    CacheNode(cs, node);
                }
            }
        }

        // Process the document
        ProcessNode(node, null, currentFileName);
    }
Ejemplo n.º 30
0
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            try
            {
                // Prepare alias path
                aliasPath = AliasPath;
                if (String.IsNullOrEmpty(aliasPath))
                {
                    aliasPath = "/%";
                }
                aliasPath = MacroResolver.ResolveCurrentPath(aliasPath);

                // Prepare site name
                siteName = SiteName;
                if (String.IsNullOrEmpty(siteName))
                {
                    siteName = SiteContext.CurrentSiteName;
                }

                // Prepare culture code
                cultureCode = CultureCode;
                if (String.IsNullOrEmpty(cultureCode))
                {
                    cultureCode = LocalizationContext.PreferredCultureCode;
                }

                // Base URL of the links
                string url;
                if (String.IsNullOrEmpty(DocumentListPath))
                {
                    url = RequestContext.CurrentURL;
                }
                else
                {
                    url = DocumentURLProvider.GetUrl(MacroResolver.ResolveCurrentPath(DocumentListPath));
                }
                url = URLHelper.ResolveUrl(url);

                string renderedTags = null;

                // Try to get data from cache
                using (var cs = new CachedSection <string>(ref renderedTags, CacheMinutes, true, CacheItemName, "tagcloud", TagGroupName, OrderBy, SelectTopN, url, TagSeparator, QueryStringName, MaxTagSize, MinTagSize, "documents", siteName, aliasPath, CacheHelper.GetCultureCacheKey(cultureCode), CombineWithDefaultCulture, WhereCondition, SelectOnlyPublished, MaxRelativeLevel))
                {
                    if (cs.LoadData)
                    {
                        // Get the correct range
                        int maxSize = Math.Max(MaxTagSize, MinTagSize);
                        int minSize = Math.Min(MaxTagSize, MinTagSize);

                        // Get the tags
                        SiteInfo si     = SiteInfoProvider.GetSiteInfo(siteName);
                        int      siteId = 0;
                        if (si != null)
                        {
                            siteId = si.SiteID;
                        }

                        // Get tag group info
                        tgi = TagGroupInfoProvider.GetTagGroupInfo(TagGroupName, siteId);

                        // Get the data
                        DataSet ds = null;
                        if (!UseDocumentFilter)
                        {
                            // Get the tag group
                            if (tgi != null)
                            {
                                // Get the tags for group
                                ds = TagInfoProvider.GetTags("TagGroupID = " + tgi.TagGroupID, OrderBy, SelectTopN);
                            }
                        }
                        else
                        {
                            // Get the tags for documents
                            string comleteWhere = TreeProvider.GetCompleteWhereCondition(siteName, aliasPath, cultureCode, CombineWithDefaultCulture, WhereCondition, SelectOnlyPublished, MaxRelativeLevel);
                            ds = TagInfoProvider.GetTags(TagGroupName, siteId, comleteWhere, OrderBy, SelectTopN);
                        }

                        // DS must have at least three columns (fist for IDs, second for names, third for counts)
                        if (!DataHelper.DataSourceIsEmpty(ds))
                        {
                            // First we need to find the maximum and minimum
                            int max = Int32.MinValue;
                            int min = Int32.MaxValue;
                            foreach (DataRow dr in ds.Tables[0].Rows)
                            {
                                int tagCount = ValidationHelper.GetInteger(dr["TagCount"], 0);
                                max = Math.Max(tagCount, max);
                                min = Math.Min(tagCount, min);
                            }

                            // Now generate the tags
                            int count = ds.Tables[0].Rows.Count;

                            StringBuilder sb    = new StringBuilder(count * 100);
                            int           index = 0;

                            // Process the tags
                            foreach (DataRow dr in ds.Tables[0].Rows)
                            {
                                if (index > 0)
                                {
                                    sb.Append(TagSeparator + "\n");
                                }

                                // Count the percentage and get the final size of the tag
                                int tagCount  = ValidationHelper.GetInteger(dr["TagCount"], 0);
                                int val       = (min == max ? 100 : (((tagCount - min) * 100) / (max - min)));
                                int pixelSize = minSize + ((val * (maxSize - minSize)) / 100);

                                // Create the link with query string parameter
                                string paramUrl = URLHelper.AddParameterToUrl(url, QueryStringName, ValidationHelper.GetString(dr["TagID"], ""));
                                sb.Append("<span><a href=\"" + HTMLHelper.HTMLEncode(paramUrl) + "\" style=\"font-size:" + pixelSize.ToString() + "px;\" >" + HTMLHelper.HTMLEncode(dr["TagName"].ToString()) + "</a></span>");

                                index++;
                            }

                            renderedTags = sb.ToString();
                        }

                        // Save to cache
                        if (cs.Cached)
                        {
                            cs.CacheDependency = GetCacheDependency();
                        }

                        cs.Data = renderedTags;
                    }
                }

                if (String.IsNullOrEmpty(renderedTags))
                {
                    // Ensure no data behavior
                    if (HideControlForZeroRows)
                    {
                        Visible = false;
                    }
                    else
                    {
                        renderedTags = ZeroRowsText;
                    }
                }

                // Display the tags
                ltlTags.Text = renderedTags;
            }
            catch (Exception ex)
            {
                // Display the error
                ltlTags.Text = "<div style=\"color: red\">" + ex.Message + "</div>";
            }
        }
    }
Ejemplo n.º 31
0
    /// <summary>
    /// Item databound handler.
    /// </summary>
    protected void rptPostArchive_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        // Select only publish is depend on view mode
        bool selectOnlyPublished = (PageManager.ViewMode.IsLiveSite());

        // Get month NodeID
        int parentId = ValidationHelper.GetInteger((DataHelper.GetDataRowValue(((DataRowView)e.Item.DataItem).Row, "NodeID")), 0);

        TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser);

        // Posts count, default '0'
        int count = 0;
        // Try to get data from cache
        using (var cs = new CachedSection<int>(ref count, CacheMinutes, true, CacheItemName, "postarchivecount", SiteContext.CurrentSiteName, rptPostArchive.Path, LocalizationContext.PreferredCultureCode, parentId, selectOnlyPublished))
        {
            if (cs.LoadData)
            {
                count = tree.SelectNodesCount(SiteContext.CurrentSiteName, rptPostArchive.Path, LocalizationContext.PreferredCultureCode, false, null, "NodeParentID = " + parentId, "", -1, selectOnlyPublished);

                // Save to cache
                if (cs.Cached)
                {
                    cs.CacheDependency = GetCacheDependency();
                }

                cs.Data = count;
            }
        }

        // Set post count as text to the label control in repeater transformation
        if (e.Item.Controls.Count > 0)
        {
            // Try find label control with id 'lblPostCount'
            Label lblCtrl = e.Item.Controls[0].FindControl("lblPostCount") as Label;
            if (lblCtrl != null)
            {
                lblCtrl.Text = count.ToString();
            }
        }
    }
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            mLayoutSeparator = DisplayLayout.ToLower() == "vertical" ? "<br />" : " ";

            DataSet ds = null;

            // Try to get data from cache
            using (CachedSection <DataSet> cs = new CachedSection <DataSet>(ref ds, this.CacheMinutes, true, this.CacheItemName, "languageselection", CMSContext.CurrentSiteName))
            {
                if (cs.LoadData)
                {
                    // Get the data
                    ds = CultureInfoProvider.GetSiteCultures(CMSContext.CurrentSiteName);

                    // Save to the cache
                    if (cs.Cached)
                    {
                        cs.CacheDependency = CacheHelper.GetCacheDependency(new string[] { "cms.culturesite|all", "cms.culture|all" });
                        cs.Data            = ds;
                    }
                }
            }

            if (!DataHelper.DataSourceIsEmpty(ds) && (ds.Tables[0].Rows.Count > 1))
            {
                // Collection of available documents in culture
                Dictionary <string, string> documentCultures = null;
                // Check whether hiding is required or URLs should be generated with lang prefix
                if (this.HideUnavailableCultures || this.UseURLsWithLangPrefix)
                {
                    string cacheItemName = this.CacheItemName;
                    if (!String.IsNullOrEmpty(cacheItemName))
                    {
                        cacheItemName += "prefix";
                    }

                    // Current page info
                    PageInfo currentPageInfo = CMSContext.CurrentPageInfo;

                    // Try to get data from cache
                    using (CachedSection <Dictionary <string, string> > cs = new CachedSection <Dictionary <string, string> >(ref documentCultures, this.CacheMinutes, true, cacheItemName, "languageselectionprefix", CMSContext.CurrentSiteName, currentPageInfo.NodeAliasPath.ToLower()))
                    {
                        if (cs.LoadData)
                        {
                            // Initialize tree provider object
                            TreeProvider tp = new TreeProvider(CMSContext.CurrentUser);
                            tp.FilterOutDuplicates       = false;
                            tp.CombineWithDefaultCulture = false;

                            // Get all language versions
                            DataSet culturesDs = tp.SelectNodes(CMSContext.CurrentSiteName, "/%", TreeProvider.ALL_CULTURES, false, null, "NodeID = " + currentPageInfo.NodeId, null, -1, true, 0, "DocumentCulture, DocumentUrlPath");

                            // Create culture/UrlPath collection
                            if (!DataHelper.DataSourceIsEmpty(culturesDs))
                            {
                                documentCultures = new Dictionary <string, string>();
                                foreach (DataRow dr in culturesDs.Tables[0].Rows)
                                {
                                    string docCulture = ValidationHelper.GetString(dr["DocumentCulture"], String.Empty).ToLower();
                                    string urlPath    = ValidationHelper.GetString(dr["DocumentUrlPath"], String.Empty);
                                    documentCultures.Add(docCulture, urlPath);
                                }
                            }

                            // Add to the cache
                            if (cs.Cached)
                            {
                                cs.CacheDependency = this.GetCacheDependency();
                                cs.Data            = documentCultures;
                            }
                        }
                    }
                }

                // Render the cultures
                ltlHyperlinks.Text = "";

                int count = 0;
                int rows  = ds.Tables[0].Rows.Count;

                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    string cultureCode      = dr["CultureCode"].ToString();
                    string cultureShortName = dr["CultureShortName"].ToString();
                    string cultureAlias     = Convert.ToString(dr["CultureAlias"]);

                    bool documentCultureExists = true;

                    // Check whether exists document in specified culture
                    if ((documentCultures != null) && (this.HideUnavailableCultures))
                    {
                        documentCultureExists = documentCultures.ContainsKey(cultureCode.ToLower());
                    }

                    if (documentCultureExists)
                    {
                        if (!((HideCurrentCulture) && (String.Compare(CMSContext.CurrentDocument.DocumentCulture, cultureCode, true) == 0)))
                        {
                            // Get flag icon URL
                            imgFlagIcon = UIHelper.GetFlagIconUrl(this.Page, cultureCode, "16x16");

                            string url  = null;
                            string lang = cultureCode;
                            // Check whether culture alias is defined and if so use it
                            if (!String.IsNullOrEmpty(cultureAlias))
                            {
                                lang = cultureAlias;
                            }

                            // Get specific url with language prefix
                            if (this.UseURLsWithLangPrefix && documentCultures != null)
                            {
                                string urlPath = String.Empty;
                                if (documentCultures.ContainsKey(cultureCode.ToLower()))
                                {
                                    urlPath = documentCultures[cultureCode.ToLower()];
                                }
                                url  = TreePathUtils.GetUrl(CMSContext.CurrentAliasPath, urlPath, CMSContext.CurrentSiteName, lang);
                                url += URLHelper.GetQuery(URLHelper.CurrentURL);
                                url  = URLHelper.RemoveParameterFromUrl(url, URLHelper.LanguageParameterName);
                                url  = URLHelper.RemoveParameterFromUrl(url, URLHelper.AliasPathParameterName);
                            }
                            // Get URL with lang parameter
                            else
                            {
                                // Build current URL
                                url = URLHelper.CurrentURL;
                                url = URLHelper.RemoveParameterFromUrl(url, URLHelper.LanguageParameterName);
                                url = URLHelper.RemoveParameterFromUrl(url, URLHelper.AliasPathParameterName);
                                url = URLHelper.AddParameterToUrl(url, URLHelper.LanguageParameterName, lang);
                            }

                            if (ShowCultureNames)
                            {
                                // Add flag icon before the link text
                                ltlHyperlinks.Text += "<img src=\"" + imgFlagIcon + "\" alt=\"" + HTMLHelper.HTMLEncode(cultureShortName) + "\" />";
                                ltlHyperlinks.Text += "<a href=\"" + url + "\">";
                                ltlHyperlinks.Text += HTMLHelper.HTMLEncode(cultureShortName);

                                // Set surrounding div css class
                                selectionClass = "languageSelectionWithCultures";
                            }
                            else
                            {
                                ltlHyperlinks.Text += "<a href=\"" + url + "\">" + "<img src=\"" + imgFlagIcon + "\" alt=\"" + HTMLHelper.HTMLEncode(cultureShortName) + "\" />";

                                // Set surrounding div css class
                                selectionClass = "languageSelection";
                            }

                            count++;

                            // Check last item
                            if (count == rows)
                            {
                                ltlHyperlinks.Text += "</a>";
                            }
                            else
                            {
                                ltlHyperlinks.Text += "</a>" + Separator + mLayoutSeparator;
                            }
                        }
                    }
                }
            }
            else
            {
                // Hide if less than two cultures
                Visible = false;
            }

            if (string.IsNullOrEmpty(selectionClass))
            {
                ltrDivOpen.Text = "<div>";
            }
            else
            {
                ltrDivOpen.Text = "<div class=\"" + selectionClass + "\">";
            }
            ltrDivClose.Text = "</div>";

            // Check if RTL hack must be applied
            if (CultureHelper.IsPreferredCultureRTL())
            {
                ltrDivOpen.Text += "<span style=\"visibility:hidden;\">a</span>";
            }
        }
    }
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            repNewsArchive.StopProcessing = true;
        }
        else
        {
            SetContext();

            Newsletter news = null;

            // Try to get data from cache
            using (CachedSection<Newsletter> cs = new CachedSection<Newsletter>(ref news, this.CacheMinutes, true, this.CacheItemName, "newsletterarchive", CMSContext.CurrentSiteName, NewsletterName))
            {
                if (cs.LoadData)
                {
                    // Get the data
                    news = NewsletterProvider.GetNewsletter(NewsletterName, CMSContext.CurrentSite.SiteID);

                    // Add data to the cache
                    if (CacheMinutes > 0)
                    {
                        cs.CacheDependency = GetCacheDependency();
                        cs.Data = news;
                    }
                }
            }

            ReleaseContext();

            if (news != null)
            {
                repNewsArchive.ControlContext = ControlContext;

                repNewsArchive.QueryName = "newsletter.issue.selectall";
                repNewsArchive.OrderBy = "IssueMailoutTime";

                string where = "(IssueNewsletterID = " + news.NewsletterID + ")";

                if (!IgnoreShowInNewsletterArchive)
                {
                    where += " AND (IssueShowInNewsletterArchive = 1)";
                }

                if (SelectOnlySendedIssues)
                {
                    where += " AND (IssueMailoutTime IS NOT NULL) AND (IssueMailoutTime < getDate())";
                }

                repNewsArchive.WhereCondition = where;
                repNewsArchive.TransformationName = TransformationName;
            }
        }
    }
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (this.StopProcessing)
        {
        }
        else
        {
            lblFirstName.Text = this.FirstNameText;
            lblLastName.Text = this.LastNameText;
            lblEmail.Text = this.EmailText;
            lblCaptcha.ResourceString = this.CaptchaText;
            plcCaptcha.Visible = this.DisplayCaptcha;

            if ((this.UseImageButton) && (!String.IsNullOrEmpty(this.ImageButtonURL)))
            {
                pnlButtonSubmit.Visible = false;
                pnlImageSubmit.Visible = true;
                btnImageSubmit.ImageUrl = this.ImageButtonURL;
            }
            else
            {
                pnlButtonSubmit.Visible = true;
                pnlImageSubmit.Visible = false;
                btnSubmit.Text = this.ButtonText;
            }

            // Display labels only if user is logged in and property AllowUserSubscribers is set to true
            if (AllowUserSubscribers && CMSContext.CurrentUser.IsAuthenticated())
            {
                visibleFirstName = false;
                visibleLastName = false;
                visibleEmail = false;
            }
            // Otherwise display text-boxes
            else
            {
                visibleFirstName = true;
                visibleLastName = true;
                visibleEmail = true;
            }

            // Hide first name field if not required
            if (!this.DisplayFirstName)
            {
                visibleFirstName = false;
            }
            // Hide last name field if not required
            if (!this.DisplayLastName)
            {
                visibleLastName = false;
            }

            if (this.NewsletterName.Equals("nwsletuserchoose", StringComparison.InvariantCultureIgnoreCase))
            {
                chooseMode = true;
                plcNwsList.Visible = true;

                if ((!ExternalUse || !RequestHelper.IsPostBack()) && (chklNewsletters.Items.Count == 0))
                {
                    DataSet ds = null;

                    // Try to get data from cache
                    using (CachedSection<DataSet> cs = new CachedSection<DataSet>(ref ds, this.CacheMinutes, true, this.CacheItemName, "newslettersubscription", CMSContext.CurrentSiteName))
                    {
                        if (cs.LoadData)
                        {
                            // Get the data
                            ds = NewsletterProvider.GetAllNewslettersForSite(CMSContext.CurrentSiteID, "NewsletterDisplayName", 0, "NewsletterDisplayName,NewsletterName");

                            // Add data to the cache
                            if (cs.Cached)
                            {
                                cs.CacheDependency = GetCacheDependency();
                                cs.Data = ds;
                            }
                        }
                    }

                    if (!DataHelper.DataSourceIsEmpty(ds))
                    {
                        ListItem li = null;
                        // Fill checkbox list with newsletters
                        foreach (DataRow dr in ds.Tables[0].Rows)
                        {
                            li = new ListItem(HTMLHelper.HTMLEncode(ValidationHelper.GetString(dr["NewsletterDisplayName"], string.Empty)), ValidationHelper.GetString(dr["NewsletterName"], string.Empty));
                            chklNewsletters.Items.Add(li);
                        }
                    }
                }
            }
            else
            {
                // Hide newsletter list
                plcNwsList.Visible = false;
            }

            // Set SkinID properties
            if (!this.StandAlone && (this.PageCycle < PageCycleEnum.Initialized) && (string.IsNullOrEmpty(ValidationHelper.GetString(this.Page.StyleSheetTheme, string.Empty))))
            {
                string skinId = this.SkinID;
                if (!string.IsNullOrEmpty(skinId))
                {
                    lblFirstName.SkinID = skinId;
                    lblLastName.SkinID = skinId;
                    lblEmail.SkinID = skinId;
                    txtFirstName.SkinID = skinId;
                    txtLastName.SkinID = skinId;
                    txtEmail.SkinID = skinId;
                    btnSubmit.SkinID = skinId;
                }
            }
        }
    }
    /// <summary>
    /// Loads the data to the control.
    /// </summary>
    protected void LoadData()
    {
        SetContext();
        string text = string.Empty;
        TreeNode node = null;

        if (Path == string.Empty)
        {
            node = DocumentContext.CurrentDocument;
        }
        else
        {
            // Try to get data from cache
            using (var cs = new CachedSection<TreeNode>(ref node, CacheMinutes, true, CacheItemName, "pagedtext", CacheHelper.GetBaseCacheKey(CheckPermissions, false), SiteName, Path, CultureCode, CombineWithDefaultCulture, SelectOnlyPublished))
            {
                if (cs.LoadData)
                {
                    // Ensure that the path is only for one single document
                    Path = MacroContext.CurrentResolver.ResolvePath(Path.TrimEnd('%').TrimEnd('/'));
                    node = TreeHelper.GetDocument(SiteName, Path, CultureCode, CombineWithDefaultCulture, null, SelectOnlyPublished, CheckPermissions, MembershipContext.AuthenticatedUser);

                    // Prepare the cache dependency
                    if (cs.Cached)
                    {
                        cs.CacheDependency = GetCacheDependency();
                    }

                    cs.Data = node;
                }
            }
        }

        if ((node != null) && (ColumnName != string.Empty))
        {
            text = ValidationHelper.GetString(node.GetValue(ColumnName), string.Empty);

            if (text != string.Empty)
            {
                textPager.TextSource = text;
                textPager.ReloadData(false);
            }
            else
            {
                Visible = false;
            }
        }
        else
        {
            Visible = false;
        }

        ReleaseContext();
    }
Ejemplo n.º 36
0
    /// <summary>
    /// Loads product options.
    /// </summary>
    private void LoadProductOptions()
    {
        DataSet dsCategories = null;

        if (IsLiveSite)
        {
            // Get cache minutes
            int cacheMinutes = SettingsKeyInfoProvider.GetIntValue(SiteContext.CurrentSiteName + ".CMSCacheMinutes");

            // Try to get data from cache
            using (var cs = new CachedSection <DataSet>(ref dsCategories, cacheMinutes, true, null, "skuoptioncategories", SKUID))
            {
                if (cs.LoadData)
                {
                    // Get all option categories for SKU
                    dsCategories = OptionCategoryInfoProvider.GetProductOptionCategories(SKUID, false);

                    // Save to the cache
                    if (cs.Cached)
                    {
                        // Get dependencies
                        var dependencies = new List <string>
                        {
                            "ecommerce.sku|byid|" + SKUID,
                            "ecommerce.optioncategory|all"
                        };

                        // Set dependencies
                        cs.CacheDependency = CacheHelper.GetCacheDependency(dependencies);
                    }

                    cs.Data = dsCategories;
                }
            }
        }
        else
        {
            // Get all option categories for SKU
            dsCategories = OptionCategoryInfoProvider.GetProductOptionCategories(SKUID, false);
        }

        // Initialize product option selectors
        if (!DataHelper.DataSourceIsEmpty(dsCategories))
        {
            mProductOptions = new Hashtable();

            // Is only one option category available for variants?
            var variantCategories = Variants.Any() ? Variants.First().ProductAttributes.CategoryIDs.ToList() : null;
            mOneCategoryUsed = variantCategories != null && variantCategories.Count == 1;

            foreach (DataRow dr in dsCategories.Tables[0].Rows)
            {
                try
                {
                    // Load control for selection product options
                    ProductOptionSelector selector = (ProductOptionSelector)LoadUserControl("~/CMSModules/Ecommerce/Controls/ProductOptions/ProductOptionSelector.ascx");

                    // Add control to the collection
                    var categoryID = ValidationHelper.GetInteger(dr["CategoryID"], 0);
                    selector.ID = "opt" + categoryID;

                    // Init selector
                    selector.LocalShoppingCartObj = ShoppingCart;
                    selector.IsLiveSite           = IsLiveSite;
                    selector.CssClassFade         = CssClassFade;
                    selector.CssClassNormal       = CssClassNormal;
                    selector.SKUID          = SKUID;
                    selector.OptionCategory = new OptionCategoryInfo(dr);

                    // If one category is used, fix the one selector with options to use only options which are not in disabled variants
                    if (mOneCategoryUsed && variantCategories.Contains(categoryID))
                    {
                        var disabled = from variant in Variants
                                       where !variant.Variant.SKUEnabled
                                       from productAttributes in variant.ProductAttributes
                                       select productAttributes.SKUID;

                        var disabledList = disabled.ToList();

                        selector.ProductOptionsInDisabledVariants = disabledList.Any() ? disabledList : null;
                    }

                    // Load all product options
                    foreach (DictionaryEntry entry in selector.ProductOptions)
                    {
                        mProductOptions[entry.Key] = entry.Value;
                    }

                    var lc = selector.SelectionControl as ListControl;
                    if (lc != null)
                    {
                        // Add Index change handler
                        lc.AutoPostBack = true;
                    }

                    pnlSelectors.Controls.Add(selector);
                }
                catch
                {
                }
            }
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        fileGuid = QueryHelper.GetGuid("fileguid", Guid.Empty);

        DebugHelper.SetContext("GetForumAttachment");

        int cacheMinutes = CacheMinutes;

        // Try to get data from cache
        using (var cs = new CachedSection<CMSOutputForumAttachment>(ref outputFile, cacheMinutes, true, null, "getforumattachment", CurrentSiteName, GetBaseCacheKey(), Request.QueryString))
        {
            if (cs.LoadData)
            {
                // Disable caching before check permissions
                cs.CacheMinutes = 0;

                // Process the file
                ProcessFile();

                // Keep original cache minutes if permissions are ok
                cs.CacheMinutes = cacheMinutes;

                // Ensure the cache settings
                if (cs.Cached)
                {
                    // Prepare the cache dependency
                    CMSCacheDependency cd = null;
                    if (outputFile != null)
                    {
                        if (outputFile.ForumAttachment != null)
                        {
                            cd = CacheHelper.GetCacheDependency(outputFile.ForumAttachment.GetDependencyCacheKeys());

                            // Do not cache if too big file which would be stored in memory
                            if (!CacheHelper.CacheImageAllowed(CurrentSiteName, outputFile.ForumAttachment.AttachmentFileSize) && !ForumAttachmentInfoProvider.StoreFilesInFileSystem(CurrentSiteName))
                            {
                                cacheMinutes = largeFilesCacheMinutes;
                            }
                        }
                    }

                    if ((cd == null) && (CurrentSite != null) && (outputFile != null))
                    {
                        // Get the current forum id
                        int forumId = 0;
                        if (outputFile.ForumAttachment != null)
                        {
                            forumId = outputFile.ForumAttachment.AttachmentForumID;
                        }

                        // Set default dependency based on GUID
                        cd = GetCacheDependency(new List<string> { "forumattachment|" + fileGuid.ToString().ToLowerCSafe() + "|" + CurrentSite.SiteID, "forumattachment|" + forumId });
                    }

                    // Cache the data
                    cs.CacheMinutes = cacheMinutes;
                    cs.CacheDependency = cd;
                }

                cs.Data = outputFile;
            }
        }

        // Send the data
        SendFile(outputFile);

        DebugHelper.ReleaseContext();
    }
    /// <summary>
    /// Loads product options.
    /// </summary>
    private void LoadProductOptions()
    {
        DataSet dsCategories = null;

        if (this.IsLiveSite)
        {
            // Get cache minutes
            int cacheMinutes = SettingsKeyProvider.GetIntValue(CMSContext.CurrentSiteName + ".CMSCacheMinutes");

            // Try to get data from cache
            using (CachedSection<DataSet> cs = new CachedSection<DataSet>(ref dsCategories, cacheMinutes, true, null, "skuproductoptions", this.SKUID))
            {
                if (cs.LoadData)
                {
                    // Get the data
                    dsCategories = OptionCategoryInfoProvider.GetSKUOptionCategories(this.SKUID, true);

                    // Save to the cache
                    if (cs.Cached)
                    {
                        cs.CacheDependency = CacheHelper.GetCacheDependency("ecommerce.sku|byid|" + this.SKUID);
                        cs.Data = dsCategories;
                    }
                }
            }
        }
        else
        {
            // Get the data
            dsCategories = OptionCategoryInfoProvider.GetSKUOptionCategories(this.SKUID, true);
        }

        // Initialize product option selectors
        if (!DataHelper.DataSourceIsEmpty(dsCategories))
        {
            this.mProductOptions = new Hashtable();

            foreach (DataRow dr in dsCategories.Tables[0].Rows)
            {
                try
                {
                    // Load control for selection product options
                    ProductOptionSelector selector = (ProductOptionSelector)LoadControl("~/CMSModules/Ecommerce/Controls/ProductOptions/ProductOptionSelector.ascx");

                    selector.ID = "opt" + ValidationHelper.GetInteger(dr["CategoryID"], 0);
                    selector.LocalShoppingCartObj = this.ShoppingCart;
                    selector.ShowPriceIncludingTax = this.ShowPriceIncludingTax;

                    // Set option category data to the selector
                    selector.OptionCategory = new OptionCategoryInfo(dr);

                    // Load all product options
                    foreach (DictionaryEntry entry in selector.ProductOptions)
                    {
                        this.mProductOptions[entry.Key] = entry.Value;
                    }

                    if (this.ShowTotalPrice)
                    {
                        ListControl lc = selector.SelectionControl as ListControl;
                        if (lc != null)
                        {
                            // Add Index change handler
                            lc.AutoPostBack = true;
                            lc.SelectedIndexChanged += new EventHandler(Selector_SelectedIndexChanged);
                        }
                    }

                    // Add control to the collection
                    this.pnlSelectors.Controls.Add(selector);
                }
                catch
                {
                }
            }
        }
    }
    /// <summary>
    /// Returns dataset with categories.
    /// </summary>
    protected DataSet GetDataSet()
    {
        DataSet ds = null;

        // Prepare user id
        int userId = 0;
        if ((MembershipContext.AuthenticatedUser != null) && (MembershipContext.AuthenticatedUser.UserID > 0))
        {
            userId = MembershipContext.AuthenticatedUser.UserID;
        }

        // Try to get data from cache
        using (var cs = new CachedSection<DataSet>(ref ds, CacheMinutes, true, CacheItemName, "categorylist", SiteContext.CurrentSiteName, DisplayGlobalCategories, AllowGlobalCategories, DisplaySiteCategories, DisplayCustomCategories, userId, UseDocumentFilter, AliasPath, CultureCode, MaxRelativeLevel, CombineWithDefaultCulture, SelectOnlyPublished, WhereCondition, StartingCategory))
        {
            if (cs.LoadData)
            {
                string where = GetCompleteWhereCondition();
                if (mUseCompleteWhere)
                {
                    ds = CategoryInfoProvider.GetDocumentCategories(where, OrderBy, SelectTopN);
                }
                else
                {
                    ds = CategoryInfoProvider.GetCategories(where, OrderBy, SelectTopN);
                }

                // Save the result to the cache
                if (cs.Cached)
                {
                    cs.CacheDependency = GetCacheDependency();
                }

                cs.Data = ds;
            }
        }

        return ds;
    }
    /// <summary>
    /// Bind data to repeater.
    /// </summary>
    private void BindData()
    {
        if (MembershipContext.AuthenticatedUser != null)
        {
            int userId = MembershipContext.AuthenticatedUser.UserID;
            int siteId = SiteContext.CurrentSiteID;

            // If sitename was specified
            if (SiteName != String.Empty)
            {
                // Get site ID
                SiteInfo si = SiteInfoProvider.GetSiteInfo(SiteName);
                if (si != null)
                {
                    siteId = si.SiteID;
                }
            }

            // Get user favorites
            DataSet ds = null;

            // Try to get data from cache
            using (var cs = new CachedSection <DataSet>(ref ds, CacheMinutes, true, CacheItemName, "forumfavorites", userId, siteId))
            {
                if (cs.LoadData)
                {
                    // Get the data
                    ds = ForumUserFavoritesInfoProvider.GetFavorites(userId, siteId);

                    // Save to the cache
                    if (cs.Cached)
                    {
                        // Save to the cache
                        cs.CacheDependency = GetCacheDependency();
                    }

                    cs.Data = ds;
                }
            }

            // Bind data, even empty dataset - delete of last item
            rptFavorites.DataSource = ds;
            rptFavorites.DataBind();

            // Hide control if no data
            if (DataHelper.DataSourceIsEmpty(ds))
            {
                if (HideControlForZeroRows)
                {
                    Visible = false;
                }
                else
                {
                    plcEmptyDSTagEnd.Visible   = true;
                    plcEmptyDSTagBegin.Visible = true;
                }
            }
            else
            {
                plcEmptyDSTagEnd.Visible   = false;
                plcEmptyDSTagBegin.Visible = false;
            }
        }
    }
Ejemplo n.º 41
0
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            try
            {
                // Prepare alias path
                aliasPath = AliasPath;
                if (String.IsNullOrEmpty(aliasPath))
                {
                    aliasPath = "/%";
                }
                aliasPath = CMSContext.ResolveCurrentPath(aliasPath);

                // Prepare site name
                siteName = SiteName;
                if (String.IsNullOrEmpty(siteName))
                {
                    siteName = CMSContext.CurrentSiteName;
                }

                // Prepare culture code
                cultureCode = CultureCode;
                if (String.IsNullOrEmpty(cultureCode))
                {
                    cultureCode = CMSContext.PreferredCultureCode;
                }

                string renderedTags = null;

                // Try to get data from cache
                using (CachedSection<string> cs = new CachedSection<string>(ref renderedTags, this.CacheMinutes, true, this.CacheItemName, "tagcloud", TagGroupName, OrderBy, SelectTopN, DocumentListPath, TagSeparator, QueryStringName, MaxTagSize, MinTagSize, "documents", siteName, aliasPath, CacheHelper.GetCultureCacheKey(cultureCode), CombineWithDefaultCulture, WhereCondition, SelectOnlyPublished, MaxRelativeLevel))
                {
                    if (cs.LoadData)
                    {
                        // Get the correct range
                        int maxSize = Math.Max(MaxTagSize, MinTagSize);
                        int minSize = Math.Min(MaxTagSize, MinTagSize);

                        // Get the tags
                        SiteInfo si = SiteInfoProvider.GetSiteInfo(siteName);
                        int siteId = 0;
                        if (si != null)
                        {
                            siteId = si.SiteID;
                        }

                        // Get tag group info
                        tgi = TagGroupInfoProvider.GetTagGroupInfo(TagGroupName, siteId);

                        // Get the data
                        DataSet ds = null;
                        if (!this.UseDocumentFilter)
                        {
                            // Get the tag group
                            if (tgi != null)
                            {
                                // Get the tags for group
                                ds = TagInfoProvider.GetTags("TagGroupID = " + tgi.TagGroupID, OrderBy, SelectTopN);
                            }
                        }
                        else
                        {
                            // Get the tags for documents
                            string comleteWhere = TreeProvider.GetCompleteWhereCondition(siteName, aliasPath, cultureCode, CombineWithDefaultCulture, WhereCondition, SelectOnlyPublished, MaxRelativeLevel);
                            ds = TagInfoProvider.GetTags(TagGroupName, siteId, comleteWhere, OrderBy, SelectTopN);
                        }

                        // DS must have at least three columns (fist for IDs, second for names, third for counts)
                        if (!DataHelper.DataSourceIsEmpty(ds))
                        {
                            // First we need to find the maximum and minimum
                            int max = Int32.MinValue;
                            int min = Int32.MaxValue;
                            foreach (DataRow dr in ds.Tables[0].Rows)
                            {
                                int tagCount = ValidationHelper.GetInteger(dr["TagCount"], 0);
                                max = Math.Max(tagCount, max);
                                min = Math.Min(tagCount, min);
                            }

                            // Base URL of the links
                            string url;
                            if (String.IsNullOrEmpty(DocumentListPath))
                            {
                                url = URLHelper.CurrentURL;
                            }
                            else
                            {
                                url = CMSContext.GetUrl(CMSContext.ResolveCurrentPath(DocumentListPath));
                            }
                            url = URLHelper.ResolveUrl(url);

                            // Now generate the tags
                            int count = ds.Tables[0].Rows.Count;

                            StringBuilder sb = new StringBuilder(count * 100);
                            int index = 0;

                            // Process the tags
                            foreach (DataRow dr in ds.Tables[0].Rows)
                            {
                                if (index > 0)
                                {
                                    sb.Append(TagSeparator + "\n");
                                }

                                // Count the percentage and get the final size of the tag
                                int tagCount = ValidationHelper.GetInteger(dr["TagCount"], 0);
                                int val = (min == max ? 100 : (((tagCount - min) * 100) / (max - min)));
                                int pixelSize = minSize + ((val * (maxSize - minSize)) / 100);

                                // Create the link with query string parameter
                                string paramUrl = URLHelper.AddParameterToUrl(url, QueryStringName, ValidationHelper.GetString(dr["TagID"], ""));
                                sb.Append("<span><a href=\"" + HTMLHelper.HTMLEncode(paramUrl) + "\" style=\"font-size:" + pixelSize.ToString() + "px;\" >" + HTMLHelper.HTMLEncode(dr["TagName"].ToString()) + "</a></span>");

                                index++;
                            }

                            renderedTags = sb.ToString();
                        }

                        // Save to cache
                        if (cs.Cached)
                        {
                            cs.CacheDependency = GetCacheDependency();
                            cs.Data = renderedTags;
                        }
                    }
                }

                if (String.IsNullOrEmpty(renderedTags))
                {
                    // Ensure no data behaviour
                    if (HideControlForZeroRows)
                    {
                        Visible = false;
                    }
                    else
                    {
                        renderedTags = ZeroRowsText;
                    }
                }

                // Display the tags
                ltlTags.Text = renderedTags;
            }
            catch (Exception ex)
            {
                // Display the error
                ltlTags.Text = "<div style=\"color: red\">" + ex.Message + "</div>";
            }
        }
    }
Ejemplo n.º 42
0
    protected void Page_Load(object sender, EventArgs e)
    {
        StringSafeDictionary <object> decodedProperties = new StringSafeDictionary <object>();

        foreach (DictionaryEntry param in properties)
        {
            // Decode special CK editor char
            String str = String.Empty;
            if (param.Value != null)
            {
                str = param.Value.ToString().Replace("%25", "%");
            }

            decodedProperties[param.Key] = HttpUtility.UrlDecode(str);
        }
        properties = decodedProperties;

        string widgetName = ValidationHelper.GetString(properties["name"], String.Empty);

        // Widget name must be specified
        if (String.IsNullOrEmpty(widgetName))
        {
            AddErrorWebPart("widgets.invalidname", null);
            return;
        }

        WidgetInfo wi = WidgetInfoProvider.GetWidgetInfo(widgetName);

        if (wi == null)
        {
            AddErrorWebPart("widget.failedtoload", null);
            return;
        }

        WebPartInfo wpi = WebPartInfoProvider.GetWebPartInfo(wi.WidgetWebPartID);

        if (wpi == null)
        {
            return;
        }

        //no widgets can be used as inline
        if (!wi.WidgetForInline)
        {
            AddErrorWebPart("widgets.cantbeusedasinline", null);
            return;
        }

        try
        {
            FormInfo fi = null;
            DataRow  dr = null;

            using (var cs = new CachedSection <FormInfo>(ref fi, 1440, (PortalContext.ViewMode == ViewModeEnum.LiveSite), null, "inlinewidgetcontrol", wi.WidgetID, wpi.WebPartID))
            {
                if (cs.LoadData)
                {
                    // Merge widget and it's parent webpart properties
                    string props = FormHelper.MergeFormDefinitions(wpi.WebPartProperties, wi.WidgetProperties);

                    // Prepare form
                    WidgetZoneTypeEnum zoneType           = WidgetZoneTypeEnum.Editor;
                    FormInfo           zoneTypeDefinition = PortalFormHelper.GetPositionFormInfo(zoneType);
                    fi = PortalFormHelper.GetWidgetFormInfo(wi.WidgetName, Enum.GetName(typeof(WidgetZoneTypeEnum), zoneType), props, zoneTypeDefinition, true, wi.WidgetDefaultValues);

                    // Apply changed values
                    dr = fi.GetDataRow();
                    fi.LoadDefaultValues(dr);

                    if (cs.Cached)
                    {
                        cs.CacheDependency = CacheHelper.GetCacheDependency("cms.webpart|byid|" + wpi.WebPartID + "\n" + "cms.widget|byid|" + wi.WidgetID);
                    }

                    cs.Data = fi;
                }
            }

            // Get datarow
            if (dr == null)
            {
                dr = fi.GetDataRow();
                fi.LoadDefaultValues(dr);
            }

            // Incorporate inline parameters to datarow
            string publicFields = ";containertitle;container;";
            if (wi.WidgetPublicFileds != null)
            {
                publicFields += ";" + wi.WidgetPublicFileds.ToLowerCSafe() + ";";
            }

            // Load the widget control
            string url = null;

            // Set widget layout
            WebPartLayoutInfo wpli = WebPartLayoutInfoProvider.GetWebPartLayoutInfo(wi.WidgetLayoutID);

            if (wpli != null)
            {
                // Load specific layout through virtual path
                url = wpli.Generalized.GetVirtualFileRelativePath(WebPartLayoutInfo.EXTERNAL_COLUMN_CODE, wpli.WebPartLayoutVersionGUID);
            }
            else
            {
                // Load regularly
                url = WebPartInfoProvider.GetWebPartUrl(wpi, false);
            }

            CMSAbstractWebPart control = (CMSAbstractWebPart)Page.LoadUserControl(url);
            control.PartInstance = new WebPartInstance();

            // Use current page placeholder
            control.PagePlaceholder = PortalHelper.FindParentPlaceholder(this);

            // Set all form values to webpart
            foreach (DataColumn column in dr.Table.Columns)
            {
                object value      = dr[column];
                string columnName = column.ColumnName.ToLowerCSafe();

                //Resolve set values by user
                if (properties.Contains(columnName))
                {
                    FormFieldInfo ffi = fi.GetFormField(columnName);
                    if ((ffi != null) && ffi.Visible && ((ffi.DisplayIn == null) || !ffi.DisplayIn.Contains(FormInfo.DISPLAY_CONTEXT_DASHBOARD)))
                    {
                        value = properties[columnName];
                    }
                }

                // Resolve macros in defined in default values
                if (!String.IsNullOrEmpty(value as string))
                {
                    // Do not resolve macros for public fields
                    if (publicFields.IndexOfCSafe(";" + columnName + ";") < 0)
                    {
                        // Check whether current column
                        bool avoidInjection = control.SQLProperties.Contains(";" + columnName + ";");

                        // Resolve macros
                        MacroSettings settings = new MacroSettings()
                        {
                            AvoidInjection = avoidInjection,
                        };
                        value = control.ContextResolver.ResolveMacros(value.ToString(), settings);
                    }
                }

                control.PartInstance.SetValue(column.ColumnName, value);
            }

            control.PartInstance.IsWidget = true;

            // Load webpart content
            control.OnContentLoaded();

            // Add webpart to controls collection
            Controls.Add(control);

            // Handle DisableViewstate setting
            control.EnableViewState = !control.DisableViewState;
        }

        catch (Exception ex)
        {
            AddErrorWebPart("widget.failedtoload", ex);
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        StringSafeDictionary<object> decodedProperties = new StringSafeDictionary<object>();
        foreach (DictionaryEntry param in Properties)
        {
            // Decode special CK editor char
            String str = String.Empty;
            if (param.Value != null)
            {
                str = param.Value.ToString().Replace("%25", "%");
            }

            decodedProperties[param.Key] = HttpUtility.UrlDecode(str);
        }
        Properties = decodedProperties;

        string widgetName = ValidationHelper.GetString(Properties["name"], String.Empty);

        // Widget name must be specified
        if (String.IsNullOrEmpty(widgetName))
        {
            AddErrorWebPart("widgets.invalidname", null);
            return;
        }

        WidgetInfo wi = WidgetInfoProvider.GetWidgetInfo(widgetName);
        if (wi == null)
        {
            AddErrorWebPart("widget.failedtoload", null);
            return;
        }

        WebPartInfo wpi = WebPartInfoProvider.GetWebPartInfo(wi.WidgetWebPartID);
        if (wpi == null)
        {
            return;
        }

        //no widgets can be used as inline
        if (!wi.WidgetForInline)
        {
            AddErrorWebPart("widgets.cantbeusedasinline", null);
            return;
        }

        try
        {
            FormInfo fi = null;
            DataRow dr = null;

            using (var cs = new CachedSection<FormInfo>(ref fi, 1440, (PortalContext.ViewMode == ViewModeEnum.LiveSite), null, "inlinewidgetcontrol", wi.WidgetID, wpi.WebPartID))
            {
                if (cs.LoadData)
                {
                    // Merge widget and it's parent webpart properties
                    string props = FormHelper.MergeFormDefinitions(wpi.WebPartProperties, wi.WidgetProperties);

                    // Prepare form
                    const WidgetZoneTypeEnum zoneType = WidgetZoneTypeEnum.Editor;
                    fi = PortalFormHelper.GetWidgetFormInfo(wi.WidgetName, zoneType, props, true, wi.WidgetDefaultValues);

                    // Apply changed values
                    dr = fi.GetDataRow();
                    fi.LoadDefaultValues(dr);

                    if (cs.Cached)
                    {
                        cs.CacheDependency = CacheHelper.GetCacheDependency("cms.webpart|byid|" + wpi.WebPartID + "\n" + "cms.widget|byid|" + wi.WidgetID);
                    }

                    cs.Data = fi;
                }
            }

            // Get datarow
            if (dr == null)
            {
                dr = fi.GetDataRow();
                fi.LoadDefaultValues(dr);
            }

            // Incorporate inline parameters to datarow
            string publicFields = ";containertitle;container;";
            if (wi.WidgetPublicFileds != null)
            {
                publicFields += ";" + wi.WidgetPublicFileds.ToLowerCSafe() + ";";
            }

            // Load the widget control
            string url = null;

            // Set widget layout
            WebPartLayoutInfo wpli = WebPartLayoutInfoProvider.GetWebPartLayoutInfo(wi.WidgetLayoutID);

            if (wpli != null)
            {
                // Load specific layout through virtual path
                url = wpli.Generalized.GetVirtualFileRelativePath(WebPartLayoutInfo.EXTERNAL_COLUMN_CODE, wpli.WebPartLayoutVersionGUID);
            }
            else
            {
                // Load regularly
                url = WebPartInfoProvider.GetWebPartUrl(wpi, false);
            }

            CMSAbstractWebPart control = (CMSAbstractWebPart)Page.LoadUserControl(url);
            control.PartInstance = new WebPartInstance();

            // Use current page placeholder
            control.PagePlaceholder = PortalHelper.FindParentPlaceholder(this);

            // Set all form values to webpart
            foreach (DataColumn column in dr.Table.Columns)
            {
                object value = dr[column];
                string columnName = column.ColumnName.ToLowerCSafe();

                //Resolve set values by user
                if (Properties.Contains(columnName))
                {
                    FormFieldInfo ffi = fi.GetFormField(columnName);
                    if ((ffi != null) && ffi.Visible && ((ffi.DisplayIn == null) || !ffi.DisplayIn.Contains(FormInfo.DISPLAY_CONTEXT_DASHBOARD)))
                    {
                        value = Properties[columnName];
                    }
                }

                // Resolve macros in defined in default values
                if (!String.IsNullOrEmpty(value as string))
                {
                    // Do not resolve macros for public fields
                    if (publicFields.IndexOfCSafe(";" + columnName + ";") < 0)
                    {
                        // Check whether current column
                        bool avoidInjection = control.SQLProperties.Contains(";" + columnName + ";");

                        // Resolve macros
                        MacroSettings settings = new MacroSettings()
                        {
                            AvoidInjection = avoidInjection,
                        };
                        value = control.ContextResolver.ResolveMacros(value.ToString(), settings);
                    }
                }

                control.PartInstance.SetValue(column.ColumnName, value);
            }

            control.PartInstance.IsWidget = true;

            // Load webpart content
            control.OnContentLoaded();

            // Add webpart to controls collection
            Controls.Add(control);

            // Handle DisableViewstate setting
            control.EnableViewState = !control.DisableViewState;
        }

        catch (Exception ex)
        {
            AddErrorWebPart("widget.failedtoload", ex);
        }
    }
Ejemplo n.º 44
0
    /// <summary>
    /// Setups control properties.
    /// </summary>
    protected void SetupControl()
    {
        // Check StopProcessing property
        if (StopProcessing)
        {
            Visible = false;
        }
        else
        {
            if (!Service.Entry <ILicenseService>().IsFeatureAvailable(FeatureEnum.OnlineUsers))
            {
                ShowLicenseLimitationError();

                return;
            }

            SetContext();

            DataSet users       = null;
            bool    transLoaded = false;

            // Load transformation
            if (!string.IsNullOrEmpty(TransformationName))
            {
                repUsers.ItemTemplate = TransformationHelper.LoadTransformation(this, TransformationName);
                transLoaded           = true;
            }

            if ((transLoaded) || (!String.IsNullOrEmpty(Path)))
            {
                // Try to get data from cache
                using (var cs = new CachedSection <DataSet>(ref users, CacheMinutes, true, CacheItemName, "onlineusers", SiteContext.CurrentSiteName, SelectTopN, Columns, Path))
                {
                    if (cs.LoadData)
                    {
                        // Get the data
                        users = SessionManager.GetOnlineUsers(null, null, SelectTopN, Columns, MacroResolver.ResolveCurrentPath(Path), SiteContext.CurrentSiteName, false, false);

                        // Prepare the cache dependency
                        if (cs.Cached)
                        {
                            cs.CacheDependency = GetCacheDependency();
                        }

                        cs.Data = users;
                    }
                }

                // Data bind
                if (!DataHelper.DataSourceIsEmpty(users))
                {
                    // Set to repeater
                    repUsers.DataSource = users;
                    repUsers.DataBind();
                }
            }

            int authenticated = 0;
            int publicUsers   = 0;

            string numbers = string.Empty;

            // Get or generate cache item name
            string cacheItemNameNumbers = CacheItemName;
            if (!string.IsNullOrEmpty(cacheItemNameNumbers))
            {
                cacheItemNameNumbers += "Number";
            }

            // Try to get data from cache
            using (var cs = new CachedSection <string>(ref numbers, CacheMinutes, true, cacheItemNameNumbers, "onlineusersnumber", SiteContext.CurrentSiteName, Path))
            {
                if (cs.LoadData)
                {
                    // Get the data
                    SessionManager.GetUsersNumber(CurrentSiteName, MacroResolver.ResolveCurrentPath(Path), false, false, out publicUsers, out authenticated);

                    // Save to the cache
                    if (cs.Cached)
                    {
                        cs.CacheDependency = GetCacheDependency();
                    }

                    cs.Data = publicUsers.ToString() + ";" + authenticated.ToString();
                }
                else if (!String.IsNullOrEmpty(numbers))
                {
                    // Retrieved from cache
                    string[] nums = numbers.Split(';');

                    publicUsers   = ValidationHelper.GetInteger(nums[0], 0);
                    authenticated = ValidationHelper.GetInteger(nums[1], 0);
                }
            }

            // Check if at least one user is online
            if ((publicUsers + authenticated) == 0)
            {
                ltrAdditionaInfos.Text = NoUsersOnlineText;
            }
            else
            {
                ltrAdditionaInfos.Text = string.Format(AdditionalInfoText, publicUsers + authenticated, publicUsers, authenticated);
            }
        }

        ReleaseContext();
    }
    /// <summary>
    /// Loads product options.
    /// </summary>
    private void LoadProductOptions()
    {
        DataSet dsCategories = null;

        if (IsLiveSite)
        {
            // Get cache minutes
            int cacheMinutes = SettingsKeyInfoProvider.GetIntValue(SiteContext.CurrentSiteName + ".CMSCacheMinutes");

            // Try to get data from cache
            using (var cs = new CachedSection<DataSet>(ref dsCategories, cacheMinutes, true, null, "skuoptioncategories", SKUID))
            {
                if (cs.LoadData)
                {
                    // Get all option categories for SKU
                    dsCategories = OptionCategoryInfoProvider.GetProductOptionCategories(SKUID, false);

                    // Save to the cache
                    if (cs.Cached)
                    {
                        // Get dependencies
                        List<string> dependencies = new List<string>();
                        dependencies.Add("ecommerce.sku|byid|" + SKUID);
                        dependencies.Add("ecommerce.optioncategory|all");

                        // Set dependencies
                        cs.CacheDependency = CacheHelper.GetCacheDependency(dependencies);
                    }

                    cs.Data = dsCategories;
                }
            }
        }
        else
        {
            // Get all option categories for SKU
            dsCategories = OptionCategoryInfoProvider.GetProductOptionCategories(SKUID, false);
        }

        // Initialize product option selectors
        if (!DataHelper.DataSourceIsEmpty(dsCategories))
        {
            mProductOptions = new Hashtable();
            // Is only one option category available for variants?
            mOneCategoryUsed = dsCategories.Tables[0].Rows.Count == 1;

            foreach (DataRow dr in dsCategories.Tables[0].Rows)
            {
                try
                {
                    // Load control for selection product options
                    ProductOptionSelector selector = (ProductOptionSelector)LoadUserControl("~/CMSModules/Ecommerce/Controls/ProductOptions/ProductOptionSelector.ascx");

                    // Add control to the collection
                    selector.ID = "opt" + ValidationHelper.GetInteger(dr["CategoryID"], 0);

                    // Init selector
                    selector.LocalShoppingCartObj = ShoppingCart;
                    selector.ShowPriceIncludingTax = ShowPriceIncludingTax;
                    selector.IsLiveSite = IsLiveSite;
                    selector.CssClassFade = CssClassFade;
                    selector.CssClassNormal = CssClassNormal;
                    selector.SKUID = SKUID;
                    selector.OptionCategory = new OptionCategoryInfo(dr);

                    // If one category is used, fix the one selector with options to use only options which are not in disabled variants
                    if (mOneCategoryUsed)
                    {
                        var disabled = from variant in Variants
                                       where !variant.Variant.SKUEnabled
                                       from productAttributes in variant.ProductAttributes
                                       select productAttributes.SKUID;

                        var disabledList = disabled.ToList();

                        selector.ProductOptionsInDisabledVariants = disabledList.Any() ? disabledList : null;
                    }

                    // Load all product options
                    foreach (DictionaryEntry entry in selector.ProductOptions)
                    {
                        mProductOptions[entry.Key] = entry.Value;
                    }

                    ListControl lc = selector.SelectionControl as ListControl;

                    if (lc != null)
                    {
                        // Add Index change handler
                        lc.AutoPostBack = true;
                    }

                    pnlSelectors.Controls.Add(selector);
                }
                catch
                {
                }
            }
        }
    }
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (this.StopProcessing)
        {
        }
        else
        {
            lblFirstName.Text         = this.FirstNameText;
            lblLastName.Text          = this.LastNameText;
            lblEmail.Text             = this.EmailText;
            lblCaptcha.ResourceString = this.CaptchaText;
            plcCaptcha.Visible        = this.DisplayCaptcha;

            if ((this.UseImageButton) && (!String.IsNullOrEmpty(this.ImageButtonURL)))
            {
                pnlButtonSubmit.Visible = false;
                pnlImageSubmit.Visible  = true;
                btnImageSubmit.ImageUrl = this.ImageButtonURL;
            }
            else
            {
                pnlButtonSubmit.Visible = true;
                pnlImageSubmit.Visible  = false;
                btnSubmit.Text          = this.ButtonText;
            }

            // Display labels only if user is logged in and property AllowUserSubscribers is set to true
            if (AllowUserSubscribers && CMSContext.CurrentUser.IsAuthenticated())
            {
                visibleFirstName = false;
                visibleLastName  = false;
                visibleEmail     = false;
            }
            // Otherwise display text-boxes
            else
            {
                visibleFirstName = true;
                visibleLastName  = true;
                visibleEmail     = true;
            }

            // Hide first name field if not required
            if (!this.DisplayFirstName)
            {
                visibleFirstName = false;
            }
            // Hide last name field if not required
            if (!this.DisplayLastName)
            {
                visibleLastName = false;
            }

            if (this.NewsletterName.Equals("nwsletuserchoose", StringComparison.InvariantCultureIgnoreCase))
            {
                chooseMode         = true;
                plcNwsList.Visible = true;

                if ((!ExternalUse || !RequestHelper.IsPostBack()) && (chklNewsletters.Items.Count == 0))
                {
                    DataSet ds = null;

                    // Try to get data from cache
                    using (CachedSection <DataSet> cs = new CachedSection <DataSet>(ref ds, this.CacheMinutes, true, this.CacheItemName, "newslettersubscription", CMSContext.CurrentSiteName))
                    {
                        if (cs.LoadData)
                        {
                            // Get the data
                            ds = NewsletterProvider.GetAllNewslettersForSite(CMSContext.CurrentSiteID, "NewsletterDisplayName", 0, "NewsletterDisplayName,NewsletterName");

                            // Add data to the cache
                            if (cs.Cached)
                            {
                                cs.CacheDependency = GetCacheDependency();
                                cs.Data            = ds;
                            }
                        }
                    }

                    if (!DataHelper.DataSourceIsEmpty(ds))
                    {
                        ListItem li = null;
                        // Fill checkbox list with newsletters
                        foreach (DataRow dr in ds.Tables[0].Rows)
                        {
                            li = new ListItem(HTMLHelper.HTMLEncode(ValidationHelper.GetString(dr["NewsletterDisplayName"], string.Empty)), ValidationHelper.GetString(dr["NewsletterName"], string.Empty));
                            chklNewsletters.Items.Add(li);
                        }
                    }
                }
            }
            else
            {
                // Hide newsletter list
                plcNwsList.Visible = false;
            }

            // Set SkinID properties
            if (!this.StandAlone && (this.PageCycle < PageCycleEnum.Initialized) && (string.IsNullOrEmpty(ValidationHelper.GetString(this.Page.StyleSheetTheme, string.Empty))))
            {
                string skinId = this.SkinID;
                if (!string.IsNullOrEmpty(skinId))
                {
                    lblFirstName.SkinID = skinId;
                    lblLastName.SkinID  = skinId;
                    lblEmail.SkinID     = skinId;
                    txtFirstName.SkinID = skinId;
                    txtLastName.SkinID  = skinId;
                    txtEmail.SkinID     = skinId;
                    btnSubmit.SkinID    = skinId;
                }
            }
        }
    }