コード例 #1
0
ファイル: StringResource.cs プロジェクト: lulzzz/BrandStore
        /// <summary>
        /// Returns a string array of filenames containing all string resource excel files for a given locale
        /// </summary>
        /// <param name="locale">Locale to retrieve string resource files for</param>
        /// <returns></returns>
        public static List <String> GetStringResourceFilesForLocale(string locale)
        {
            List <string> files = new List <string>();

            files.AddRange(Directory.GetFiles(CommonLogic.SafeMapPath("~/stringresources"), "*." + locale + ".xls", SearchOption.TopDirectoryOnly));
            return(files);
        }
コード例 #2
0
        private bool FindIDFile()
        {
            if (m_ID != 0)
            {
                // try to locate by id.htm
                m_URL = Path.Combine(m_Root, m_ID.ToString() + "." + m_LocaleSetting + ".htm");
                m_FN  = CommonLogic.SafeMapPath(m_URL);
                if (CommonLogic.FileExists(m_FN))
                {
                    return(true);
                }

                // try default store locale path:
                m_URL = Path.Combine(m_Root, m_ID.ToString() + "." + Localization.GetDefaultLocale() + ".htm");
                m_FN  = CommonLogic.SafeMapPath(m_URL);
                if (CommonLogic.FileExists(m_FN))
                {
                    return(true);
                }

                // try skin (NULL) path:
                m_URL = Path.Combine(m_Root, m_ID.ToString() + ".htm");
                m_FN  = CommonLogic.SafeMapPath(m_URL);
                if (CommonLogic.FileExists(m_FN))
                {
                    return(true);
                }
            }
            m_URL = String.Empty;
            m_FN  = String.Empty;
            return(false);
        }
コード例 #3
0
 public ConfigurationAtom(String XMLFileName)
 {
     using (XmlTextReader reader = new XmlTextReader(CommonLogic.SafeMapPath(_XmlDirectory + XMLFileName)))
     {
         reader.WhitespaceHandling = WhitespaceHandling.None;
         XmlDocument doc = new XmlDocument();
         doc.Load(reader);
         reader.Close();
         InitFromXML(doc);
     }
 }
コード例 #4
0
 static private String GetWebConfigDefaultLocale()
 {
     if (WebConfigLocale.Length == 0)
     {
         XmlDocument doc = new XmlDocument();
         doc.Load(CommonLogic.SafeMapPath("~/web.config"));                 // Always the top App web.config
         XmlNode node = doc.DocumentElement.SelectSingleNode("/descendant::*[local-name()='globalization']");
         WebConfigLocale = CheckLocaleSettingForProperCase(node.Attributes["culture"].InnerText);
     }
     return(WebConfigLocale);
 }
コード例 #5
0
        public ConfigurationAtom(string xmlFileName)
        {
            string xmlFilePath = CommonLogic.SafeMapPath(String.Format("{0}/{1}{2}", AppLogic.GetAdminDir(), XmlDirectory, xmlFileName));

            using (XmlTextReader reader = new XmlTextReader(xmlFilePath))
            {
                reader.WhitespaceHandling = WhitespaceHandling.None;
                var doc = new XmlDocument();
                doc.Load(reader);
                reader.Close();
                InitFromXML(doc);
            }
        }
コード例 #6
0
        static void ResizeForMicro(string tempFilename, string filename, int microWidth, int microHeight)
        {
            var resizedWidth  = microWidth;
            var resizedHeight = microHeight;

            using (var origPhoto = Image.FromFile(CommonLogic.SafeMapPath(tempFilename)))
            {
                var sourceWidth  = origPhoto.Width;
                var sourceHeight = origPhoto.Height;
                var sourceX      = 0;
                var sourceY      = 0;
                var destX        = -2;
                var destY        = -2;

                var nPercent  = 0f;
                var nPercentW = ((float)resizedWidth / (float)sourceWidth);
                var nPercentH = ((float)resizedHeight / (float)sourceHeight);

                var destWidth  = 0;
                var destHeight = 0;

                if (nPercentH < nPercentW)
                {
                    nPercent = nPercentW;
                    destY    = (int)((resizedHeight - (sourceHeight * nPercent)) / 2) - 2;
                }
                else
                {
                    nPercent = nPercentH;
                    destX    = (int)((resizedWidth - (sourceWidth * nPercent)) / 2) - 2;
                }

                destWidth  = (int)Math.Ceiling(sourceWidth * nPercent) + 4;
                destHeight = (int)Math.Ceiling(sourceHeight * nPercent) + 4;

                using (var resizedPhoto = new Bitmap(resizedWidth, resizedHeight, PixelFormat.Format24bppRgb))
                    using (var grPhoto = Graphics.FromImage(resizedPhoto))
                    {
                        grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        grPhoto.DrawImage(origPhoto,
                                          new Rectangle(destX, destY, destWidth, destHeight),
                                          new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
                                          GraphicsUnit.Pixel);

                        resizedPhoto.Save(filename);
                    }
            }
        }
コード例 #7
0
        private bool FindNameFile()
        {
            try
            {
                m_Name = AppLogic.GetEntityName(m_DescriptionType, m_ID, m_LocaleSetting);

                if (m_Name.Length != 0)
                {
                    // try specified locale
                    m_URL = Path.Combine(m_Root, m_Name + "." + m_LocaleSetting + ".htm");
                    m_FN  = CommonLogic.SafeMapPath(m_URL);
                    if (CommonLogic.FileExists(m_FN))
                    {
                        return(true);
                    }

                    // try default store locale path:
                    m_URL = Path.Combine(m_Root, m_Name + "." + Localization.GetDefaultLocale() + ".htm");
                    m_FN  = CommonLogic.SafeMapPath(m_URL);
                    if (CommonLogic.FileExists(m_FN))
                    {
                        return(true);
                    }

                    // try base (NULL) path:
                    m_URL = Path.Combine(m_Root, m_Name + ".htm");
                    m_FN  = CommonLogic.SafeMapPath(m_URL);
                    if (CommonLogic.FileExists(m_FN))
                    {
                        return(true);
                    }
                }
                m_URL = String.Empty;
                m_FN  = String.Empty;
                return(false);
            }
            catch
            {
                return(false);
            }
        }
コード例 #8
0
        private bool FindSKUFile()
        {
            try
            {
                if (m_ProductSKU.Length != 0)
                {
                    // try specified locale first
                    m_URL = Path.Combine(m_Root, m_ProductSKU + "." + m_LocaleSetting + ".htm");
                    m_FN  = CommonLogic.SafeMapPath(m_URL);
                    if (CommonLogic.FileExists(m_FN))
                    {
                        return(true);
                    }

                    // try default store locale path:
                    m_URL = Path.Combine(m_Root, m_ProductSKU + "." + Localization.GetDefaultLocale() + ".htm");
                    m_FN  = CommonLogic.SafeMapPath(m_URL);
                    if (CommonLogic.FileExists(m_FN))
                    {
                        return(true);
                    }

                    // try base (NULL) path:
                    m_URL = Path.Combine(m_Root, m_ProductSKU + ".htm");
                    m_FN  = CommonLogic.SafeMapPath(m_URL);
                    if (CommonLogic.FileExists(m_FN))
                    {
                        return(true);
                    }
                }
                m_URL = String.Empty;
                m_FN  = String.Empty;
                return(false);
            }
            catch
            {
                return(false);
            }
        }
コード例 #9
0
        /// <summary>
        /// Performs an audit and returns a list of audit issues
        /// </summary>
        public static IEnumerable <SecurityAuditItem> GetAuditIssues(HttpRequestBase request = null)
        {
            // 1. Ensure that SSL is working on the admin site.  An issue with LiveServer can cause SSL not to function.
            if (!CommonLogic.IsSecureConnection())
            {
                yield return new SecurityAuditItem()
                       {
                           Message  = AppLogic.GetString("admin.splash.aspx.security.SSL"),
                           ItemType = SecurityAuditItemType.Security
                       }
            }
            ;

            // 2. Check for path element containing /admin/. We do not allow Admin sites to be located at the default /admin/ path. Too easy to guess.
            if (request != null && request.Path.IndexOf("/admin/", StringComparison.InvariantCultureIgnoreCase) != -1)
            {
                yield return new SecurityAuditItem()
                       {
                           Message  = AppLogic.GetString("admin.splash.aspx.security.PathElement"),
                           ItemType = SecurityAuditItemType.Security
                       }
            }
            ;

            // 3. Remove or change [email protected]. Cannot use the default credentials long-term.
            if (new Customer("*****@*****.**").EMail == "*****@*****.**")
            {
                yield return new SecurityAuditItem()
                       {
                           Message  = AppLogic.GetString("admin.splash.aspx.security.DefaultAdmin"),
                           ItemType = SecurityAuditItemType.Security
                       }
            }
            ;

            // 4. Check MailMe_Server AppConfig Setting. Cannot Allow blank MailMe_Server AppConfig.
            var mailServerConfig = AppLogic.AppConfig("MailMe_Server");

            if (string.IsNullOrWhiteSpace(mailServerConfig) ||
                mailServerConfig.Equals(AppLogic.ro_TBD, StringComparison.InvariantCultureIgnoreCase) ||
                mailServerConfig.Equals("MAIL.YOURDOMAIN.COM", StringComparison.InvariantCultureIgnoreCase))
            {
                yield return new SecurityAuditItem()
                       {
                           Message  = AppLogic.GetString("admin.splash.aspx.security.MailServer"),
                           ItemType = SecurityAuditItemType.Security
                       }
            }
            ;

            // 5. Check for admin\assetmanager folder. Should be deleted.
            if (Directory.Exists(CommonLogic.SafeMapPath("assetmanager")))
            {
                yield return new SecurityAuditItem()
                       {
                           Message  = AppLogic.GetString("admin.splash.aspx.security.AssetManager"),
                           ItemType = SecurityAuditItemType.Security
                       }
            }
            ;

            // 6. Check for match between path and AdminDir. Verify that AdminDir is set correctly.
            if (request != null && request.Path.IndexOf(string.Format("/{0}/", AppLogic.AppConfig("AdminDir")), StringComparison.InvariantCultureIgnoreCase) == -1)
            {
                yield return new SecurityAuditItem()
                       {
                           Message  = AppLogic.GetString("admin.splash.aspx.security.AdminDir"),
                           ItemType = SecurityAuditItemType.Security
                       }
            }
            ;

            if (AppLogic.TrustLevel == AspNetHostingPermissionLevel.Unrestricted || AppLogic.TrustLevel == AspNetHostingPermissionLevel.High)
            {
                var webConfig = WebConfigurationManager.OpenWebConfiguration("~");

                // 7. Check for debug=true in web.config. Should be false on a live site.
                var compilation = (CompilationSection)webConfig.GetSection("system.web/compilation");
                if (compilation.Debug == true)
                {
                    yield return new SecurityAuditItem()
                           {
                               Message  = AppLogic.GetString("admin.splash.aspx.security.Debug"),
                               ItemType = SecurityAuditItemType.Security
                           }
                }
                ;

                // 8. Check encryption on web.config. Must be encrypted as the last step before going Live.
                var appSettings = webConfig.GetSection("appSettings");
                if (!appSettings.SectionInformation.IsProtected)
                {
                    yield return new SecurityAuditItem()
                           {
                               Message  = AppLogic.GetString("admin.splash.aspx.security.Encryption"),
                               ItemType = SecurityAuditItemType.Security
                           }
                }
                ;

                // 9. Check write permissions on web.config. Must have write-permission to encrypt, then have read-only permission after encryption.
                if (FileIsWriteable(CommonLogic.SafeMapPath("~/web.config")))
                {
                    yield return new SecurityAuditItem()
                           {
                               Message  = AppLogic.GetString("admin.splash.aspx.security.WebConfigWritable"),
                               ItemType = SecurityAuditItemType.Security
                           }
                }
                ;

                // 10. Check non-write permissions on root. Cannot allow root folder to have write permission.
                if (FolderIsWriteable(CommonLogic.SafeMapPath("~/")))
                {
                    yield return new SecurityAuditItem()
                           {
                               Message  = AppLogic.GetString("admin.splash.aspx.security.RootWritable"),
                               ItemType = SecurityAuditItemType.Security
                           }
                }
                ;

                // 11. Check for customErrors Mode=Off in web.config. Should be RemoteOnly or On on a Live site.
                var customErrors = (CustomErrorsSection)webConfig.GetSection("system.web/customErrors");
                if (customErrors.Mode == CustomErrorsMode.Off)
                {
                    yield return new SecurityAuditItem()
                           {
                               Message  = AppLogic.GetString("admin.splash.aspx.security.CustomErrors"),
                               ItemType = SecurityAuditItemType.Security
                           }
                }
                ;
            }

            // 12. DotFeed is installed but not enabled.
            if (AppConfigManager.AppConfigExists("DotFeed.AccessKey") && string.IsNullOrEmpty(AppLogic.AppConfig("DotFeed.AccessKey")))
            {
                yield return new SecurityAuditItem()
                       {
                           Message  = AppLogic.GetString("admin.splash.aspx.security.DotFeedNotEnabled"),
                           ItemType = SecurityAuditItemType.Configuration
                       }
            }
            ;

            // 13. Site is using the default Search Engine Meta Title, Description, and Keywords tags.
            if (AppLogic.AppConfig("SE_MetaTitle").ContainsIgnoreCase("Enter your site title here") ||
                AppLogic.AppConfig("SE_MetaDescription").ContainsIgnoreCase("enter your site description here") ||
                AppLogic.AppConfig("SE_MetaKeywords").ContainsIgnoreCase("enter your site keywords here"))
            {
                yield return new SecurityAuditItem()
                       {
                           Message  = AppLogic.GetString("admin.splash.aspx.security.MetaTagsNotSet"),
                           ItemType = SecurityAuditItemType.Configuration
                       }
            }
            ;

            // 14. Time to change the encrypt key
            var nextKeyChangeDate = DateTime.MinValue;

            if (AppLogic.AppConfigBool("StoreCCInDB") &&
                DateTime.TryParse(AppLogic.AppConfig("NextKeyChange"), out nextKeyChangeDate))
            {
                if (nextKeyChangeDate < DateTime.Now)
                {
                    yield return new SecurityAuditItem()
                           {
                               Message  = AppLogic.GetString("admin.default.ChangeEncryptKey"),
                               ItemType = SecurityAuditItemType.Security
                           }
                }
                ;
            }
        }
コード例 #10
0
        public void LoadFromDB()
        {
            string suffix   = "_" + m_ProductID.ToString();
            string pvsuffix = "_" + m_ProductID.ToString() + "_" + m_VariantID.ToString();

            m_ImageNumbersSplit = m_ImageNumbers.Split(',');
            bool m_WatermarksEnabled = AppLogic.AppConfigBool("Watermark.Enabled");


            m_ColorsSplit = new String[1] {
                ""
            };
            if (m_Colors == String.Empty)
            {
                using (SqlConnection dbconn = new SqlConnection(DB.GetDBConn()))
                {
                    dbconn.Open();
                    using (IDataReader rs = DB.GetRS("select Colors from productvariant   with (NOLOCK)  where VariantID=" + m_VariantID.ToString(), dbconn))
                    {
                        if (rs.Read())
                        {
                            m_Colors = DB.RSFieldByLocale(rs, "Colors", Localization.GetDefaultLocale());                             // remember to add "empty" color to front, for no color selected
                            if (m_Colors.Length != 0)
                            {
                                m_ColorsSplit = ("," + m_Colors).Split(',');
                            }
                        }
                    }
                }
            }
            else
            {
                m_ColorsSplit = ("," + m_Colors).Split(',');
            }
            if (m_Colors.Length != 0)
            {
                for (int i = m_ColorsSplit.GetLowerBound(0); i <= m_ColorsSplit.GetUpperBound(0); i++)
                {
                    String s2 = AppLogic.RemoveAttributePriceModifier(m_ColorsSplit[i]);
                    m_ColorsSplit[i] = CommonLogic.MakeSafeFilesystemName(s2);
                }
            }

            if (AppLogic.AppConfigBool("MultiImage.UseProductIconPics"))
            {
                m_ImageUrlsicon = new String[m_ImageNumbersSplit.Length, m_ColorsSplit.Length];
                for (int x = m_ImageNumbersSplit.GetLowerBound(0); x <= m_ImageNumbersSplit.GetUpperBound(0); x++)
                {
                    int ImgIdx = Localization.ParseUSInt(m_ImageNumbersSplit[x]);
                    for (int i = m_ColorsSplit.GetLowerBound(0); i <= m_ColorsSplit.GetUpperBound(0); i++)
                    {
                        String Url = string.Empty;
                        if (m_ProductSKU == string.Empty)
                        {
                            Url = AppLogic.LookupProductImageByNumberAndColor(m_ProductID, m_SkinID, m_LocaleSetting, ImgIdx, AppLogic.RemoveAttributePriceModifier(m_ColorsSplit[i]), "icon");
                        }
                        else
                        {
                            Url = AppLogic.LookupProductImageByNumberAndColor(m_ProductID, m_SkinID, m_ProductSKU, m_LocaleSetting, ImgIdx, AppLogic.RemoveAttributePriceModifier(m_ColorsSplit[i]), "icon");
                        }
                        if (m_WatermarksEnabled && Url.Length != 0 && Url.IndexOf("nopicture") == -1)
                        {
                            if (Url.StartsWith("/"))
                            {
                                m_ImageUrlsicon[x, i] = Url.Substring(HttpContext.Current.Request.ApplicationPath.Length);
                            }
                            else
                            {
                                m_ImageUrlsicon[x, i] = Url.Substring(HttpContext.Current.Request.ApplicationPath.Length - 1);
                            }

                            if (m_ImageUrlsicon[x, i].StartsWith("/"))
                            {
                                m_ImageUrlsicon[x, i] = m_ImageUrlsicon[x, i].TrimStart('/');
                            }
                        }
                        else
                        {
                            m_ImageUrlsicon[x, i] = Url;
                        }
                    }
                }
                for (int x = m_ImageNumbersSplit.GetLowerBound(0); x <= m_ImageNumbersSplit.GetUpperBound(0); x++)
                {
                    int ImgIdx = Localization.ParseUSInt(m_ImageNumbersSplit[x]);
                    if (m_ImageUrlsicon[x, 0].IndexOf("nopicture") == -1)
                    {
                        m_MaxImageIndex = ImgIdx;
                    }
                }
            }

            m_ImageUrlsmedium = new String[m_ImageNumbersSplit.Length, m_ColorsSplit.Length];
            for (int j = m_ImageNumbersSplit.GetLowerBound(0); j <= m_ImageNumbersSplit.GetUpperBound(0); j++)
            {
                int ImgIdx = Localization.ParseUSInt(m_ImageNumbersSplit[j]);
                for (int i = m_ColorsSplit.GetLowerBound(0); i <= m_ColorsSplit.GetUpperBound(0); i++)
                {
                    String Url = string.Empty;
                    if (m_ProductSKU == string.Empty)
                    {
                        Url = AppLogic.LookupProductImageByNumberAndColor(m_ProductID, m_SkinID, m_LocaleSetting, ImgIdx, AppLogic.RemoveAttributePriceModifier(m_ColorsSplit[i]), "medium");
                    }
                    else
                    {
                        Url = AppLogic.LookupProductImageByNumberAndColor(m_ProductID, m_SkinID, m_ProductSKU, m_LocaleSetting, ImgIdx, AppLogic.RemoveAttributePriceModifier(m_ColorsSplit[i]), "medium");
                    }
                    if (m_WatermarksEnabled && Url.Length != 0 && Url.IndexOf("nopicture") == -1)
                    {
                        if (Url.StartsWith("/"))
                        {
                            m_ImageUrlsmedium[j, i] = Url.Substring(HttpContext.Current.Request.ApplicationPath.Length);
                        }
                        else
                        {
                            m_ImageUrlsmedium[j, i] = Url.Substring(HttpContext.Current.Request.ApplicationPath.Length - 1);
                        }

                        if (m_ImageUrlsmedium[j, i].StartsWith("/"))
                        {
                            m_ImageUrlsmedium[j, i] = m_ImageUrlsmedium[j, i].TrimStart('/');
                        }
                    }
                    else
                    {
                        m_ImageUrlsmedium[j, i] = Url;
                    }
                }
            }
            for (int j = m_ImageNumbersSplit.GetLowerBound(0); j <= m_ImageNumbersSplit.GetUpperBound(0); j++)
            {
                int ImgIdx = Localization.ParseUSInt(m_ImageNumbersSplit[j]);
                if (m_ImageUrlsmedium[j, 0].IndexOf("nopicture") == -1)
                {
                    m_MaxImageIndex = ImgIdx;
                }
            }

            m_ImageUrlslarge = new String[m_ImageNumbersSplit.Length, m_ColorsSplit.Length];
            for (int j = m_ImageNumbersSplit.GetLowerBound(0); j <= m_ImageNumbersSplit.GetUpperBound(0); j++)
            {
                int ImgIdx = Localization.ParseUSInt(m_ImageNumbersSplit[j]);
                for (int i = m_ColorsSplit.GetLowerBound(0); i <= m_ColorsSplit.GetUpperBound(0); i++)
                {
                    String Url = string.Empty;
                    if (m_ProductSKU == string.Empty)
                    {
                        Url = AppLogic.LookupProductImageByNumberAndColor(m_ProductID, m_SkinID, m_LocaleSetting, ImgIdx, AppLogic.RemoveAttributePriceModifier(m_ColorsSplit[i]), "large");
                    }
                    else
                    {
                        Url = AppLogic.LookupProductImageByNumberAndColor(m_ProductID, m_SkinID, m_ProductSKU, m_LocaleSetting, ImgIdx, AppLogic.RemoveAttributePriceModifier(m_ColorsSplit[i]), "large");
                    }

                    if (m_WatermarksEnabled && Url.Length != 0 && Url.IndexOf("nopicture") == -1)
                    {
                        if (Url.StartsWith("/"))
                        {
                            m_ImageUrlslarge[j, i] = Url.Substring(HttpContext.Current.Request.ApplicationPath.Length);
                        }
                        else
                        {
                            m_ImageUrlslarge[j, i] = Url.Substring(HttpContext.Current.Request.ApplicationPath.Length - 1);
                        }

                        if (m_ImageUrlslarge[j, i].StartsWith("/"))
                        {
                            m_ImageUrlslarge[j, i] = m_ImageUrlslarge[j, i].TrimStart('/');
                        }

                        m_HasSomeLarge = true;
                    }
                    else if (Url.Length == 0 || Url.IndexOf("nopicture") != -1)
                    {
                        m_ImageUrlslarge[j, i] = String.Empty;
                    }
                    else
                    {
                        m_HasSomeLarge         = true;
                        m_ImageUrlslarge[j, i] = Url;
                    }
                }
            }

            if (!IsEmpty())
            {
                bool AttemptZoomify = AppLogic.AppConfigBool("Zoomify.Active") && (AppLogic.AppConfigBool("Zoomify.GalleryMedium") || AppLogic.AppConfigBool("Zoomify.ProductMedium"));
                bool GalleryZoomify = AttemptZoomify && AppLogic.AppConfigBool("Zoomify.GalleryMedium");

                StringBuilder tmpS = new StringBuilder(4096);
                tmpS.Append("<script type=\"text/javascript\">\n");
                tmpS.Append("var ProductPicIndex" + suffix + " = 1;\n");
                tmpS.Append("var ProductColor" + suffix + " = '';\n");
                tmpS.Append("var boardpics" + suffix + " = new Array();\n");
                tmpS.Append("var boardpicslg" + suffix + " = new Array();\n");
                tmpS.Append("var boardpicslgwidth" + suffix + " = new Array();\n");
                tmpS.Append("var boardpicslgheight" + suffix + " = new Array();\n");
                if (AttemptZoomify)
                {
                    tmpS.Append("var boardpicsZ" + suffix + " = new Array();\n");
                }
                for (int i = 1; i <= m_MaxImageIndex; i++)
                {
                    foreach (String c in m_ColorsSplit)
                    {
                        String MdUrl            = ImageUrl(i, c, "medium").ToLowerInvariant();
                        String MdWatermarkedUrl = MdUrl;

                        if (m_WatermarksEnabled)
                        {
                            if (MdUrl.Length > 0)
                            {
                                string[] split    = MdUrl.Split('/');
                                string   lastPart = split.Last();
                                MdUrl = AppLogic.LocateImageURL(lastPart, "PRODUCT", "medium", "");
                            }
                        }

                        tmpS.Append("boardpics" + suffix + "['" + i.ToString() + "," + c + "'] = '" + MdWatermarkedUrl + "';\n");

                        String LgUrl            = ImageUrl(i, c, "large").ToLowerInvariant();
                        String LgWatermarkedUrl = LgUrl;

                        if (m_WatermarksEnabled)
                        {
                            if (LgUrl.Length > 0)
                            {
                                string[] split    = LgUrl.Split('/');
                                string   lastPart = split.Last();
                                LgUrl = AppLogic.LocateImageURL(lastPart, "PRODUCT", "large", "");
                            }
                        }

                        tmpS.Append("boardpicslg" + suffix + "['" + i.ToString() + "," + c + "'] = '" + LgWatermarkedUrl + "';\n");

                        if (LgUrl.Length > 0)
                        {
                            System.Drawing.Size lgsz = CommonLogic.GetImagePixelSize(LgUrl);
                            tmpS.Append("boardpicslgwidth" + suffix + "['" + i.ToString() + "," + c + "'] = '" + lgsz.Width.ToString() + "';\n");
                            tmpS.Append("boardpicslgheight" + suffix + "['" + i.ToString() + "," + c + "'] = '" + lgsz.Height.ToString() + "';\n");
                        }

                        if (AttemptZoomify)
                        {
                            String ZMdUrl = string.Empty;

                            // Yes we use the large url here, because the Zoomify data is always in Large
                            if (LgUrl.Length > 0)
                            {
                                ZMdUrl = LgUrl.Remove(LgUrl.Length - 4);                                 // remove extension
                            }

                            if (GalleryZoomify && CommonLogic.FileExists(CommonLogic.SafeMapPath(LgUrl)))
                            {
                                tmpS.Append("boardpicsZ" + suffix + "['" + i.ToString() + "," + c + "'] = '" + AppLogic.RunXmlPackage("Zoomify.Medium", null, null, m_SkinID, "", "ImagePath=" + ZMdUrl + "&AltSrc=" + LgUrl, false, false).Replace("\r\n", " ").Replace("\r", " ").Replace("\n", " ").Replace("'", "\\'") + "';\n");                                 // the Replace's are to make the xmlpackage output consumable by javascript
                            }
                            else
                            {
                                tmpS.Append("boardpicsZ" + suffix + "['" + i.ToString() + "," + c + "'] = '';\n");
                            }
                        }
                    }
                }

                if (AttemptZoomify)
                {
                    tmpS.Append("function changeContent(markup)\n");
                    tmpS.Append("{\n");
                    tmpS.Append("	id='divProductPicZ"+ m_ProductID.ToString() + "';\n");
                    tmpS.Append("	if (document.getElementById || document.all)\n");
                    tmpS.Append("	{\n");
                    tmpS.Append("		var el = document.getElementById? document.getElementById(id): document.all[id];\n");
                    tmpS.Append("		if (el && typeof el.innerHTML != \"undefined\") el.innerHTML = markup;\n");
                    tmpS.Append("	}\n");
                    tmpS.Append("}\n");
                }

                tmpS.Append("function changecolorimg" + suffix + "()\n");
                tmpS.Append("{\n");
                tmpS.Append("	var scidx = ProductPicIndex"+ suffix + " + ',' + ProductColor" + suffix + ".toLowerCase();\n");

                if (AttemptZoomify)
                {
                    tmpS.Append("if (boardpicsZ" + suffix + "[scidx]!='') {\n");
                    tmpS.Append("  divProductPicZ" + m_ProductID.ToString() + ".style.display='inline';\n");
                    tmpS.Append("  divProductPic" + m_ProductID.ToString() + ".style.display='none';\n");
                    tmpS.Append("  changeContent(boardpicsZ" + suffix + "[scidx]); }\n");
                    tmpS.Append("else {\n");
                    tmpS.Append("  divProductPicZ" + m_ProductID.ToString() + ".style.display='none';\n");
                    tmpS.Append("  divProductPic" + m_ProductID.ToString() + ".style.display='inline';\n");
                    tmpS.Append("  document.ProductPic" + m_ProductID.ToString() + ".src=boardpics" + suffix + "[scidx]; }\n");
                }
                else
                {
                    tmpS.Append("	document.ProductPic"+ m_ProductID.ToString() + ".src=boardpics" + suffix + "[scidx];\n");
                }

                tmpS.Append("}\n");

                tmpS.Append("function popuplarge" + suffix + "()\n");
                tmpS.Append("{\n");
                tmpS.Append("	var scidx = ProductPicIndex"+ suffix + " + ',' + ProductColor" + suffix + ".toLowerCase();\n");
                tmpS.Append("	var LargeSrc = boardpicslg"+ suffix + "[scidx];\n");

                if (m_WatermarksEnabled)
                {
                    tmpS.AppendFormat("	var imageName = LargeSrc.split(\"/\").pop(-1);{0}", Environment.NewLine);
                    tmpS.AppendFormat("	LargeSrc = 'watermark.axd?size=large&imgurl=images/product/large/' + imageName;{0}", Environment.NewLine);
                }
                tmpS.Append("if(boardpicslg" + suffix + "[scidx] != '')\n");
                tmpS.Append("{\n");
                tmpS.Append("	window.open('popup.aspx?src=' + LargeSrc,'LargerImage"+ CommonLogic.GetRandomNumber(1, 100000) + "','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=" + CommonLogic.IIF(AppLogic.AppConfigBool("ResizableLargeImagePopup"), "yes", "no") + ",resizable=" + CommonLogic.IIF(AppLogic.AppConfigBool("ResizableLargeImagePopup"), "yes", "no") + ",copyhistory=no,width=' + boardpicslgwidth" + suffix + "[scidx] + ',height=' + boardpicslgheight" + suffix + "[scidx] + ',left=0,top=0');\n");
                tmpS.Append("}\n");
                tmpS.Append("else\n");
                tmpS.Append("{\n");
                tmpS.Append("	alert('There is no large image available for this picture');\n");
                tmpS.Append("}\n");
                tmpS.Append("}\n");

                tmpS.Append("function setcolorpicidx" + suffix + "(idx)\n");
                tmpS.Append("{\n");
                tmpS.Append("	ProductPicIndex"+ suffix + " = idx;\n");
                tmpS.Append("	changecolorimg"+ suffix + "();\n");
                tmpS.Append("}\n");

                tmpS.Append("function setActive(element)\n");
                tmpS.Append("{\n");
                tmpS.Append("	adnsf$('li.page-link').removeClass('active');\n");
                tmpS.Append("	adnsf$(element).parent().addClass('active');\n");
                tmpS.Append("}\n");

                tmpS.Append("function cleansizecoloroption" + suffix + "(theVal)\n");
                tmpS.Append("{\n");
                tmpS.Append("   if(theVal.indexOf('[') != -1){theVal = theVal.substring(0, theVal.indexOf('['))}");
                tmpS.Append("	theVal = theVal.replace(/[\\W]/g,\"\");\n");
                tmpS.Append("	theVal = theVal.toLowerCase();\n");
                tmpS.Append("	return theVal;\n");
                tmpS.Append("}\n");

                tmpS.Append("function setcolorpic" + suffix + "(color)\n");
                tmpS.Append("{\n");

                tmpS.Append("	while(color != unescape(color))\n");
                tmpS.Append("	{\n");
                tmpS.Append("		color = unescape(color);\n");
                tmpS.Append("	}\n");

                tmpS.Append("	if(color == '-,-' || color == '-')\n");
                tmpS.Append("	{\n");
                tmpS.Append("		color = '';\n");
                tmpS.Append("	}\n");

                tmpS.Append("	if(color != '' && color.indexOf(',') != -1)\n");
                tmpS.Append("	{\n");

                tmpS.Append("		color = color.substring(0,color.indexOf(',')).replace(new RegExp(\"'\", 'gi'), '');\n");                     // remove sku from color select value

                tmpS.Append("	}\n");
                tmpS.Append("	if(color != '' && color.indexOf('[') != -1)\n");
                tmpS.Append("	{\n");

                tmpS.Append("	    color = color.substring(0,color.indexOf('[')).replace(new RegExp(\"'\", 'gi'), '');\n");
                tmpS.Append("		color = color.replace(/[\\s]+$/g,\"\");\n");

                tmpS.Append("	}\n");
                tmpS.Append("	ProductColor"+ suffix + " = cleansizecoloroption" + suffix + "(color);\n");

                tmpS.Append("	changecolorimg"+ suffix + "();\n");
                tmpS.Append("	setcolorlisttoactiveitem"+ suffix + "(color);\n");
                tmpS.Append("	return (true);\n");
                tmpS.Append("}\n");

                // this one (without suffix) added back for backwards compatibility with older existing product data, where
                // the swatch map called to this js routine directly
                tmpS.Append("function setcolorpic(color)\n");
                tmpS.Append("{\n");

                tmpS.Append("	if(color == '-,-' || color == '-')\n");
                tmpS.Append("	{\n");
                tmpS.Append("		color = '';\n");
                tmpS.Append("	}\n");

                tmpS.Append("	if(color != '' && color.indexOf(',') != -1)\n");
                tmpS.Append("	{\n");

                tmpS.Append("		color = color.substring(0,color.indexOf(',')).replace(new RegExp(\"'\", 'gi'), '');\n");                     // remove sku from color select value

                tmpS.Append("	}\n");
                tmpS.Append("	if(color != '' && color.indexOf('[') != -1)\n");
                tmpS.Append("	{\n");

                tmpS.Append("	    color = color.substring(0,color.indexOf('[')).replace(new RegExp(\"'\", 'gi'), '');\n");
                tmpS.Append("		color = color.replace(/[\\s]+$/g,\"\");\n");

                tmpS.Append("	}\n");
                tmpS.Append("	ProductColor"+ suffix + " = cleansizecoloroption" + suffix + "(color);\n");

                tmpS.Append("	changecolorimg"+ suffix + "();\n");
                tmpS.Append("	setcolorlisttoactiveitem"+ suffix + "(color.toLowerCase());\n");
                tmpS.Append("	return (true);\n");
                tmpS.Append("}\n");

                tmpS.Append("function setcolorlisttoactiveitem" + suffix + "(color)\n");
                tmpS.Append("{\n");

                tmpS.Append("var lst = document.getElementById('Color" + pvsuffix + "');\n");

                tmpS.Append("var matchColor = cleansizecoloroption" + suffix + "(color);\n");

                tmpS.Append("for (var i=0; i < lst.length; i++)\n");
                tmpS.Append("   {\n");

                tmpS.Append("var value = lst[i].value;\n");
                tmpS.Append("var arrayValue = value.split(',');\n");
                tmpS.Append("var lstColor = cleansizecoloroption" + suffix + "(arrayValue[0]);\n");

                //tmpS.Append("	var lstColor = cleansizecoloroption" + suffix + "(lst[i].value);\n");

                tmpS.Append("   if (lstColor == matchColor)\n");
                tmpS.Append("      {\n");
                tmpS.Append("		lst.selectedIndex = i;\n");
                tmpS.Append("		return (true);\n");
                tmpS.Append("      }\n");
                tmpS.Append("   }\n");

                tmpS.Append("return (true);\n");
                tmpS.Append("}\n");

                tmpS.Append("</script>\n");
                m_ImgDHTML = tmpS.ToString();

                bool useMicros = AppLogic.AppConfigBool("UseImagesForMultiNav");

                bool microAction = CommonLogic.IIF(AppLogic.AppConfigBool("UseRolloverForMultiNav"), true, false);

                if (m_MaxImageIndex > 1)
                {
                    tmpS.Remove(0, tmpS.Length);

                    if (!AppLogic.AppConfigBool("MultiImage.UseProductIconPics") && !useMicros)
                    {
                        tmpS.Append("<ul class=\"pagination image-paging\">");
                        for (int i = 1; i <= m_MaxImageIndex; i++)
                        {
                            if (i == 1)
                            {
                                tmpS.Append("<li class=\"page-link active\">");
                            }
                            else
                            {
                                tmpS.Append("<li class=\"page-link\">");
                            }

                            tmpS.Append(string.Format("<a href=\"javascript:void(0);\" onclick='setcolorpicidx{0}({1});setActive(this);' class=\"page-number\">{1}</a>", suffix, i));
                            tmpS.Append("</li>");
                        }
                        tmpS.Append("</ul>");
                    }
                    else
                    {
                        tmpS.Append("<div class=\"product-gallery-items\">");
                        for (int i = 1; i <= m_MaxImageIndex; i++)
                        {
                            tmpS.Append("<div class=\"product-gallery-item\">");
                            tmpS.Append("	<div class=\"gallery-item-inner\">");
                            if (AppLogic.AppConfigBool("MultiImage.UseProductIconPics"))
                            {
                                string strImageTag = "<img class='product-gallery-image' onclick='setcolorpicidx{0}({1});setImageURL(\"{2}\")' alt='Show Picture {1}' src='{2}' border='0' />";
                                tmpS.AppendFormat(strImageTag, new object[] {
                                    suffix,
                                    i,
                                    m_ImageUrlsicon[i - 1, 0].ToString()
                                });
                            }
                            else
                            {
                                // check for different extensions but don't let the non existance leave a gap
                                // or crash because it can't find an image
                                String ImageLoc = String.Empty;
                                if (AppLogic.AppConfigBool("UseSKUForProductImageName"))
                                {
                                    using (SqlConnection dbconn = new SqlConnection(DB.GetDBConn()))
                                    {
                                        dbconn.Open();
                                        using (IDataReader skus = DB.GetRS("SELECT p.SKU FROM Product p  with (NOLOCK)  WHERE p.ProductID=" + m_ProductID.ToString(), dbconn))
                                        {
                                            try
                                            {
                                                String microSKU = String.Empty;
                                                if (skus.Read())
                                                {
                                                    microSKU = DB.RSField(skus, "SKU");
                                                }
                                                ImageLoc = AppLogic.LocateImageURL("images/product/micro/" + microSKU.ToString() + "_" + i.ToString() + ".gif");
                                                if (!CommonLogic.FileExists(ImageLoc))
                                                {
                                                    ImageLoc = AppLogic.LocateImageURL("images/product/micro/" + microSKU.ToString() + "_" + i.ToString() + "_" + ".gif");
                                                }
                                                if (!CommonLogic.FileExists(ImageLoc))
                                                {
                                                    ImageLoc = AppLogic.LocateImageURL("images/product/micro/" + microSKU.ToString() + "_" + i.ToString() + ".jpg");
                                                }
                                                if (!CommonLogic.FileExists(ImageLoc))
                                                {
                                                    ImageLoc = AppLogic.LocateImageURL("images/product/micro/" + microSKU.ToString() + "_" + i.ToString() + "_" + ".jpg");
                                                }
                                                if (!CommonLogic.FileExists(ImageLoc))
                                                {
                                                    ImageLoc = AppLogic.LocateImageURL("images/product/micro/" + microSKU.ToString() + "_" + i.ToString() + ".png");
                                                }
                                                if (!CommonLogic.FileExists(ImageLoc))
                                                {
                                                    ImageLoc = AppLogic.LocateImageURL("images/product/micro/" + microSKU.ToString() + "_" + i.ToString() + "_" + ".png");
                                                }
                                                if (!CommonLogic.FileExists(ImageLoc))
                                                {
                                                    ImageLoc = AppLogic.LocateImageURL("App_Themes/skin_" + m_SkinID + "/images/nopicturemicro.gif");
                                                }
                                            }
                                            catch { }
                                        }
                                    }
                                }
                                else
                                {
                                    ImageLoc = AppLogic.LocateImageURL("images/product/micro/" + m_ProductID.ToString() + "_" + i.ToString() + ".gif");
                                    if (!CommonLogic.FileExists(ImageLoc))
                                    {
                                        ImageLoc = AppLogic.LocateImageURL("images/product/micro/" + m_ProductID.ToString() + "_" + i.ToString() + "_" + ".gif");
                                    }
                                    if (!CommonLogic.FileExists(ImageLoc))
                                    {
                                        ImageLoc = AppLogic.LocateImageURL("images/product/micro/" + m_ProductID.ToString() + "_" + i.ToString() + ".jpg");
                                    }
                                    if (!CommonLogic.FileExists(ImageLoc))
                                    {
                                        ImageLoc = AppLogic.LocateImageURL("images/product/micro/" + m_ProductID.ToString() + "_" + i.ToString() + "_" + ".jpg");
                                    }
                                    if (!CommonLogic.FileExists(ImageLoc))
                                    {
                                        ImageLoc = AppLogic.LocateImageURL("images/product/micro/" + m_ProductID.ToString() + "_" + i.ToString() + ".png");
                                    }
                                    if (!CommonLogic.FileExists(ImageLoc))
                                    {
                                        ImageLoc = AppLogic.LocateImageURL("images/product/micro/" + m_ProductID.ToString() + "_" + i.ToString() + "_" + ".png");
                                    }
                                    if (!CommonLogic.FileExists(ImageLoc))
                                    {
                                        ImageLoc = AppLogic.LocateImageURL("App_Themes/skin_" + m_SkinID + "/images/nopicturemicro.gif");
                                    }
                                }

                                // if not using rollover to change the images
                                if (!microAction && ImageLoc.Length > 0)
                                {
                                    string strImageTag = string.Format("<img class='product-gallery-image' onclick='setcolorpicidx{0}({1});setImageURL(\"{2}\")' alt='Show Picture {1}' src='{2}' border='0' />",
                                                                       new object[]
                                    {
                                        suffix, i, ImageLoc
                                    });
                                    tmpS.Append(strImageTag);
                                }
                                else if (ImageLoc.Length > 0)
                                {
                                    string strImageTag = string.Format("<img class='product-gallery-image' onMouseOver='setcolorpicidx{0}({1});setImageURL(\"{2}\")' alt='Show Picture {1}' src='{2}' border='0' />",
                                                                       new object[]
                                    {
                                        suffix, i, ImageLoc
                                    });
                                    tmpS.Append(strImageTag);
                                }
                            }
                            tmpS.Append("	</div>");
                            tmpS.Append("</div>");
                        }
                        tmpS.Append("</div>");
                    }

                    m_ImgGalIcons = tmpS.ToString();
                }
            }
        }
コード例 #11
0
ファイル: Topic.cs プロジェクト: lulzzz/BrandStore
        // Find the specified topic content. note, we try to find content even if it doesn't exactly match the input specs, by doing an ordered lookup in various areas
        // we want to show SOME topic content if it is at all possible, even if the language is not right, etc...
        // Note: site id only used for file based topic _contents
        // Search Order is (yes, other orderings are possible, but this is the one we chose, where ANY db topic match overrides file content):
        // the other option would be to match on locales in the order of DB/File (Customer Locale), DB/File (Store Locale), DB/File (Null locale)
        // DB (customer locale)
        // DB (store locale)
        // DB (null locale)
        // File (customer locale)
        // File (store locale)
        // File (null locale)
        void LoadFromDB(int StoreID)
        {
            m_FromDB               = false;
            m_DisplayOrder         = 1;
            m_SkinID               = ThisCustomer.SkinID;
            m_StoreID              = StoreID;
            m_LocaleSetting        = CommonLogic.IIF(m_LocaleSetting.Length > 0, m_LocaleSetting, Localization.GetDefaultLocale());
            m_Contents             = String.Empty;
            m_ContentsRAW          = String.Empty;
            m_SectionTitle         = String.Empty;
            m_RequiresSubscription = false;
            m_RequiresDisclaimer   = false;
            m_ShowInSiteMap        = true;
            m_Password             = String.Empty;
            m_SETitle              = m_TopicName;
            m_SEKeywords           = String.Empty;
            m_SEDescription        = String.Empty;
            m_SENoScript           = String.Empty;
            m_FN           = String.Empty;
            m_MasterLocale = m_LocaleSetting;
            m_Children     = new List <int>();
            m_HasChildren  = false;

            if (m_TopicID == 0)
            {
                m_TopicID = Topic.GetTopicID(m_TopicName, CommonLogic.IIF(AppLogic.IsAdminSite, m_MasterLocale, m_LocaleSetting), AppLogic.StoreID());
            }

            if (m_TopicID != 0)
            {
                String sql = String.Format("SELECT * from Topic with (NOLOCK) where Deleted=0 and Published=1 and TopicID={1} and (SkinID IS NULL or SkinID=0 or SkinID={2}) order by DisplayOrder, Name ASC", CommonLogic.IIF(AppLogic.GlobalConfigBool("AllowTopicFiltering") == true, 1, 0), m_TopicID.ToString(), m_SkinID.ToString());

                using (SqlConnection con = new SqlConnection(DB.GetDBConn()))
                {
                    con.Open();
                    using (IDataReader rs = DB.GetRS(sql, con))
                    {
                        if (rs.Read())
                        {
                            m_FromDB               = true;
                            m_TopicID              = DB.RSFieldInt(rs, "TopicID");
                            m_TopicName            = DB.RSField(rs, "Name");
                            m_Contents             = DB.RSFieldByLocale(rs, "Description", m_LocaleSetting);
                            m_Password             = DB.RSField(rs, "Password");
                            m_RequiresSubscription = DB.RSFieldBool(rs, "RequiresSubscription");
                            m_RequiresDisclaimer   = DB.RSFieldBool(rs, "RequiresDisclaimer");
                            m_GraphicsColor        = DB.RSField(rs, "GraphicsColor");
                            m_ContentsBGColor      = DB.RSField(rs, "ContentsBGColor");
                            m_PageBGColor          = DB.RSField(rs, "PageBGColor");
                            m_DisplayOrder         = DB.RSFieldInt(rs, "DisplayOrder");
                            m_ShowInSiteMap        = DB.RSFieldBool(rs, "ShowInSiteMap");
                            m_SkinID               = DB.RSFieldInt(rs, "SkinID");
                            if (m_Contents.Length != 0)
                            {
                                m_ContentsRAW   = m_Contents;
                                m_SectionTitle  = DB.RSFieldByLocale(rs, "Title", m_LocaleSetting);
                                m_SETitle       = DB.RSFieldByLocale(rs, "SETitle", m_LocaleSetting);
                                m_SEKeywords    = DB.RSFieldByLocale(rs, "SEKeywords", m_LocaleSetting);
                                m_SEDescription = DB.RSFieldByLocale(rs, "SEDescription", m_LocaleSetting);
                                m_SENoScript    = DB.RSFieldByLocale(rs, "SENoScript", m_LocaleSetting);
                            }
                            else // nothing found, try master locale:
                            {
                                m_Contents      = DB.RSFieldByLocale(rs, "Description", m_MasterLocale);
                                m_ContentsRAW   = m_Contents;
                                m_SectionTitle  = DB.RSFieldByLocale(rs, "Title", m_MasterLocale);
                                m_SETitle       = DB.RSFieldByLocale(rs, "SETitle", m_MasterLocale);
                                m_SEKeywords    = DB.RSFieldByLocale(rs, "SEKeywords", m_MasterLocale);
                                m_SEDescription = DB.RSFieldByLocale(rs, "SEDescription", m_MasterLocale);
                                m_SENoScript    = DB.RSFieldByLocale(rs, "SENoScript", m_MasterLocale);
                            }

                            // if an html tag is present, extract just the body of the content
                            if (m_Contents.IndexOf("<html", StringComparison.InvariantCultureIgnoreCase) != -1)
                            {
                                m_Contents = CommonLogic.ExtractBody(m_ContentsRAW);
                            }
                        }
                    }
                }

                // loads the child topics
                m_HasChildren = DB.GetSqlN("select count(tm.TopicID) as N from dbo.TopicMapping tm with(NOLOCK) left join dbo.Topic t with(NOLOCK) on t.TopicID = tm.ParentTopicID where t.TopicID =" + m_TopicID.ToString() + " and t.Deleted=0") > 0;

                if (m_HasChildren)
                {
                    LoadChildren();
                }
            }

            if (!m_FromDB)            // did not find anything in db, try file based topic content (in skins folder as topicname.htm)
            {
                string appdir = HttpContext.Current.Request.PhysicalApplicationPath;

                List <string> possibleFileNames = new List <string> {
                    Path.Combine(appdir, string.Format("App_Templates\\Skin_{0}\\Topics\\{1}.{2}.htm", SkinID.ToString(), m_TopicName, m_LocaleSetting)),   //Skin specific, localized
                    Path.Combine(appdir, String.Format("App_Templates\\Skin_{0}\\Topics\\{1}.htm", SkinID.ToString(), m_TopicName)),                        //Skin specific, unlocalized
                    Path.Combine(appdir, string.Format("Topics\\{0}.{1}.htm", m_TopicName, m_LocaleSetting)),                                               //Root folder, localized
                    Path.Combine(appdir, string.Format("Topics\\{0}.htm", m_TopicName)),                                                                    //Root folder, unlocalized
                    Path.Combine(appdir, string.Format("App_Templates\\Skin_{0}\\Topics\\{1}.{2}.html", SkinID.ToString(), m_TopicName, m_LocaleSetting)),  //Skin specific, localized HTML
                    Path.Combine(appdir, String.Format("App_Templates\\Skin_{0}\\Topics\\{1}.html", SkinID.ToString(), m_TopicName)),                       //Skin specific, unlocalized HTML
                    Path.Combine(appdir, string.Format("Topics\\{0}.{1}.html", m_TopicName, m_LocaleSetting)),                                              //Root folder, localized HTML
                    Path.Combine(appdir, string.Format("Topics\\{0}.html", m_TopicName))                                                                    //Root folder, unlocalized HTML
                };

                foreach (string fileNametoCheck in possibleFileNames)
                {
                    m_FN = CommonLogic.SafeMapPath(fileNametoCheck);

                    if (CommonLogic.FileExists(m_FN))
                    {
                        break;
                    }
                }

                if (m_FN.Length != 0 && CommonLogic.FileExists(m_FN))
                {
                    m_Contents     = CommonLogic.ReadFile(m_FN, true);
                    m_ContentsRAW  = m_Contents;
                    m_SectionTitle = CommonLogic.ExtractToken(m_ContentsRAW, "<title>", "</title>");
                    m_Contents     = CommonLogic.ExtractBody(m_Contents);

                    // try old token formats first, for backwards compatibility:
                    m_SETitle       = CommonLogic.ExtractToken(m_ContentsRAW, "<PAGETITLE>", "</PAGETITLE>");
                    m_SEKeywords    = CommonLogic.ExtractToken(m_ContentsRAW, "<PAGEKEYWORDS>", "</PAGEKEYWORDS>");
                    m_SEDescription = CommonLogic.ExtractToken(m_ContentsRAW, "<PAGEDESCRIPTION>", "</PAGEDESCRIPTION>");
                    m_SENoScript    = CommonLogic.ExtractToken(m_ContentsRAW, "<NOSCRIPT>", "</NOSCRIPT>");

                    // if regular HTML tokens found, try to parse it out in regular HTML syntax meta tag format and they take precedence over the old tokens (above):
                    String t = Regex.Match(m_ContentsRAW, @"(?<=<title[^\>]*>).*?(?=</title>)", RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture).Value;
                    if (t.Length != 0)
                    {
                        m_SETitle = t;
                    }

                    String MK = String.Empty;
                    String MV = String.Empty;
                    foreach (Match metamatch in Regex.Matches(m_ContentsRAW, @"<meta\s*(?:(?:\b(\w|-)+\b\s*(?:=\s*(?:""[^""]*""|'[^']*'|[^""'<> ]+)\s*)?)*)/?\s*>", RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture))
                    {
                        MK = String.Empty;
                        MV = String.Empty;
                        // Loop through the attribute/value pairs inside the tag
                        foreach (Match submatch in Regex.Matches(metamatch.Value.ToString(), @"(?<name>\b(\w|-)+\b)\s*=\s*(""(?<value>[^""]*)""|'(?<value>[^']*)'|(?<value>[^""'<> ]+)\s*)+", RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture))
                        {
                            if ("http-equiv".Equals(submatch.Groups[1].ToString(), StringComparison.InvariantCultureIgnoreCase))
                            {
                                MV = submatch.Groups[2].ToString();
                            }
                            if (("name".Equals(submatch.Groups[1].ToString(), StringComparison.InvariantCultureIgnoreCase)) &&
                                MK == String.Empty) // if it's already set, HTTP-EQUIV takes precedence
                            {
                                MV = submatch.Groups[2].ToString();
                            }
                            if ("content".Equals(submatch.Groups[1].ToString(), StringComparison.InvariantCultureIgnoreCase))
                            {
                                MV = submatch.Groups[2].ToString();
                            }
                        }
                        switch (MK.ToLowerInvariant())
                        {
                        case "description":
                            m_SEDescription = MV;
                            break;

                        case "keywords":
                        case "keyword":
                            m_SEKeywords = MV;
                            break;
                        }
                    }
                }

                if (m_CommandHashtable.Contains("contentsbgcolor"))
                {
                    m_ContentsBGColor = m_CommandHashtable["contentsbgcolor"].ToString();
                }
                if (m_CommandHashtable.Contains("pagebgcolor"))
                {
                    m_PageBGColor = m_CommandHashtable["pagebgcolor"].ToString();
                }
                if (m_CommandHashtable.Contains("graphicscolor"))
                {
                    m_GraphicsColor = m_CommandHashtable["graphicscolor"].ToString();
                }
            }

            if (m_SETitle.Length == 0)
            {
                m_SETitle = m_SectionTitle;
            }

            if (AppLogic.ReplaceImageURLFromAssetMgr)
            {
                while (m_Contents.IndexOf("../images") != -1)
                {
                    m_Contents = m_Contents.Replace("../images", "images");
                }
            }
            if (m_UseParser != null)
            {
                m_Contents = m_UseParser.ReplaceTokens(m_Contents);
            }
            else
            {
                if (SkinID > 0)
                {
                    m_Contents = m_Contents.Replace("(!SKINID!)", SkinID.ToString());
                }
            }
        }
コード例 #12
0
ファイル: DownloadItem.cs プロジェクト: giagiigi/WE
        public void Release(bool releaseMaxMindDelay)
        {
            Customer customer = new Customer(this.CustomerId);

            if (this.DownloadLocation == null || this.DownloadLocation.Length == 0)
            {
                string emailSubject = string.Format("{0 } - Download Delayed: Download Location is Empty.", AppLogic.AppConfig("StoreName"));
                string emailBody    = string.Format("Download \"{ 0}\" for OrderNumber {1} and CustomerID {2} was not released to the customer due to there not being a download location specified.  It is in the pending state and can be manually released to the customer via the Orders page in the AspDotNetStorefront Admin once you have assigned a Download Location.  ", this.DownloadName, this.OrderNumber, this.CustomerId);

                NotifyAdminDelayedDownload(customer, emailSubject, emailBody);

                return;
            }

            string finalDownloadLocation = this.DownloadLocation;

            if (AppLogic.AppConfigBool("MaxMind.Enabled"))
            {
                Order order = new Order(this.OrderNumber);
                if (!releaseMaxMindDelay && order.MaxMindFraudScore >= AppLogic.AppConfigNativeDecimal("MaxMind.DelayDownloadThreshold"))
                {
                    string emailSubject = string.Format("{0 } - Download Delayed: Exceeded MaxMind Fraud Score Threshold.", AppLogic.AppConfig("StoreName"));
                    string emailBody    = string.Format("Download \"{ 0}\" for OrderNumber {1} and CustomerID {2} was not released to the customer due to exceeding your MaxMind score threshold for download items.  It is in the pending state and can be manually released to the customer via the Orders page in the AspDotNetStorefront Admin.  ", this.DownloadName, this.OrderNumber, this.CustomerId);

                    NotifyAdminDelayedDownload(customer, emailSubject, emailBody);
                    return;
                }
            }

            if (AppLogic.AppConfigBool("Download.CopyFileForEachOrder") && !this.DownloadLocation.Contains("http:") && !this.DownloadLocation.Contains("https:"))
            {
                try
                {
                    var downloadPath           = CommonLogic.SafeMapPath(this.DownloadLocation);
                    var filename               = Path.GetFileName(downloadPath);
                    var orderDownloadLocation  = string.Format("~/orderdownloads/{0}_{1}", this.OrderNumber, this.CustomerId);
                    var orderDownloadDirectory = CommonLogic.SafeMapPath(orderDownloadLocation);

                    if (!Directory.Exists(orderDownloadDirectory))
                    {
                        Directory.CreateDirectory(orderDownloadDirectory);
                    }

                    var orderDownloadPath = string.Format("{0}/{1}", orderDownloadDirectory, filename);

                    File.Copy(downloadPath, orderDownloadPath, true);

                    finalDownloadLocation = string.Format("{0}/{1}", orderDownloadLocation, filename);
                }
                catch (Exception ex)
                {
                    SysLog.LogException(ex, MessageTypeEnum.GeneralException, MessageSeverityEnum.Error);
                    return;
                }
            }
            using (var cn = new SqlConnection(DB.GetDBConn()))
            {
                cn.Open();
                using (var cmd = new SqlCommand(@"update orders_ShoppingCart set                                
									DownloadReleasedOn=@DownloadReleasedOn,
									DownloadStatus=@DownloadStatus,
									DownloadLocation=@DownloadLocation
									where ShoppingCartRecID=@ShoppingCartRecID"                                    , cn))
                {
                    cmd.Parameters.Add(new SqlParameter("@DownloadReleasedOn", SqlDbType.DateTime));
                    cmd.Parameters.Add(new SqlParameter("@DownloadStatus", SqlDbType.Int));
                    cmd.Parameters.Add(new SqlParameter("@DownloadLocation", SqlDbType.NText));
                    cmd.Parameters.Add(new SqlParameter("@ShoppingCartRecID", SqlDbType.Int));

                    cmd.Parameters["@DownloadReleasedOn"].Value = DateTime.Now;
                    cmd.Parameters["@DownloadStatus"].Value     = (int)DownloadItemStatus.Available;
                    cmd.Parameters["@DownloadLocation"].Value   = finalDownloadLocation;
                    cmd.Parameters["@ShoppingCartRecID"].Value  = this.ShoppingCartRecordId;

                    cmd.ExecuteNonQuery();
                }
            }
        }
コード例 #13
0
 /// <summary>
 /// Returns a string array of filenames containing all string resource excel files for a given locale
 /// </summary>
 /// <param name="locale">Locale to retrieve string resource files for</param>
 /// <returns>A collection of paths to the string resource files for the given locale.</returns>
 public static IEnumerable <string> GetStringResourceFilesForLocale(string locale)
 {
     return(Directory.GetFiles(CommonLogic.SafeMapPath("~/stringresources"), "*." + locale + ".csv", SearchOption.TopDirectoryOnly)
            .Concat(Directory.GetFiles(CommonLogic.SafeMapPath("~/stringresources"), "*." + locale + ".xls", SearchOption.TopDirectoryOnly)));
 }
コード例 #14
0
ファイル: SiteMap.cs プロジェクト: lulzzz/BrandStore
        public SiteMap1(System.Collections.Generic.Dictionary <string, EntityHelper> EntityHelpers, int SkinID, Customer ThisCustomer)
        {
            bool   FromCache = false;
            String CacheName = String.Format("SiteMap1_{0}_{1}", SkinID.ToString(), ThisCustomer.LocaleSetting);

            if (AppLogic.CachingOn)
            {
                m_Contents = (String)HttpContext.Current.Cache.Get(CacheName);
                if (m_Contents != null)
                {
                    FromCache = true;
                }
            }

            if (!FromCache)
            {
                StringBuilder tmpS = new StringBuilder(50000);

                if (AppLogic.IsAdminSite || AppLogic.AppConfigBool("SiteMap.ShowCategories"))
                {
                    // Categories:
                    String s = AppLogic.LookupHelper("Category", 0).GetEntityULList(0, ThisCustomer.LocaleSetting, ThisCustomer.AffiliateID, ThisCustomer.CustomerLevelID, true, AppLogic.AppConfigBool("SiteMap.ShowProducts") && AppLogic.NumProductsInDB < 250, true, "sitemapul", true, 0, String.Empty);
                    if (s.Length != 0)
                    {
                        tmpS.Append("<b>");
                        if (AppLogic.IsAdminSite)
                        {
                            tmpS.Append("<a href=\"newentities.aspx?entityname=category\">");
                        }
                        tmpS.Append(AppLogic.GetString("AppConfig.CategoryPromptPlural", SkinID, ThisCustomer.LocaleSetting).ToUpperInvariant());
                        if (AppLogic.IsAdminSite)
                        {
                            tmpS.Append("</a>");
                        }
                        tmpS.Append("</b>");
                        tmpS.Append(s);
                    }
                }

                if (AppLogic.IsAdminSite || AppLogic.AppConfigBool("SiteMap.ShowSections"))
                {
                    // Sections:
                    String s = AppLogic.LookupHelper("Section", 0).GetEntityULList(0, ThisCustomer.LocaleSetting, ThisCustomer.AffiliateID, ThisCustomer.CustomerLevelID, true, AppLogic.AppConfigBool("SiteMap.ShowProducts") && AppLogic.NumProductsInDB < 250, true, "sitemapul", true, 0, String.Empty);
                    if (s.Length != 0)
                    {
                        tmpS.Append("<b>");
                        if (AppLogic.IsAdminSite)
                        {
                            tmpS.Append("<a href=\"newentities.aspx?entityname=section\">");
                        }
                        tmpS.Append(AppLogic.GetString("AppConfig.SectionPromptPlural", SkinID, ThisCustomer.LocaleSetting).ToUpperInvariant());
                        if (AppLogic.IsAdminSite)
                        {
                            tmpS.Append("</a>");
                        }
                        tmpS.Append("</b>");
                        tmpS.Append(s);
                    }
                }

                if (AppLogic.IsAdminSite || AppLogic.AppConfigBool("SiteMap.ShowLibraries"))
                {
                    // Libraries:
                    String s = AppLogic.LookupHelper("Library", 0).GetEntityULList(0, ThisCustomer.LocaleSetting, ThisCustomer.AffiliateID, ThisCustomer.CustomerLevelID, AppLogic.AppConfigBool("SiteMap.ShowDocuments"), true, true, "sitemapul", true, 0, String.Empty);
                    if (s.Length != 0)
                    {
                        tmpS.Append("<b>");
                        if (AppLogic.IsAdminSite)
                        {
                            tmpS.Append("<a href=\"newentities.aspx?entityname=library\">");
                        }
                        tmpS.Append(AppLogic.GetString("AppConfig.LibraryPromptPlural", SkinID, ThisCustomer.LocaleSetting).ToUpperInvariant());
                        if (AppLogic.IsAdminSite)
                        {
                            tmpS.Append("</a>");
                        }
                        tmpS.Append("</b>");
                        tmpS.Append(s);
                    }
                }

                if (AppLogic.IsAdminSite || AppLogic.AppConfigBool("SiteMap.ShowManufacturers"))
                {
                    // Manufacturers:
                    String s = AppLogic.LookupHelper("Manufacturer", 0).GetEntityULList(0, ThisCustomer.LocaleSetting, ThisCustomer.AffiliateID, ThisCustomer.CustomerLevelID, false, AppLogic.AppConfigBool("SiteMap.ShowProducts") && AppLogic.NumProductsInDB < 250, true, "sitemapul", true, 0, String.Empty);
                    if (s.Length != 0)
                    {
                        tmpS.Append("<b>");
                        if (AppLogic.IsAdminSite)
                        {
                            tmpS.Append("<a href=\"newentities.aspx?entityname=manufacturer\">");
                        }
                        tmpS.Append(AppLogic.GetString("AppConfig.ManufacturerPromptPlural", SkinID, ThisCustomer.LocaleSetting).ToUpperInvariant());
                        if (AppLogic.IsAdminSite)
                        {
                            tmpS.Append("</a>");
                        }
                        tmpS.Append("</b>");
                        tmpS.Append(s);
                    }
                }

                if (AppLogic.IsAdminSite || AppLogic.AppConfigBool("SiteMap.ShowTopics"))
                {
                    // Topics:
                    tmpS.Append("<b>");
                    if (AppLogic.IsAdminSite)
                    {
                        tmpS.Append("<a href=\"topics.aspx\">");
                    }
                    tmpS.Append(AppLogic.GetString("sitemap.aspx.2", SkinID, ThisCustomer.LocaleSetting).ToUpperInvariant());
                    if (AppLogic.IsAdminSite)
                    {
                        tmpS.Append("</a>");
                    }
                    tmpS.Append("</b>");
                    tmpS.Append("<ul class=\"sitemapul\">\n");

                    using (SqlConnection dbconn = DB.dbConn())
                    {
                        dbconn.Open();
                        using (IDataReader rs = DB.GetRS(string.Format("select count(*) as N from Topic with (NOLOCK) where {0} Deleted=0 AND Published=1 and (SkinID IS NULL or SkinID=0 or SkinID={1}) ", CommonLogic.IIF(AppLogic.IsAdminSite, "", "ShowInSiteMap=1 and "), SkinID.ToString()) + "; " + string.Format("select Name,Title,TopicID from Topic with (NOLOCK) where {0} Deleted=0 and Published=1 and (SkinID IS NULL or SkinID=0 or SkinID={1}) Order By DisplayOrder, Name ASC", CommonLogic.IIF(AppLogic.IsAdminSite, "", "ShowInSiteMap=1 and "), SkinID.ToString()), dbconn))
                        {
                            if (rs.Read() && DB.RSFieldInt(rs, "N") > 0)
                            {
                                if (rs.NextResult())
                                {
                                    while (rs.Read())
                                    {
                                        tmpS.Append("<li>");
                                        if (AppLogic.IsAdminSite)
                                        {
                                            tmpS.Append(String.Format("<a href=\"edittopic.aspx?topicid={0}\">", DB.RSFieldInt(rs, "TopicID").ToString()));
                                        }
                                        else
                                        {
                                            tmpS.Append("<a href=\"" + SE.MakeDriverLink(DB.RSFieldByLocale(rs, "Name", Localization.GetDefaultLocale())) + "\">");
                                        }
                                        tmpS.Append(Security.HtmlEncode(DB.RSFieldByLocale(rs, "Title", Localization.GetDefaultLocale())));
                                        tmpS.Append("</a>");
                                        tmpS.Append("</li>\n");
                                    }
                                }
                            }
                        }
                    }

                    // File Topics:
                    // create an array to hold the list of files
                    ArrayList fArray = new ArrayList();

                    // get information about our initial directory
                    String SFP = CommonLogic.SafeMapPath(CommonLogic.IIF(AppLogic.IsAdminSite, "../", "") + "App_Templates/Skin_" + SkinID.ToString() + "/template.htm").Replace("template.htm", "");

                    DirectoryInfo dirInfo = new DirectoryInfo(SFP);

                    // retrieve array of files & subdirectories
                    FileSystemInfo[] myDir = dirInfo.GetFileSystemInfos();

                    for (int i = 0; i < myDir.Length; i++)
                    {
                        // check the file attributes

                        // if a subdirectory, add it to the sArray
                        // otherwise, add it to the fArray
                        if (((Convert.ToUInt32(myDir[i].Attributes) & Convert.ToUInt32(FileAttributes.Directory)) > 0))
                        {
                        }
                        else
                        {
                            bool skipit = false;
                            if (!myDir[i].FullName.EndsWith("htm", StringComparison.InvariantCultureIgnoreCase) ||
                                (myDir[i].FullName.IndexOf("TEMPLATE", StringComparison.InvariantCultureIgnoreCase) != -1) ||
                                (myDir[i].FullName.IndexOf("AFFILIATE_", StringComparison.InvariantCultureIgnoreCase) != -1) ||
                                (myDir[i].FullName.IndexOf(AppLogic.ro_PMMicropay, StringComparison.InvariantCultureIgnoreCase) != -1))
                            {
                                skipit = true;
                            }
                            if (!skipit)
                            {
                                fArray.Add(Path.GetFileName(myDir[i].FullName));
                            }
                        }
                    }

                    if (fArray.Count != 0)
                    {
                        // sort the files alphabetically
                        fArray.Sort(0, fArray.Count, null);
                        for (int i = 0; i < fArray.Count; i++)
                        {
                            tmpS.Append("<li>");
                            if (!AppLogic.IsAdminSite) // admin site can't link to these kinds of topics
                            {
                                tmpS.Append("<a href=\"" + SE.MakeDriverLink(fArray[i].ToString().Replace(".htm", "")) + "\">");
                            }
                            else
                            {
                                tmpS.Append("(file based topic) ");
                            }
                            tmpS.Append(Security.HtmlEncode(CommonLogic.Capitalize(fArray[i].ToString().Replace(".htm", ""))));
                            if (!AppLogic.IsAdminSite)
                            {
                                tmpS.Append("</a>");
                            }
                            tmpS.Append("</li>\n");
                        }
                    }
                    tmpS.Append("</ul>\n");
                }
                m_Contents = tmpS.ToString();
                if (AppLogic.CachingOn)
                {
                    HttpContext.Current.Cache.Insert(CacheName, m_Contents, null, System.DateTime.Now.AddMinutes(AppLogic.CacheDurationMinutes()), TimeSpan.Zero);
                }
            }
        }
コード例 #15
0
        /// <summary>
        /// Performs an audit and returns a list of audit issues
        /// </summary>
        public static IEnumerable <SecurityAuditItem> GetAuditIssues(HttpRequestBase request = null)
        {
            // 1. Ensure that SSL is working on the admin site.  An issue with LiveServer can cause SSL not to function.
            if (!CommonLogic.IsSecureConnection())
            {
                yield return new SecurityAuditItem()
                       {
                           Message  = "Your Admin site is not currently using SSL.  This can allow data being sent to and from the admin site to be read in transit.  <a href='http://www.aspdotnetstorefront.com/linkmanager.aspx?topic=10000manual&type=ssl' target='_blank'>Click Here</a> to learn how to enable SSL.",
                           ItemType = SecurityAuditItemType.Security
                       }
            }
            ;

            // 2. Check for path element containing /admin/. We do not allow Admin sites to be located at the default /admin/ path. Too easy to guess.
            if (request != null && request.Path.IndexOf("/admin/", StringComparison.InvariantCultureIgnoreCase) != -1)
            {
                yield return new SecurityAuditItem()
                       {
                           Message  = "The URL to your Admin site contains '/admin/'. This does not follow our <a href='http://www.aspdotnetstorefront.com/linkmanager.aspx?topic=10000manual&type=securitybestpractices' target='_blank'>security best practices</a>. Please immediately rename the Admin folder, and restart the website.",
                           ItemType = SecurityAuditItemType.Security
                       }
            }
            ;

            // 3. Remove or change [email protected]. Cannot use the default credentials long-term.
            if (new Customer("*****@*****.**").EMail == "*****@*****.**")
            {
                yield return new SecurityAuditItem()
                       {
                           Message  = "The default user '*****@*****.**' is a registered user on this website. <a href='customers.aspx?filter.0.0=admin%40aspdotnetstorefront.com'>Click Here</a> to edit this user.",
                           ItemType = SecurityAuditItemType.Security
                       }
            }
            ;

            // 4. Check MailMe_Server AppConfig Setting. Cannot Allow blank MailMe_Server AppConfig.
            var mailServerConfig = AppLogic.AppConfig("MailMe_Server");

            if (string.IsNullOrWhiteSpace(mailServerConfig) ||
                mailServerConfig.Equals(AppLogic.ro_TBD, StringComparison.InvariantCultureIgnoreCase) ||
                mailServerConfig.Equals("MAIL.YOURDOMAIN.COM", StringComparison.InvariantCultureIgnoreCase))
            {
                yield return new SecurityAuditItem()
                       {
                           Message  = "The 'MailMe_Server' Setting is not properly configured. Click <a href=\"mailingtest.aspx\">here</a> to configure mail settings.",
                           ItemType = SecurityAuditItemType.Security
                       }
            }
            ;

            // 5. Check for admin\assetmanager folder. Should be deleted.
            if (Directory.Exists(CommonLogic.SafeMapPath("assetmanager")))
            {
                yield return new SecurityAuditItem()
                       {
                           Message  = "The obsolete folder 'assetmanager' exists in your site's Admin folder, and can present a security risk. Please delete this folder and its contents.",
                           ItemType = SecurityAuditItemType.Security
                       }
            }
            ;

            // 6. Check for match between path and AdminDir. Verify that AdminDir is set correctly.
            if (request != null && request.Path.IndexOf(string.Format("/{0}/", AppLogic.AppConfig("AdminDir")), StringComparison.InvariantCultureIgnoreCase) == -1)
            {
                yield return new SecurityAuditItem()
                       {
                           Message  = "The URL to your Admin site does not match the 'AdminDir' Setting, which can lead to disclosure of your Admin URL. Please update the 'AdminDir' Setting, using the 'Configuration -> Settings' menu.",
                           ItemType = SecurityAuditItemType.Security
                       }
            }
            ;

            if (AppLogic.TrustLevel == AspNetHostingPermissionLevel.Unrestricted || AppLogic.TrustLevel == AspNetHostingPermissionLevel.High)
            {
                var webConfig = WebConfigurationManager.OpenWebConfiguration("~");

                // 7. Check for debug=true in web.config. Should be false on a live site.
                var compilation = (CompilationSection)webConfig.GetSection("system.web/compilation");
                if (compilation.Debug == true)
                {
                    yield return new SecurityAuditItem()
                           {
                               Message  = "The 'compilation' element in web.config is set to 'debug=true'. Please set it to 'debug=false' to improve site performance.",
                               ItemType = SecurityAuditItemType.Security
                           }
                }
                ;

                // 8. Check encryption on web.config. Must be encrypted as the last step before going Live.
                var appSettings = webConfig.GetSection("appSettings");
                if (!appSettings.SectionInformation.IsProtected)
                {
                    yield return new SecurityAuditItem()
                           {
                               Message  = "The web.config file is not encrypted. This does not follow our <a href='http://www.aspdotnetstorefront.com/linkmanager.aspx?topic=10000manual&type=securitybestpractices' target='_blank'>security best practices</a>. Please use the <a href='wizard.aspx'>Site Setup Wizard</a> to encrypt the web.config file before going Live.",
                               ItemType = SecurityAuditItemType.Security
                           }
                }
                ;

                // 9. Check write permissions on web.config. Must have write-permission to encrypt, then have read-only permission after encryption.
                if (FileIsWriteable(CommonLogic.SafeMapPath("~/web.config")))
                {
                    yield return new SecurityAuditItem()
                           {
                               Message  = "The file permission on web.config allows for write-access. This does not follow our <a href='http://www.aspdotnetstorefront.com/linkmanager.aspx?topic=10000manual&type=securitybestpractices' target=\"_blank\">security best practices</a>. Please set the web.config file as read-only before going Live.",
                               ItemType = SecurityAuditItemType.Security
                           }
                }
                ;

                // 10. Check non-write permissions on root. Cannot allow root folder to have write permission.
                if (FolderIsWriteable(CommonLogic.SafeMapPath("~/")))
                {
                    yield return new SecurityAuditItem()
                           {
                               Message  = "The root directory of your website allows write-access. Please remove write-access before going Live. <a href='http://www.aspdotnetstorefront.com/linkmanager.aspx?topic=10000manual&type=golive' target='_blank'>Read more</a>",
                               ItemType = SecurityAuditItemType.Security
                           }
                }
                ;

                // 11. Check for customErrors Mode=Off in web.config. Should be RemoteOnly or On on a Live site.
                var customErrors = (CustomErrorsSection)webConfig.GetSection("system.web/customErrors");
                if (customErrors.Mode == CustomErrorsMode.Off)
                {
                    yield return new SecurityAuditItem()
                           {
                               Message  = "The 'customErrors' element in web.config is set to 'off'. Please set it to 'on' before going Live. <a href='http://www.aspdotnetstorefront.com/linkmanager.aspx?topic=10000manual&type=golive' target=\"_blank\">Read more</a>",
                               ItemType = SecurityAuditItemType.Security
                           }
                }
                ;
            }

            // 12. DotFeed is installed but not enabled.
            if (AppConfigManager.AppConfigExists("DotFeed.AccessKey") && string.IsNullOrEmpty(AppLogic.AppConfig("DotFeed.AccessKey")))
            {
                yield return new SecurityAuditItem()
                       {
                           Message = "DotFeed is installed but not enabled, <a href=\"https://manage.dotfeed.com\" target=\"_blank\">click here</a> to configure DotFeed",

                           ItemType = SecurityAuditItemType.Configuration
                       }
            }
            ;

            // 13. Site is using the default Search Engine Meta Title, Description, and Keywords tags.
            if (AppLogic.AppConfig("SE_MetaTitle").ContainsIgnoreCase("Enter your site title here") ||
                AppLogic.AppConfig("SE_MetaDescription").ContainsIgnoreCase("enter your site description here") ||
                AppLogic.AppConfig("SE_MetaKeywords").ContainsIgnoreCase("enter your site keywords here"))
            {
                yield return new SecurityAuditItem()
                       {
                           Message  = "Your site is using the default Search Engine Meta Title & Description tags, <a href=\"wizard.aspx#trSEO\">click here</a> to update.",
                           ItemType = SecurityAuditItemType.Configuration
                       }
            }
            ;

            // 14. Time to change the encrypt key
            var nextKeyChangeDate = DateTime.MinValue;

            if (AppLogic.AppConfigBool("StoreCCInDB") &&
                DateTime.TryParse(AppLogic.AppConfig("NextKeyChange"), out nextKeyChangeDate))
            {
                if (nextKeyChangeDate < DateTime.Now)
                {
                    yield return new SecurityAuditItem()
                           {
                               Message  = "Time To Change Your Encrypt Key!",
                               ItemType = SecurityAuditItemType.Security
                           }
                }
                ;
            }
        }
コード例 #16
0
        public void Release(bool releaseMaxMindDelay)
        {
            Customer customer = new Customer(this.CustomerId);

            if (this.DownloadLocation == null || this.DownloadLocation.Length == 0)
            {
                string emailSubject = string.Format(AppLogic.GetString("notification.downloaddelayed.3", customer.SkinID, customer.LocaleSetting), AppLogic.AppConfig("StoreName"));
                string emailBody    = string.Format(AppLogic.GetString("notification.downloaddelayed.4", customer.SkinID, customer.LocaleSetting), this.DownloadName, this.OrderNumber, this.CustomerId);

                NotifyAdminDelayedDownload(customer, emailSubject, emailBody);

                return;
            }

            string finalDownloadLocation = this.DownloadLocation;

            if (AppLogic.AppConfigBool("MaxMind.Enabled"))
            {
                Order order = new Order(this.OrderNumber);
                if (!releaseMaxMindDelay && order.MaxMindFraudScore >= AppLogic.AppConfigNativeDecimal("MaxMind.DelayDownloadThreshold"))
                {
                    string emailSubject = string.Format(AppLogic.GetString("notification.downloaddelayed.1", customer.SkinID, customer.LocaleSetting), AppLogic.AppConfig("StoreName"));
                    string emailBody    = string.Format(AppLogic.GetString("notification.downloaddelayed.2", customer.SkinID, customer.LocaleSetting), this.DownloadName, this.OrderNumber, this.CustomerId);

                    NotifyAdminDelayedDownload(customer, emailSubject, emailBody);
                    return;
                }
            }

            if (AppLogic.AppConfigBool("Download.CopyFileForEachOrder") && !this.DownloadLocation.Contains("http:") && !this.DownloadLocation.Contains("https:"))
            {
                try
                {
                    var downloadPath           = CommonLogic.SafeMapPath(this.DownloadLocation);
                    var filename               = Path.GetFileName(downloadPath);
                    var orderDownloadLocation  = string.Format("~/orderdownloads/{0}_{1}", this.OrderNumber, this.CustomerId);
                    var orderDownloadDirectory = CommonLogic.SafeMapPath(orderDownloadLocation);

                    if (!Directory.Exists(orderDownloadDirectory))
                    {
                        Directory.CreateDirectory(orderDownloadDirectory);
                    }

                    var orderDownloadPath = string.Format("{0}/{1}", orderDownloadDirectory, filename);

                    File.Copy(downloadPath, orderDownloadPath, true);

                    finalDownloadLocation = string.Format("{0}/{1}", orderDownloadLocation, filename);
                }
                catch (Exception ex)
                {
                    SysLog.LogException(ex, MessageTypeEnum.GeneralException, MessageSeverityEnum.Error);
                    return;
                }
            }
            using (var cn = new SqlConnection(DB.GetDBConn()))
            {
                cn.Open();
                using (var cmd = new SqlCommand(@"update orders_ShoppingCart set                                
									DownloadReleasedOn=@DownloadReleasedOn,
									DownloadStatus=@DownloadStatus,
									DownloadLocation=@DownloadLocation
									where ShoppingCartRecID=@ShoppingCartRecID"                                    , cn))
                {
                    cmd.Parameters.Add(new SqlParameter("@DownloadReleasedOn", SqlDbType.DateTime));
                    cmd.Parameters.Add(new SqlParameter("@DownloadStatus", SqlDbType.Int));
                    cmd.Parameters.Add(new SqlParameter("@DownloadLocation", SqlDbType.NText));
                    cmd.Parameters.Add(new SqlParameter("@ShoppingCartRecID", SqlDbType.Int));

                    cmd.Parameters["@DownloadReleasedOn"].Value = DateTime.Now;
                    cmd.Parameters["@DownloadStatus"].Value     = (int)DownloadItemStatus.Available;
                    cmd.Parameters["@DownloadLocation"].Value   = finalDownloadLocation;
                    cmd.Parameters["@ShoppingCartRecID"].Value  = this.ShoppingCartRecordId;

                    cmd.ExecuteNonQuery();
                }
            }
        }
コード例 #17
0
ファイル: Feed.cs プロジェクト: lulzzz/BrandStore
        public string ExecuteFeed(Customer ThisCustomer, String RuntimeParams)
        {
            string folderpath = CommonLogic.IIF(AppLogic.IsAdminSite, CommonLogic.SafeMapPath("../images/"), CommonLogic.SafeMapPath("images"));
            string retval     = string.Empty;

            try
            {
                string filename = String.Empty;
                if (FTPFilename.Length == 0)
                {
                    FTPFilename = XmlPackage + ".txt";
                }
                //Strip all of the remote pathing stuff before setting the local filename
                if (FTPFilename.IndexOf("/") != -1)
                {
                    filename = FTPFilename.Substring(FTPFilename.LastIndexOf("/")).Trim('/');
                }
                else
                {
                    filename = FTPFilename;
                }
                filename = Path.Combine(folderpath, filename);

                String[] Files;
                Files = Directory.GetFileSystemEntries(folderpath);
                foreach (string Element in Files)
                {
                    try
                    {
                        if (Element.Substring(Element.LastIndexOf("\\")).Trim('\\').Substring(0, FTPFilename.Substring(0, FTPFilename.LastIndexOf(".")).Length) == FTPFilename.Substring(0, FTPFilename.LastIndexOf(".")))
                        {
                            File.Delete(Element);
                        }
                    }
                    catch { }
                }

                string HideProductsWithLessThanThisInventoryLevel = AppLogic.AppConfig("HideProductsWithLessThanThisInventoryLevel");
                if (HideProductsWithLessThanThisInventoryLevel == null || HideProductsWithLessThanThisInventoryLevel == "")
                {
                    HideProductsWithLessThanThisInventoryLevel = "0";
                }

                // SELECT query for getting the total number of rows
                StringBuilder SqlQuery = new StringBuilder(10000);
                SqlQuery.Append("SELECT COUNT(*) FROM (select p.productid, p.name, isnull(pv.name, '') VariantName, p.description, p.sename, p.ImageFileNameOverride, p.SKU, isnull(p.FroogleDescription, '') ProductFroogleDescription, p.SEKeywords, ");
                SqlQuery.Append("p.ManufacturerPartNumber, pv.price, isnull(pv.saleprice, 0) saleprice, isnull(pv.FroogleDescription, '') VariantFroogleDescription, isnull(pv.description, '') VariantDescr from dbo.product p ");
                SqlQuery.Append("join dbo.productvariant pv on p.productid = pv.productid left join (select variantid, sum(quan) inventory from dbo.inventory group by variantid) i on pv.variantid = i.variantid where p.IsSystem=0 and p.deleted = 0 ");
                SqlQuery.Append("and p.published = 1 and p.ExcludeFromPriceFeeds = 0 and pv.isdefault = 1 and case p.TrackInventoryBySizeAndColor when 1 then isnull(i.inventory, 0) else pv.inventory end >= " + HideProductsWithLessThanThisInventoryLevel + ") AS tmp");

                // Code for query execution
                string        err;
                object        objReturn;
                Int32         RowCount;
                SqlConnection cn  = new SqlConnection(DB.GetDBConn());
                SqlCommand    cmd = new SqlCommand();
                cn.Open();
                cmd.Connection  = cn;
                cmd.CommandText = SqlQuery.ToString();
                cmd.CommandType = CommandType.Text;
                try
                {
                    // Get the result of the query
                    objReturn = cmd.ExecuteScalar();

                    // Check if result is null
                    if (objReturn != null)
                    {
                        RowCount = (Int32)objReturn;

                        string newFileNames = string.Empty;

                        // The lower and upper bounds of the records to be retrieved
                        Int32 LowerBound = 1;
                        Int32 UpperBound = (LowerBound - 1) + 20000;

                        // Looping for processing of records by 20000
                        while (RowCount > 0)
                        {
                            if (RowCount < 20000)
                            {
                                UpperBound = (LowerBound - 1) + RowCount;
                                RowCount   = 0;
                            }
                            else
                            {
                                RowCount -= 20000;
                            }

                            // Add parameters to feed.googlebase.xml.config
                            RuntimeParams += String.Format("LowerBound={0}", LowerBound);
                            RuntimeParams += String.Format("&UpperBound={0}", UpperBound);

                            // Same as the old code
                            string feeddocument = AppLogic.RunXmlPackage(m_Xmlpackage, null, ThisCustomer, 1, "", RuntimeParams, false, false);
                            feeddocument = feeddocument.Replace("encoding=\"utf-16\"", "");

                            // Construction of the new filename. New filename will be old filename concatenated to the record numbers being processed, e.g. googlefeed1_20000
                            string filenamePrefix = LowerBound.ToString() + "_" + UpperBound.ToString();

                            string newFileName;
                            if (filename.LastIndexOf(".") < 1)
                            {
                                newFileName = filename + filenamePrefix;
                            }
                            else
                            {
                                newFileName = filename.Insert(filename.LastIndexOf("."), filenamePrefix);
                            }

                            if (newFileNames == string.Empty)
                            {
                                newFileNames = newFileName;
                            }
                            else
                            {
                                newFileNames = string.Concat(newFileNames, ",", newFileName);
                            }


                            using (StreamWriter sw = new StreamWriter(newFileName, false))
                            {
                                sw.Write(feeddocument);
                                sw.Close();
                            }
                            if (this.CanAutoFTP)
                            {
                                FtpClient ftp = new FtpClient(this.FTPServer + ":" + this.FTPPort.ToString(), this.FTPUsername, this.FTPPassword);
                                //retval = ftp.Upload(filename, this.FTPFilename);
                                retval = ftp.Upload(newFileName.Trim(), this.FTPFilename);
                            }
                            else
                            {
                                //retval = "The file " + this.FTPFilename + " has been created in the /images folder of your website";
                                retval = "The file(s) " + newFileNames.Trim() + " has been created in the /images folder of your website";
                            }

                            LowerBound += 20000;
                            UpperBound += 20000;

                            filenamePrefix = "";
                            feeddocument   = "";
                            RuntimeParams  = "";
                        }
                    }
                }
                catch (Exception ex)
                {
                    err = ex.Message;
                    return(err);
                }

                cn.Close();
                cmd.Dispose();
                cn.Dispose();

                return(retval);
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
コード例 #18
0
        // Find the specified topic content. note, we try to find content even if it doesn't exactly match the input specs, by doing an ordered lookup in various areas
        // we want to show SOME topic content if it is at all possible, even if the language is not right, etc...
        // Note: site id only used for file based topic _contents
        // Search Order is (yes, other orderings are possible, but this is the one we chose, where ANY db topic match overrides file content):
        // the other option would be to match on locales in the order of DB/File (Customer Locale), DB/File (Store Locale), DB/File (Null locale)
        // DB (customer locale)
        // DB (store locale)
        // DB (null locale)
        // File (customer locale)
        // File (store locale)
        // File (null locale)
        void LoadFromDB(int StoreID)
        {
            m_FromDB             = false;
            m_DisplayOrder       = 1;
            m_SkinID             = ThisCustomer.SkinID;
            m_StoreID            = StoreID;
            m_LocaleSetting      = CommonLogic.IIF(m_LocaleSetting.Length > 0, m_LocaleSetting, Localization.GetDefaultLocale());
            m_Contents           = String.Empty;
            m_ContentsRAW        = String.Empty;
            m_SectionTitle       = String.Empty;
            m_RequiresDisclaimer = false;
            m_ShowInSiteMap      = true;
            m_Password           = String.Empty;
            m_SETitle            = m_TopicName;
            m_SEKeywords         = String.Empty;
            m_SEDescription      = String.Empty;
            m_FN           = String.Empty;
            m_MasterLocale = m_LocaleSetting;
            m_HasChildren  = false;

            if (m_TopicID == 0)
            {
                m_TopicID = Topic.GetTopicID(m_TopicName, CommonLogic.IIF(AppLogic.IsAdminSite, m_MasterLocale, m_LocaleSetting), AppLogic.StoreID());
            }

            if (m_TopicID != 0)
            {
                var sql = string.Format("SELECT * from Topic with (NOLOCK) where Deleted=0 and Published=1 and TopicID={0} and (SkinID IS NULL or SkinID=0 or SkinID={1}) order by DisplayOrder, Name ASC", m_TopicID.ToString(), m_SkinID.ToString());

                using (var con = new SqlConnection(DB.GetDBConn()))
                {
                    con.Open();
                    using (var rs = DB.GetRS(sql, con))
                    {
                        if (rs.Read())
                        {
                            m_FromDB             = true;
                            m_TopicID            = DB.RSFieldInt(rs, "TopicID");
                            m_TopicName          = DB.RSField(rs, "Name");
                            m_Contents           = DB.RSFieldByLocale(rs, "Description", m_LocaleSetting);
                            m_Password           = DB.RSField(rs, "Password");
                            m_RequiresDisclaimer = DB.RSFieldBool(rs, "RequiresDisclaimer");
                            m_DisplayOrder       = DB.RSFieldInt(rs, "DisplayOrder");
                            m_ShowInSiteMap      = DB.RSFieldBool(rs, "ShowInSiteMap");
                            m_SkinID             = DB.RSFieldInt(rs, "SkinID");
                            if (m_Contents.Length != 0)
                            {
                                m_ContentsRAW   = m_Contents;
                                m_SectionTitle  = DB.RSFieldByLocale(rs, "Title", m_LocaleSetting);
                                m_SETitle       = DB.RSFieldByLocale(rs, "SETitle", m_LocaleSetting);
                                m_SEKeywords    = DB.RSFieldByLocale(rs, "SEKeywords", m_LocaleSetting);
                                m_SEDescription = DB.RSFieldByLocale(rs, "SEDescription", m_LocaleSetting);
                            }
                            else                             // nothing found, try master locale:
                            {
                                m_Contents      = DB.RSFieldByLocale(rs, "Description", m_MasterLocale);
                                m_ContentsRAW   = m_Contents;
                                m_SectionTitle  = DB.RSFieldByLocale(rs, "Title", m_MasterLocale);
                                m_SETitle       = DB.RSFieldByLocale(rs, "SETitle", m_MasterLocale);
                                m_SEKeywords    = DB.RSFieldByLocale(rs, "SEKeywords", m_MasterLocale);
                                m_SEDescription = DB.RSFieldByLocale(rs, "SEDescription", m_MasterLocale);
                            }

                            // if an html tag is present, extract just the body of the content
                            if (m_Contents.IndexOf("<html", StringComparison.InvariantCultureIgnoreCase) != -1)
                            {
                                m_Contents = CommonLogic.ExtractBody(m_ContentsRAW);
                            }
                        }
                    }
                }
            }

            if (!m_FromDB)            // did not find anything in db, try file based topic content (in skins folder as topicname.htm)
            {
                string appdir = HttpContext.Current.Request.PhysicalApplicationPath;

                List <string> possibleFileNames = new List <string> {
                    Path.Combine(appdir, string.Format("Skins\\{0}\\Topics\\{1}.{2}.htm", SkinProvider.GetSkinNameById(SkinID), m_TopicName, m_LocaleSetting)),  //Skin specific, localized
                    Path.Combine(appdir, String.Format("Skins\\{0}\\Topics\\{1}.htm", SkinProvider.GetSkinNameById(SkinID), m_TopicName)),                       //Skin specific, unlocalized
                    Path.Combine(appdir, string.Format("Topics\\{0}.{1}.htm", m_TopicName, m_LocaleSetting)),                                                    //Root folder, localized
                    Path.Combine(appdir, string.Format("Topics\\{0}.htm", m_TopicName)),                                                                         //Root folder, unlocalized
                    Path.Combine(appdir, string.Format("Skins\\{0}\\Topics\\{1}.{2}.html", SkinProvider.GetSkinNameById(SkinID), m_TopicName, m_LocaleSetting)), //Skin specific, localized HTML
                    Path.Combine(appdir, String.Format("Skins\\{0}\\Topics\\{1}.html", SkinProvider.GetSkinNameById(SkinID), m_TopicName)),                      //Skin specific, unlocalized HTML
                    Path.Combine(appdir, string.Format("Topics\\{0}.{1}.html", m_TopicName, m_LocaleSetting)),                                                   //Root folder, localized HTML
                    Path.Combine(appdir, string.Format("Topics\\{0}.html", m_TopicName))                                                                         //Root folder, unlocalized HTML
                };

                foreach (string fileNametoCheck in possibleFileNames)
                {
                    m_FN = CommonLogic.SafeMapPath(fileNametoCheck);

                    if (CommonLogic.FileExists(m_FN))
                    {
                        break;
                    }
                }

                if (m_FN.Length != 0 && CommonLogic.FileExists(m_FN))
                {
                    m_Contents     = CommonLogic.ReadFile(m_FN, true);
                    m_ContentsRAW  = m_Contents;
                    m_SectionTitle = CommonLogic.ExtractToken(m_ContentsRAW, "<title>", "</title>");
                    m_Contents     = CommonLogic.ExtractBody(m_Contents);

                    // Throw a helpful error if the topic file is not formatted properly
                    if (m_Contents.Length == 0 && m_ContentsRAW.Length > 0)
                    {
                        throw new Exception(@"Make sure to format your topic file like a normal html document.
							For Example:
							<!DOCTYPE html>
							<html>
								<head>
									<title>Your title</title>
								</head>
								<body>
									Your content here
								</body>
							</html>"                            );
                    }

                    // try old token formats first, for backwards compatibility:
                    m_SETitle       = CommonLogic.ExtractToken(m_ContentsRAW, "<PAGETITLE>", "</PAGETITLE>");
                    m_SEKeywords    = CommonLogic.ExtractToken(m_ContentsRAW, "<PAGEKEYWORDS>", "</PAGEKEYWORDS>");
                    m_SEDescription = CommonLogic.ExtractToken(m_ContentsRAW, "<PAGEDESCRIPTION>", "</PAGEDESCRIPTION>");

                    // if regular HTML tokens found, try to parse it out in regular HTML syntax meta tag format and they take precedence over the old tokens (above):
                    String t = Regex.Match(m_ContentsRAW, @"(?<=<title[^\>]*>).*?(?=</title>)", RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture).Value;
                    if (t.Length != 0)
                    {
                        m_SETitle = t;
                    }

                    String MK = String.Empty;
                    String MV = String.Empty;
                    foreach (Match metamatch in Regex.Matches(m_ContentsRAW, @"<meta\s*(?:(?:\b(\w|-)+\b\s*(?:=\s*(?:""[^""]*""|'[^']*'|[^""'<> ]+)\s*)?)*)/?\s*>", RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture))
                    {
                        MK = String.Empty;
                        MV = String.Empty;
                        // Loop through the attribute/value pairs inside the tag
                        foreach (Match submatch in Regex.Matches(metamatch.Value.ToString(), @"(?<name>\b(\w|-)+\b)\s*=\s*(""(?<value>[^""]*)""|'(?<value>[^']*)'|(?<value>[^""'<> ]+)\s*)+", RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture))
                        {
                            if ("http-equiv".Equals(submatch.Groups[1].ToString(), StringComparison.InvariantCultureIgnoreCase))
                            {
                                MV = submatch.Groups[2].ToString();
                            }
                            if (("name".Equals(submatch.Groups[1].ToString(), StringComparison.InvariantCultureIgnoreCase)) &&
                                MK == String.Empty)                                 // if it's already set, HTTP-EQUIV takes precedence
                            {
                                MV = submatch.Groups[2].ToString();
                            }
                            if ("content".Equals(submatch.Groups[1].ToString(), StringComparison.InvariantCultureIgnoreCase))
                            {
                                MV = submatch.Groups[2].ToString();
                            }
                        }
                        switch (MK.ToLowerInvariant())
                        {
                        case "description":
                            m_SEDescription = MV;
                            break;

                        case "keywords":
                        case "keyword":
                            m_SEKeywords = MV;
                            break;
                        }
                    }
                }
            }

            if (m_SETitle.Length == 0)
            {
                m_SETitle = m_SectionTitle;
            }

            if (AppLogic.ReplaceImageURLFromAssetMgr)
            {
                while (m_Contents.IndexOf("../images") != -1)
                {
                    m_Contents = m_Contents.Replace("../images", "images");
                }
            }
            if (m_UseParser != null)
            {
                m_Contents = m_UseParser.ReplaceTokens(m_Contents);
            }
            else
            {
                if (SkinID > 0)
                {
                    m_Contents = m_Contents.Replace("(!SKINID!)", SkinID.ToString());
                }
            }
        }
コード例 #19
0
        public SiteMapComponentArt(Dictionary <string, EntityHelper> EntityHelpers, int SkinID, Customer ThisCustomer, bool showCustomerService)
        {
            bool   FromCache = false;
            String CacheName = String.Format("SiteMapComponentArt_{0}_{1}", SkinID.ToString(), ThisCustomer.LocaleSetting);

            if (AppLogic.CachingOn)
            {
                m_Contents = (String)HttpContext.Current.Cache.Get(CacheName);
                if (m_Contents != null)
                {
                    FromCache = true;
                }
            }

            if (!FromCache)
            {
                StringBuilder tmpS = new StringBuilder(50000);
                tmpS.Append("<SiteMap>\n");

                if (AppLogic.IsAdminSite || AppLogic.AppConfigBool("SiteMap.ShowCategories"))
                {
                    // Categories:
                    String s = AppLogic.LookupHelper("Category", 0).GetEntityComponentArtNode(0, ThisCustomer.LocaleSetting, ThisCustomer.AffiliateID, ThisCustomer.CustomerLevelID, true, AppLogic.IsAdminSite || AppLogic.AppConfigBool("SiteMap.ShowProducts") && AppLogic.NumProductsInDB < 250);
                    if (s.Length != 0)
                    {
                        if (AppLogic.IsAdminSite)
                        {
                            tmpS.Append("<node Text=\"" + XmlCommon.XmlEncodeAttribute(AppLogic.GetString("AppConfig.CategoryPromptPlural", SkinID, ThisCustomer.LocaleSetting).ToUpperInvariant()) + "\" NavigateUrl=\"newentities.aspx?entityname=category\">\n");
                        }
                        else
                        {
                            tmpS.Append("<node Text=\"" + XmlCommon.XmlEncodeAttribute(AppLogic.GetString("AppConfig.CategoryPromptPlural", SkinID, ThisCustomer.LocaleSetting).ToUpperInvariant()) + "\">\n");
                        }
                        tmpS.Append(s);
                        tmpS.Append("</node>");
                    }
                }

                if (AppLogic.IsAdminSite || AppLogic.AppConfigBool("SiteMap.ShowSections"))
                {
                    // Sections:
                    String s = AppLogic.LookupHelper("Section", 0).GetEntityComponentArtNode(0, ThisCustomer.LocaleSetting, ThisCustomer.AffiliateID, ThisCustomer.CustomerLevelID, true, AppLogic.IsAdminSite || AppLogic.AppConfigBool("SiteMap.ShowProducts") && AppLogic.NumProductsInDB < 250);
                    if (s.Length != 0)
                    {
                        if (AppLogic.IsAdminSite)
                        {
                            tmpS.Append("<node Text=\"" + XmlCommon.XmlEncodeAttribute(AppLogic.GetString("AppConfig.SectionPromptPlural", SkinID, ThisCustomer.LocaleSetting).ToUpperInvariant()) + "\" NavigateUrl=\"newentities.aspx?entityname=section\">\n");
                        }
                        else
                        {
                            tmpS.Append("<node Text=\"" + XmlCommon.XmlEncodeAttribute(AppLogic.GetString("AppConfig.SectionPromptPlural", SkinID, ThisCustomer.LocaleSetting).ToUpperInvariant()) + "\">\n");
                        }
                        tmpS.Append(s);
                        tmpS.Append("</node>");
                    }
                }

                if (AppLogic.IsAdminSite || AppLogic.AppConfigBool("SiteMap.ShowLibraries"))
                {
                    // Libraries:
                    String s = AppLogic.LookupHelper("Library", 0).GetEntityComponentArtNode(0, ThisCustomer.LocaleSetting, ThisCustomer.AffiliateID, ThisCustomer.CustomerLevelID, true, AppLogic.IsAdminSite || AppLogic.AppConfigBool("SiteMap.ShowDocuments") && AppLogic.NumProductsInDB < 250);
                    if (s.Length != 0)
                    {
                        if (AppLogic.IsAdminSite)
                        {
                            tmpS.Append("<node Text=\"" + XmlCommon.XmlEncodeAttribute(AppLogic.GetString("AppConfig.LibraryPromptPlural", SkinID, ThisCustomer.LocaleSetting).ToUpperInvariant()) + "\" NavigateUrl=\"newentities.aspx?entityname=library\">\n");
                        }
                        else
                        {
                            tmpS.Append("<node Text=\"" + XmlCommon.XmlEncodeAttribute(AppLogic.GetString("AppConfig.LibraryPromptPlural", SkinID, ThisCustomer.LocaleSetting).ToUpperInvariant()) + "\">\n");
                        }
                        tmpS.Append(s);
                        tmpS.Append("</node>");
                    }
                }

                if (AppLogic.IsAdminSite || AppLogic.AppConfigBool("SiteMap.ShowManufacturers"))
                {
                    // Manufacturers:
                    String s = AppLogic.LookupHelper("Manufacturer", 0).GetEntityComponentArtNode(0, ThisCustomer.LocaleSetting, ThisCustomer.AffiliateID, ThisCustomer.CustomerLevelID, true, AppLogic.IsAdminSite || AppLogic.AppConfigBool("SiteMap.ShowProducts") && AppLogic.NumProductsInDB < 250);
                    if (s.Length != 0)
                    {
                        if (AppLogic.IsAdminSite)
                        {
                            tmpS.Append("<node Text=\"" + XmlCommon.XmlEncodeAttribute(AppLogic.GetString("AppConfig.ManufacturerPromptPlural", SkinID, ThisCustomer.LocaleSetting).ToUpperInvariant()) + "\" NavigateUrl=\"newentities.aspx?entityname=manufacturer\">\n");
                        }
                        else
                        {
                            tmpS.Append("<node Text=\"" + XmlCommon.XmlEncodeAttribute(AppLogic.GetString("AppConfig.ManufacturerPromptPlural", SkinID, ThisCustomer.LocaleSetting).ToUpperInvariant()) + "\">\n");
                        }
                        tmpS.Append(s);
                        tmpS.Append("</node>");
                    }
                }

                if (!AppLogic.IsAdminSite && AppLogic.AppConfigBool("SiteMap.ShowCustomerService") && showCustomerService)
                {
                    tmpS.Append("<node Text=\"" + XmlCommon.XmlEncodeAttribute(AppLogic.GetString("menu.CustomerService", ThisCustomer.SkinID, ThisCustomer.LocaleSetting)) + "\">\n");
                    tmpS.Append("	<node Text=\""+ XmlCommon.XmlEncodeAttribute(AppLogic.GetString("menu.YourAccount", SkinID, ThisCustomer.LocaleSetting)) + "\" NavigateUrl=\"account.aspx\" />\n");
                    tmpS.Append("	<node Text=\""+ XmlCommon.XmlEncodeAttribute(AppLogic.GetString("menu.OrderHistory", SkinID, ThisCustomer.LocaleSetting)) + "\" NavigateUrl=\"account.aspx\" />\n");

                    tmpS.Append("	<node Text=\""+ XmlCommon.XmlEncodeAttribute(AppLogic.GetString("menu.PolicyReturns", SkinID, ThisCustomer.LocaleSetting)) + "\" NavigateUrl=\"" + SE.MakeDriverLink("returns") + "\" />\n");
                    tmpS.Append("	<node Text=\""+ XmlCommon.XmlEncodeAttribute(AppLogic.GetString("menu.Shipping", SkinID, ThisCustomer.LocaleSetting)) + "\" NavigateUrl=\"" + SE.MakeDriverLink("shipping") + "\" />\n");
                    tmpS.Append("	<node Text=\""+ XmlCommon.XmlEncodeAttribute(AppLogic.GetString("menu.Contact", SkinID, ThisCustomer.LocaleSetting)) + "\" NavigateUrl=\"contactus.aspx\" />\n");
                    tmpS.Append("	<node Text=\""+ XmlCommon.XmlEncodeAttribute(AppLogic.GetString("menu.PolicyPrivacy", SkinID, ThisCustomer.LocaleSetting)) + "\" NavigateUrl=\"" + SE.MakeDriverLink("privacy") + "\" />\n");
                    tmpS.Append("	<node Text=\""+ XmlCommon.XmlEncodeAttribute(AppLogic.GetString("menu.PolicySecurity", SkinID, ThisCustomer.LocaleSetting)) + "\" NavigateUrl=\"" + SE.MakeDriverLink("security") + "\" />\n");
                    tmpS.Append("</node>\n");
                }

                if (AppLogic.IsAdminSite || AppLogic.AppConfigBool("SiteMap.ShowTopics"))
                {
                    // Topics:
                    if (AppLogic.IsAdminSite)
                    {
                        tmpS.Append("<node Text=\"" + XmlCommon.XmlEncodeAttribute(AppLogic.GetString("sitemap.aspx.2", SkinID, ThisCustomer.LocaleSetting).ToUpperInvariant()) + "\" NavigateUrl=\"topics.aspx\">\n");
                    }
                    else
                    {
                        tmpS.Append("<node Text=\"" + XmlCommon.XmlEncodeAttribute(AppLogic.GetString("sitemap.aspx.2", SkinID, ThisCustomer.LocaleSetting).ToUpperInvariant()) + "\" NavigateUrl=\"\">\n");
                    }

                    using (SqlConnection con = new SqlConnection(DB.GetDBConn()))
                    {
                        con.Open();
                        using (IDataReader rs = DB.GetRS(string.Format("select Name,Title,TopicID,ShowInSiteMap from Topic with (NOLOCK) where {0} Deleted=0 and Published=1 and (SkinID IS NULL or SkinID=0 or SkinID={1}) Order By DisplayOrder, Name ASC", CommonLogic.IIF(AppLogic.IsAdminSite, "", "ShowInSiteMap=1 and "), SkinID.ToString()), con))
                        {
                            string displayname = string.Empty;
                            string name        = string.Empty;
                            while (rs.Read())
                            {
                                String URL = String.Empty;
                                name = DB.RSFieldByLocale(rs, "Name", ThisCustomer.LocaleSetting);
                                if (AppLogic.IsAdminSite)
                                {
                                    URL = String.Format("topics.aspx?EditTopicId={0}", DB.RSFieldInt(rs, "TopicID").ToString());
                                }
                                else
                                {
                                    URL = SE.MakeDriverLink(name);
                                }
                                displayname = XmlCommon.XmlEncodeAttribute(DB.RSFieldByLocale(rs, "Title", ThisCustomer.LocaleSetting));
                                if (displayname != string.Empty)
                                {
                                    if (name.IndexOf("GOOGLE", StringComparison.InvariantCultureIgnoreCase) == -1 && name.IndexOf("PHONE", StringComparison.InvariantCultureIgnoreCase) == -1 &&
                                        name.IndexOf("AFFILIATE", StringComparison.InvariantCultureIgnoreCase) == -1 && name.IndexOf("GIFTREGISTRY", StringComparison.InvariantCultureIgnoreCase) == -1 &&
                                        name.IndexOf("WISHLIST", StringComparison.InvariantCultureIgnoreCase) == -1 && name.IndexOf("CHECKOUTANON", StringComparison.InvariantCultureIgnoreCase) == -1 &&
                                        name.IndexOf("DOWNLOAD", StringComparison.InvariantCultureIgnoreCase) == -1 && name.IndexOf("GENRE", StringComparison.InvariantCultureIgnoreCase) == -1 &&
                                        name.IndexOf("DISTRIBUTOR", StringComparison.InvariantCultureIgnoreCase) == -1 && name.IndexOf("VECTOR", StringComparison.InvariantCultureIgnoreCase) == -1 &&
                                        name.IndexOf("CARTPAGEFOOTER", StringComparison.InvariantCultureIgnoreCase) == -1 && name.IndexOf("CODINSTRUCTIONS", StringComparison.InvariantCultureIgnoreCase) == -1)
                                    {
                                        tmpS.Append("<node Text=\"" + displayname + "\" NavigateUrl=\"" + XmlCommon.XmlEncodeAttribute(URL) + "\" />\n");
                                    }
                                }
                            }
                        }
                    }

                    // File Topics:
                    // create an array to hold the list of files
                    ArrayList fArray = new ArrayList();

                    // get information about our initial directory
                    String SFP = CommonLogic.SafeMapPath(CommonLogic.IIF(AppLogic.IsAdminSite, "../", "") + "App_Templates/Skin_" + SkinID.ToString() + "/template.htm").Replace("template.htm", "");

                    DirectoryInfo dirInfo = new DirectoryInfo(SFP);

                    // retrieve array of files & subdirectories
                    FileSystemInfo[] myDir = dirInfo.GetFileSystemInfos();

                    for (int i = 0; i < myDir.Length; i++)
                    {
                        // check the file attributes

                        // if a subdirectory, add it to the sArray
                        // otherwise, add it to the fArray
                        if (((Convert.ToUInt32(myDir[i].Attributes) & Convert.ToUInt32(FileAttributes.Directory)) > 0))
                        {
                        }
                        else
                        {
                            bool skipit = false;
                            if (!myDir[i].FullName.EndsWith("htm", StringComparison.InvariantCultureIgnoreCase) ||
                                (myDir[i].FullName.IndexOf("TEMPLATE", StringComparison.InvariantCultureIgnoreCase) != -1) ||
                                (myDir[i].FullName.IndexOf("AFFILIATE_", StringComparison.InvariantCultureIgnoreCase) != -1) ||
                                (myDir[i].FullName.IndexOf(AppLogic.ro_PMMicropay, StringComparison.InvariantCultureIgnoreCase) != -1))
                            {
                                skipit = true;
                            }
                            if (!skipit)
                            {
                                fArray.Add(Path.GetFileName(myDir[i].FullName));
                            }
                        }
                    }

                    if (fArray.Count != 0)
                    {
                        // sort the files alphabetically
                        fArray.Sort(0, fArray.Count, null);
                        for (int i = 0; i < fArray.Count; i++)
                        {
                            String URL = String.Empty;
                            if (!AppLogic.IsAdminSite) // admin site can't link to these kinds of topics
                            {
                                URL = SE.MakeDriverLink(fArray[i].ToString().Replace(".htm", ""));
                            }
                            tmpS.Append("<node Text=\"" + XmlCommon.XmlEncodeAttribute(CommonLogic.Capitalize(fArray[i].ToString().Replace(".htm", ""))) + "\" " + CommonLogic.IIF(URL.Length != 0, "NavigateUrl=\"" + XmlCommon.XmlEncodeAttribute(URL) + "\"", "") + "/>\n");
                        }
                    }
                    tmpS.Append("</node>");
                }

                tmpS.Append("</SiteMap>\n");
                m_Contents = tmpS.ToString();
                if (AppLogic.CachingOn)
                {
                    HttpContext.Current.Cache.Insert(CacheName, m_Contents, null, System.DateTime.Now.AddMinutes(AppLogic.CacheDurationMinutes()), TimeSpan.Zero);
                }
            }
        }
コード例 #20
0
        public ArrayList GetEntityArrayList(int ForParentEntityID, String Prefix, int FilterEntityID, String LocaleSetting, bool AllowCaching)
        {
            ArrayList al;
            String    CacheName = String.Format("GetEntityArrayList_{0}_{1}_{2}_{3}_{4}_{5}", m_EntitySpecs.m_EntityName, ForParentEntityID.ToString(), Prefix, FilterEntityID.ToString(), LocaleSetting, AppLogic.IsAdminSite.ToString());

            if (AppLogic.CachingOn && AllowCaching)
            {
                al = (ArrayList)HttpContext.Current.Cache.Get(CacheName);
                if (al != null)
                {
                    if (CommonLogic.ApplicationBool("DumpSQL"))
                    {
                        HttpContext.Current.Response.Write("Cache Hit Found!\n");
                    }
                    return(al);
                }
            }

            al = new ArrayList();

            StringWriter         tmpS    = new StringWriter();
            String               XslFile = "EntityArrayListXML";
            XslCompiledTransform xForm;
            string               XslFilePath = CommonLogic.SafeMapPath(string.Format("{0}/EntityHelper/{1}.xslt", AppLogic.AdminDir(), XslFile));

            xForm = (XslCompiledTransform)HttpContext.Current.Cache.Get(XslFilePath);
            if (xForm == null)
            {
                xForm = new XslCompiledTransform(false);
                xForm.Load(XslFilePath);
                HttpContext.Current.Cache.Insert(XslFilePath, xForm, new CacheDependency(XslFilePath));
            }
            XsltArgumentList xslArgs = new XsltArgumentList();

            xslArgs.AddParam("ForParentEntityID", "", ForParentEntityID);
            xslArgs.AddParam("filterID", "", FilterEntityID);
            xslArgs.AddParam("custlocale", "", LocaleSetting);
            xslArgs.AddParam("deflocale", "", Localization.GetDefaultLocale());
            xslArgs.AddParam("adminsite", "", AppLogic.IsAdminSite);
            xForm.Transform(m_TblMgr.XmlDoc, xslArgs, tmpS);

            XmlDocument returnedXML = new XmlDocument();

            returnedXML.LoadXml(tmpS.ToString());

            XmlNodeList entityNodes = returnedXML.SelectNodes("/Entities/Entity");

            foreach (XmlNode n in entityNodes)
            {
                try
                {
                    XmlNode idNode   = n.SelectNodes("EntityId")[0];
                    XmlNode nameNode = n.SelectNodes("EntityName")[0];
                    int     entityId;
                    if (int.TryParse(idNode.InnerText, out entityId) && !string.IsNullOrEmpty(nameNode.InnerText))
                    {
                        ListItemClass li = new ListItemClass();
                        li.Value = entityId;
                        li.Item  = Security.HtmlEncode(nameNode.InnerText);
                        al.Add(li);
                    }
                }
                catch (Exception)
                {
                }
            }

            if (AppLogic.AppConfigBool("XmlPackage.DumpTransform"))
            {
                try                 // don't let logging crash the site
                {
                    StreamWriter sw = File.CreateText(CommonLogic.SafeMapPath(String.Format("{0}images/{1}_{2}_{3}.xfrm.xml", CommonLogic.IIF(AppLogic.IsAdminSite, "~/", ""), XslFile, m_EntitySpecs.m_EntityName, CommonLogic.IIF(AppLogic.IsAdminSite, "admin", "store"))));
                    sw.WriteLine(XmlCommon.PrettyPrintXml(tmpS.ToString()));
                    sw.Close();
                }
                catch { }
            }

            if (AppLogic.CachingOn && AllowCaching)
            {
                HttpContext.Current.Cache.Insert(CacheName, al, null, System.DateTime.Now.AddMinutes(AppLogic.CacheDurationMinutes()), TimeSpan.Zero);
            }
            return(al);
        }