public override List <Bundle> ParseConfigs() { if (!Directory.Exists(ProjectPath)) { throw new DirectoryNotFoundException("Could not find project directory."); } FindConfigs(); var loader = new ConfigLoader( FilePaths, new ExceptionThrowingLogger(), new ConfigLoaderOptions { ProcessBundles = true }); Configuration = loader.Get(); var bundles = new List <Bundle>(); foreach (var bundleDefinition in Configuration.Bundles.BundleEntries.Where(r => !r.IsVirtual)) { var bundle = new Bundle(); bundle.Output = GetOutputPath(bundleDefinition.OutputPath, bundleDefinition.Name); bundle.Files = bundleDefinition.BundleItems .Select(r => new FileSpec(this.ResolvePhysicalPath(r.RelativePath), r.CompressionType)) .ToList(); bundles.Add(bundle); } return(bundles); }
public override List <Bundle> ParseConfigs() { if (!Directory.Exists(ProjectPath)) { throw new DirectoryNotFoundException($"Could not find project directory '{ProjectPath}'."); } FindConfigs(); var loader = new ConfigLoader( FilePaths, new ExceptionThrowingLogger(), new ConfigLoaderOptions { ProcessBundles = true }); Configuration = loader.Get(); var bundles = Configuration.AutoBundles.Bundles .Select(autoBundle => createBundleOf(autoBundle)) .ToList(); this.WriteOverrideConfigs(bundles); return(bundles); }
public SitemapController(ICatalogApi catalogApi, ICategoryViewModelBuilder catViewModelBuilder, ILinkGenerator linkGenerator) { _catalogApi = catalogApi; _linkGenerator = linkGenerator; _catViewModelBuilder = catViewModelBuilder; _siteConfig = ConfigLoader.Get <SiteConfig>(); }
public Crypto() { var thumbprint = ConfigLoader.Get <CryptographicServiceThumbprintConfig>().ThumbPrint; _enabled = !string.IsNullOrWhiteSpace(thumbprint); if (!_enabled) { return; } var cert = GetCertificate(thumbprint); var config = ConfigLoader.Get <CryptographicServiceConfig>(); var dict = new Dictionary <string, string>(StringComparer.InvariantCultureIgnoreCase) { { "key", config.AesKey }, { "initVector", config.AesInitVector }, { "salt", config.AesSalt } }; dict.Keys.ToList().ForEach(key => { dict[key] = Decrypt(cert, dict[key]); }); _aesSettings = new AesSettings(dict["key"], dict["initVector"], dict["salt"]); }
/// <summary> /// get configured redirection for a category id /// </summary> /// <param name="categoryId"></param> /// <returns>null if no redirect</returns> public static CategoryRedirect GetCategoryRedirect(long categoryId) { var catRedConfig = ConfigLoader.Get <CategoryRedirectConfig>(); return(catRedConfig != null ? catRedConfig.CategoryRedirects.FirstOrDefault(c => c.CategoryId == categoryId.ToString(CultureInfo.InvariantCulture)) : null); }
/// <summary> /// Setup RequireJS to be used in layouts /// </summary> /// <param name="baseUrl">Scrips folder</param> /// <param name="requireUrl">requirejs.js url</param> /// <param name="configsList">RequireJS.config files path</param> public static MvcHtmlString RenderRequireJsSetup(this HtmlHelper html, string baseUrl, string requireUrl, IList <string> configsList, IRequireJsLogger logger = null) { var entryPointPath = html.RequireJsEntryPoint(); if (entryPointPath == null) { return(new MvcHtmlString(string.Empty)); } if (!configsList.Any()) { throw new Exception("No config files to load."); } var processedConfigs = configsList.Select(r => { var resultingPath = html.ViewContext.HttpContext.MapPath(r); PathHelpers.VerifyFileExists(resultingPath); return(resultingPath); }).ToList(); var loader = new ConfigLoader(processedConfigs, logger); var resultingConfig = loader.Get(); var outputConfig = new JsonConfig { BaseUrl = baseUrl, Locale = html.CurrentCulture(), Paths = resultingConfig.Paths.PathList.ToDictionary(r => r.Key, r => r.Value), Shim = resultingConfig.Shim.ShimEntries.ToDictionary(r => r.For, r => new JsonRequireDeps { Dependencies = r.Dependencies.Select(x => x.Dependency).ToList(), Exports = r.Exports }), Map = resultingConfig.Map.MapElements.ToDictionary(r => r.For, r => r.Replacements.ToDictionary(x => x.OldKey, x => x.NewKey)) }; var options = new JsonRequireOptions { Locale = html.CurrentCulture(), PageOptions = html.ViewBag.PageOptions, WebsiteOptions = html.ViewBag.GlobalOptions }; var configBuilder = new JavaScriptBuilder(); configBuilder.AddStatement(JavaScriptHelpers.SerializeAsVariable(options, "requireConfig")); configBuilder.AddStatement(JavaScriptHelpers.SerializeAsVariable(outputConfig, "require")); var requireRootBuilder = new JavaScriptBuilder(); requireRootBuilder.AddAttributesToStatement("data-main", entryPointPath.ToString()); requireRootBuilder.AddAttributesToStatement("src", requireUrl); return(new MvcHtmlString(configBuilder.Render() + requireRootBuilder.Render())); }
/// <summary> /// Because Product.ThumbnailImage and Product.ProductImage were designed for sites with simple image requirements (thumbnail and detail), /// we use this function to pull out images from the product attributes when multiple image sizes are needed. For the demo store, we have at least /// three sizes to choose from. /// </summary> /// <param name="product">The product that we would like to retrieve the image for.</param> /// <param name="attributeName">The product attribute that holds the image we would like to use.</param> /// <param name="fallbackUrl">A fallback image URL to use in case the image doesn't exist.</param> /// <returns>The URI of the image.</returns> public static string GetImageFromAttribute(Product product, string attributeName, string fallbackUrl) { var imgurl = product.CustomAttributes.ValueByName(attributeName) ?? fallbackUrl; if (!imgurl.StartsWith("http")) { imgurl = ConfigLoader.Get<ExternalWebLinkConfig>().ProductImageUrl + imgurl; } return imgurl; }
private async Task <string> GetStringAsync(string uri, bool bNoRetry = false) { var log = BeginLog("GET", uri); HttpResponseMessage response; if (bNoRetry) { response = await _httpClient.GetAsync(uri).ConfigureAwait(false); } else { response = await RetryIfTokenExpired(() => _httpClient.GetAsync(uri)).ConfigureAwait(false); } LogResponse(log, response); string payload = null; if (response.Content != null) { payload = await response.Content.ReadAsStringAsync().ConfigureAwait(false); } if (response.StatusCode == HttpStatusCode.NotFound) { // for an ordinary "resource not found" such as a wrong prod id, we return null string // but if uri is totally nutso cuckoo, throw not found if (string.IsNullOrEmpty(payload) || ExtractError(payload).Relation.EndsWith("shoppers/errors")) { ThrowIfFail(response, log, payload); } } else if (response.StatusCode == HttpStatusCode.Conflict) { // for an ordinary "conflict" we will throw and exception // but if the error "code" is in our configured list of codes to treat as 404's, return null var config = ConfigLoader.Get <Psuedo404ErrorCodesConfig>(); if (!config.Codes.Contains(ExtractError(payload).Code)) { ThrowIfFail(response, log, payload); } } else { await ThrowIfFailAsync(response, log).ConfigureAwait(false); } if (response.StatusCode == HttpStatusCode.NotFound || response.StatusCode == HttpStatusCode.Conflict) { payload = null; } EndLog(log, payload, _refreshingCache ? DataFlow.CacheRefresh : DataFlow.FromShopperApi); return(payload); }
public static async Task <Billboard> GetAsync(IClient client) { if (_current != null) { return(_current); } var uriConfig = ConfigLoader.Get <ShopperApiUriConfig>(); _current = new Billboard { RawBillboard = (await client.GetCacheableAsync <ShopperApiBillboard>(uriConfig.BillboardUri).ConfigureAwait(false)).V1 }; return(_current); }
private static bool TryGetSiteInfo(HttpContext context, out SiteInfo siteInfo) { string siteId; string cultureCode; if (!context.TryGetSiteId(out siteId) || !context.TryGetCultureCode(siteId, out cultureCode)) { siteInfo = null; return(false); } var siteConfiguration = ConfigLoader.Get <SiteConfig>(); return(siteConfiguration.TryGetSiteInfo(new SiteCultureInfo(siteId, (string)context.Items[MarketPlaceParameter], cultureCode, ""), out siteInfo)); }
private static ConfigurationCollection GetOverridenConfig( List <string> processedConfigs, RequireRendererConfiguration config, string entryPointPath) { var loader = new ConfigLoader( processedConfigs, config.Logger, new ConfigLoaderOptions { LoadOverrides = config.LoadOverrides, CachingPolicy = config.ConfigCachingPolicy }); var resultingConfig = loader.Get(); var overrider = new ConfigOverrider(); overrider.Override(resultingConfig, entryPointPath.ToModuleName()); return(resultingConfig); }
private VariationsCollection GetVariationsByAttributes(Product parentProduct, Variations variations) { VariationsCollection collection = null; if (variations != null) { var config = ConfigLoader.Get <ProductVariationsConfig>(); var group = GetGroup(config, parentProduct, variations); if (group != null) { // GUID changes on every call - use a value that is driven off the data //var id = Guid.NewGuid().ToString("N"); var sb = new StringBuilder(); sb.Append(parentProduct.Id); foreach (var p in variations.Product) { sb.Append('-'); sb.Append(p.Id); } var id = sb.ToString(); var result = GetVariationsByAttributes(variations, id, group.Variations, 0, new List <string>(), new List <string>()); if (result != null) { collection = new VariationsCollection { Id = id, Count = group.Variations.Length, Levels = @group.Variations.Select(v => v.Id + "_" + id).ToArray(), Variations = result }; } } } return(collection); }
public static async Task <ResourceAccessBillboard> GetResourceAccessAsync(IClient client) { if (_current != null) { return(_current.RawBillboard.ResourceAccess); } var uriConfig = ConfigLoader.Get <ShopperApiUriConfig>(); // make sure we do this as unauthorized, otherwise we might suffer from attempting to use an expired token and get in an endless loop var saveBearerToken = client.BearerToken; try { var res = (await client.GetCacheableAsync <ShopperApiBillboard>(ResolveTemplate(uriConfig.BillboardUri, Templates.ApiKeyQuery, new { apiKey = client.ApiKey })).ConfigureAwait(false)).V1.ResourceAccess; client.BearerToken = saveBearerToken; return(res); } catch (Exception) { client.BearerToken = saveBearerToken; throw; } }
public static string GetSessionTokenUri() { var uriConfig = ConfigLoader.Get <ShopperApiUriConfig>(); return(uriConfig.SessionTokenUri); }
private static void ReconfigureLog() { var hier = log4net.LogManager.GetRepository() as Hierarchy; if (hier != null) { // Get appender var jungoAppender = (RollingFileAppender)hier.GetAppenders() .FirstOrDefault( appender => appender.Name.Equals("JungoAppender", StringComparison.InvariantCultureIgnoreCase)); if (jungoAppender != null) { var config = ConfigLoader.Get<JungoLoggerLog4NetConfig>(); _configuredDelimiter = config.Delimiter; _logLevelsIncluded = config.LogLevelsIncluded; var delimiter = _configuredDelimiter == JungoLoggerLog4NetDelimiter.Comma ? "," : "\t"; var header = new StringBuilder("datetime"); var logFormatBuilder = new StringBuilder("{0}"); foreach (var column in config.Columns) { var colNum = -1; switch (column.FieldName) { case "Order": colNum = 1; break; case "LogType": colNum = 2; break; case "RequestType": colNum = 3; break; case "TimeElapsed": colNum = 4; break; case "Host": colNum = 5; break; case "Uri": colNum = 6; break; case "RequestPayload": colNum = 7; break; case "HttpStatus": colNum = 8; break; case "DataFlow": colNum = 9; break; case "ResponsePayload": colNum = 10; break; case "Error": colNum = 11; break; case "SessionId": colNum = 12; break; case "RequestId": colNum = 13; break; case "DrRequestId": colNum = 14; break; case "ResponsePayloadFirst1000": colNum = 15; break; case "ResponsePayloadCompressed": colNum = 16; break; case "ServerTrace": colNum = 17; break; } if (colNum < 0) continue; header.Append(String.Format("{0}{1}", delimiter, column.Heading)); logFormatBuilder.Append(String.Format("{0}{{{1}}}", delimiter, colNum)); } header.Append("\n\r"); if (config.Columns.Count() < 17) { for (var i = config.Columns.Count(); i < 17; i++) logFormatBuilder.Append(delimiter); } _logFormat = logFormatBuilder.ToString(); var layout = new log4net.Layout.PatternLayout { Header = header.ToString(), ConversionPattern = "%message%newline" }; layout.ActivateOptions(); jungoAppender.Layout = layout; jungoAppender.ActivateOptions(); } } _log = log4net.LogManager.GetLogger("JungoLogger"); }
/// <summary> /// Setup RequireJS to be used in layouts /// </summary> /// <param name="html"> /// Html helper. /// </param> /// <param name="config"> /// Configuration object for various options. /// </param> /// <returns> /// The <see cref="MvcHtmlString"/>. /// </returns> public static MvcHtmlString RenderRequireJsSetup( this HtmlHelper html, RequireRendererConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } var entryPointPath = html.RequireJsEntryPoint(config.BaseUrl, config.EntryPointRoot); if (entryPointPath == null) { return(new MvcHtmlString(string.Empty)); } if (config.ConfigurationFiles == null || !config.ConfigurationFiles.Any()) { throw new Exception("No config files to load."); } var processedConfigs = config.ConfigurationFiles.Select(r => { var resultingPath = html.ViewContext.HttpContext.MapPath(r); PathHelpers.VerifyFileExists(resultingPath); return(resultingPath); }).ToList(); var loader = new ConfigLoader( processedConfigs, config.Logger, new ConfigLoaderOptions { LoadOverrides = config.LoadOverrides, CachingPolicy = config.ConfigCachingPolicy }); var resultingConfig = loader.Get(); var overrider = new ConfigOverrider(); overrider.Override(resultingConfig, entryPointPath.ToString().ToModuleName()); var locale = config.LocaleSelector(html); var outputConfig = new JsonRequireOutput { BaseUrl = config.BaseUrl, Locale = locale, UrlArgs = config.UrlArgs, WaitSeconds = config.WaitSeconds, Paths = resultingConfig.Paths.PathList.ToDictionary(r => r.Key, r => r.Value), Shim = resultingConfig.Shim.ShimEntries.ToDictionary( r => r.For, r => new JsonRequireDeps { Dependencies = r.Dependencies.Select(x => x.Dependency).ToList(), Exports = r.Exports }), Map = resultingConfig.Map.MapElements.ToDictionary( r => r.For, r => r.Replacements.ToDictionary(x => x.OldKey, x => x.NewKey)) }; config.ProcessConfig(outputConfig); var options = new JsonRequireOptions { Locale = locale, PageOptions = RequireJsOptions.GetPageOptions(html.ViewContext.HttpContext), WebsiteOptions = RequireJsOptions.GetGlobalOptions(html.ViewContext.HttpContext) }; config.ProcessOptions(options); var configBuilder = new JavaScriptBuilder(); configBuilder.AddStatement(JavaScriptHelpers.SerializeAsVariable(options, "requireConfig")); configBuilder.AddStatement(JavaScriptHelpers.SerializeAsVariable(outputConfig, "require")); var requireRootBuilder = new JavaScriptBuilder(); requireRootBuilder.AddAttributesToStatement("src", config.RequireJsUrl); var requireEntryPointBuilder = new JavaScriptBuilder(); requireEntryPointBuilder.AddStatement( JavaScriptHelpers.MethodCall( "require", (object)new[] { entryPointPath.ToString() })); return(new MvcHtmlString( configBuilder.Render() + Environment.NewLine + requireRootBuilder.Render() + Environment.NewLine + requireEntryPointBuilder.Render())); }
public override List <Bundle> ParseConfigs() { var bundles = new List <Bundle>(); if (!Directory.Exists(ProjectPath)) { throw new DirectoryNotFoundException("Could not find project directory."); } FindConfigs(); var loader = new ConfigLoader( FilePaths, new ExceptionThrowingLogger(), new ConfigLoaderOptions { ProcessBundles = true }); Configuration = loader.Get(); foreach (var bundle in Configuration.AutoBundles.Bundles) { var files = new List <string>(); var bundleResult = new Bundle { Files = new List <FileSpec>(), Output = this.GetOutputPath(bundle.OutputPath, bundle.Id), ContainingConfig = bundle.ContainingConfig, BundleId = bundle.Id }; bundles.Add(bundleResult); var tempFileList = new List <RequireFile>(); foreach (var include in bundle.Includes) { if (!string.IsNullOrEmpty(include.File)) { files.Add(this.ResolvePhysicalPath(include.File)); } else if (!string.IsNullOrEmpty(include.Directory)) { var absDirectory = this.GetAbsoluteDirectory(include.Directory); // not using filter for this since we're going to use the one the user provided in the future var dirFiles = Directory.GetFiles(absDirectory, "*", SearchOption.AllDirectories).Where(r => Path.GetExtension(r) == ".js").ToList(); files.AddRange(dirFiles); } } files = files.Distinct().ToList(); var fileQueue = new Queue <string>(); this.EnqueueFileList(tempFileList, fileQueue, files); while (fileQueue.Any()) { var file = fileQueue.Dequeue(); var fileText = File.ReadAllText(file, encoding); var relativePath = PathHelpers.GetRelativePath(file, EntryPoint + Path.DirectorySeparatorChar); var processor = new ScriptProcessor(relativePath, fileText, Configuration); processor.Process(); var result = processor.ProcessedString; var dependencies = processor.Dependencies.Select(r => this.ResolvePhysicalPath(r)).Distinct().ToList(); tempFileList.Add(new RequireFile { Name = file, Content = result, Dependencies = dependencies }); this.EnqueueFileList(tempFileList, fileQueue, dependencies); } while (tempFileList.Any()) { var addedFiles = bundleResult.Files.Select(r => r.FileName).ToList(); var noDeps = tempFileList.Where(r => !r.Dependencies.Any() || r.Dependencies.All(x => addedFiles.Contains(x))).ToList(); if (!noDeps.Any()) { noDeps = tempFileList.ToList(); } foreach (var requireFile in noDeps) { bundleResult.Files.Add(new FileSpec(requireFile.Name, string.Empty) { FileContent = requireFile.Content }); tempFileList.Remove(requireFile); } } } this.WriteOverrideConfigs(bundles); return(bundles); }
public void SetApiKeyFromConfig() { ApiKey = ConfigLoader.Get <ShopperApiKeyConfig>().ApiKey; }