本文整理汇总了C#中BundleContext类的典型用法代码示例。如果您正苦于以下问题:C# BundleContext类的具体用法?C# BundleContext怎么用?C# BundleContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
BundleContext类属于命名空间,在下文中一共展示了BundleContext类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: OrderFiles
public override IEnumerable<BundleFile> OrderFiles(BundleContext context, IEnumerable<BundleFile> files)
{
var result = base.OrderFiles(context, files);
return result.Where(f => f.VirtualFile.Name.Equals(_filename, StringComparison.OrdinalIgnoreCase))
.Concat(
result.Where(f => !f.VirtualFile.Name.Equals(_filename, StringComparison.OrdinalIgnoreCase)));
}
示例2: GenerateBundleResponse
public override BundleResponse GenerateBundleResponse(BundleContext context)
{
// This is overridden, because BudleTransformer adds LESS @imports
// to the Bundle.Files collection. This is bad as we allow switching
// Optimization mode per UI. Switching from true to false would also include
// ALL LESS imports in the generated output ('link' tags)
// get all ORIGINAL bundle parts (including LESS parents, no @imports)
var files = this.EnumerateFiles(context);
// replace file pattern like {version} and let Bundler resolve min/debug extensions.
files = context.BundleCollection.FileExtensionReplacementList.ReplaceFileExtensions(context, files);
// save originals for later use
_originalBundleFilePathes = files.Select(x => x.IncludedVirtualPath.TrimStart('~')).ToArray();
var response = base.GenerateBundleResponse(context);
// at this stage, BundleTransformer pushed ALL LESS @imports to Bundle.Files, which is bad...
_transformedBundleFiles = response.Files;
if (!CacheIsEnabled(context))
{
// ...so we must clean the file list immediately when caching is disabled ('cause UpdateCache() will not run)
CleanBundleFiles(response);
}
return response;
}
示例3: Process
public void Process(BundleContext context, BundleResponse response)
{
var compiler = new HandlebarsCompiler();
var templates = new Dictionary<string, string>();
var server = context.HttpContext.Server;
foreach (var bundleFile in response.Files)
{
var filePath = server.MapPath(bundleFile.VirtualFile.VirtualPath);
var bundleRelativePath = GetRelativePath(server, bundleFile, filePath);
var templateName = namer.GenerateName(bundleRelativePath, bundleFile.VirtualFile.Name);
var template = File.ReadAllText(filePath);
var compiled = compiler.Precompile(template, false);
templates[templateName] = compiled;
}
StringBuilder javascript = new StringBuilder();
foreach (var templateName in templates.Keys)
{
javascript.AppendFormat("Ember.TEMPLATES['{0}']=", templateName);
javascript.AppendFormat("Ember.Handlebars.template({0});", templates[templateName]);
}
var Compressor = new JavaScriptCompressor();
var compressed = Compressor.Compress(javascript.ToString());
response.ContentType = "text/javascript";
response.Cacheability = HttpCacheability.Public;
response.Content = compressed;
}
示例4: Process
/// <summary>
/// The process.
/// </summary>
/// <param name="context">
/// The context.
/// </param>
/// <param name="bundleResponse">
/// The bundle response.
/// </param>
/// <exception cref="ArgumentNullException">
/// Argument NULL Exception
/// </exception>
public void Process(BundleContext context, BundleResponse bundleResponse)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (bundleResponse == null)
{
throw new ArgumentNullException("bundleResponse");
}
context.HttpContext.Response.Cache.SetLastModifiedFromFileDependencies();
IEnumerable<BundleFile> bundleFiles = bundleResponse.Files;
bundleResponse.Content = Process(ref bundleFiles);
// set bundle response files back (with imported ones)
if (context.EnableOptimizations)
{
bundleResponse.Files = bundleFiles;
}
bundleResponse.ContentType = "text/css";
}
示例5: GetTransientBundleFilesKey
/// <summary>
/// Returns cache key for <paramref name="bundle" />.
/// </summary>
/// <param name="bundle"><see cref="Bundle" /> to get cache for.</param>
/// <param name="context">Current <see cref="BundleContext" /></param>
/// <returns>Cache key string.</returns>
internal static string GetTransientBundleFilesKey(this Bundle bundle, BundleContext context)
{
return ComposeTransientFilesKey(bundle
.EnumerateFiles(context)
.SelectMany(file => new[] {file.IncludedVirtualPath}.Concat(
GetFileDependencies(bundle, file.IncludedVirtualPath, context))));
}
示例6: OrderFiles
public IEnumerable<FileInfo> OrderFiles(BundleContext context, IEnumerable<FileInfo> files)
{
var workingItems = files.AsParallel().Select(i => new _WorkingItem {
Path = i.FullName,
FileInfo = i,
Dependencies = this._GetDependencies(i.FullName),
});
var fileDependencies = new Dictionary<string, _WorkingItem>(_DependencyNameComparer);
foreach (var item in workingItems) {
_WorkingItem duplicate;
if (fileDependencies.TryGetValue(item.Path, out duplicate))
throw new ArgumentException(string.Format("During dependency resolution, a collision between '{0}' and '{1}' was detected. Files in a bundle must not collide with respect to the dependency name comparer.", Path.GetFileName(item.Path), Path.GetFileName(duplicate.Path)));
fileDependencies.Add(item.Path, item);
}
foreach (var item in fileDependencies.Values) {
foreach (var dependency in item.Dependencies) {
if (!fileDependencies.ContainsKey(dependency))
throw new ArgumentException(string.Format("Dependency '{0}' referenced by '{1}' could not found. Ensure the dependency is part of the bundle and its name can be detected by the dependency name comparer. If the dependency is not supposed to be in the bundle, add it to the list of excluded dependencies.", Path.GetFileName(dependency), Path.GetFileName(item.Path)));
}
}
while (fileDependencies.Count > 0) {
var result = fileDependencies.Values.FirstOrDefault(f => f.Dependencies.All(d => !fileDependencies.ContainsKey(d)));
if (result == null)
throw new ArgumentException(string.Format("During dependency resolution, a cyclic dependency was detected among the remaining dependencies {0}.", string.Join(", ", fileDependencies.Select(d => "'" + Path.GetFileName(d.Value.Path) + "'"))));
yield return result.FileInfo;
fileDependencies.Remove(result.Path);
}
}
示例7: Process
public virtual void Process(BundleContext context, BundleResponse response)
{
var file = VirtualPathUtility.GetFileName(context.BundleVirtualPath);
if (!context.BundleCollection.UseCdn)
{
return;
}
if (string.IsNullOrWhiteSpace(ContainerName))
{
throw new Exception("ContainerName Not Set");
}
var connectionString = CloudConfigurationManager.GetSetting("StorageConnectionString");
var conn = CloudStorageAccount.Parse(connectionString);
var cont = conn.CreateCloudBlobClient().GetContainerReference(ContainerName);
cont.CreateIfNotExists(BlobContainerPublicAccessType.Blob);
var blob = cont.GetBlockBlobReference(file);
blob.Properties.ContentType = response.ContentType;
blob.UploadText(response.Content);
var uri = string.IsNullOrWhiteSpace(CdnHost) ? blob.Uri.AbsoluteUri.Replace("http:", "").Replace("https:", "") : string.Format("{0}/{1}/{2}", CdnHost, ContainerName, file);
using (var hashAlgorithm = CreateHashAlgorithm())
{
var hash = HttpServerUtility.UrlTokenEncode(hashAlgorithm.ComputeHash(Encoding.Unicode.GetBytes(response.Content)));
context.BundleCollection.GetBundleFor(context.BundleVirtualPath).CdnPath = string.Format("{0}?v={1}", uri, hash);
}
}
示例8: GivenAJavascriptFile_Process_ReturnsABundledResponse
public void GivenAJavascriptFile_Process_ReturnsABundledResponse()
{
// Arrange.
var compressorConfig = new JavaScriptCompressorConfig();
var transform = new YuiCompressorTransform(compressorConfig);
var contextBase = A.Fake<HttpContextBase>();
var bundles = new BundleCollection();
var javascriptContent = File.ReadAllText("Javascript Files\\jquery-1.10.2.js");
var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(javascriptContent));
var fakeStream = A.Fake<Stream>(x => x.Wrapping(memoryStream));
var fakeVirtualFile = A.Fake<VirtualFile>(x => x.WithArgumentsForConstructor(new[] { "/Scripts/jquery-1.10.2.js" }));
fakeVirtualFile.CallsTo(x => x.Open()).Returns(fakeStream);
var bundleFiles = new List<BundleFile>
{
new BundleFile("/Scripts/jquery-1.10.2.js", fakeVirtualFile)
};
var bundleContext = new BundleContext(contextBase, bundles, "~/bundles/jquery");
var bundleResponse = new BundleResponse(null, bundleFiles);
// Act.
transform.Process(bundleContext, bundleResponse);
// Assert.
bundleResponse.ShouldNotBe(null);
bundleResponse.Content.Substring(0, 300).ShouldBe("/*\n * jQuery JavaScript Library v1.10.2\n * http://jquery.com/\n *\n * Includes Sizzle.js\n * http://sizzlejs.com/\n *\n * Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors\n * Released under the MIT license\n * http://jquery.org/license\n *\n * Date: 2013-07-03T13:48Z\n */\n(function(bW,bU){v");
bundleResponse.Content.Length.ShouldBe(105397);
memoryStream.Dispose();
}
示例9: SetBundleHeaders
private void SetBundleHeaders(BundleResponse bundleResponse, BundleContext context)
{
if (context.HttpContext.Response == null)
{
return;
}
if (bundleResponse.ContentType != null)
{
context.HttpContext.Response.ContentType = bundleResponse.ContentType;
}
if (context.EnableInstrumentation || context.HttpContext.Response.Cache == null)
{
return;
}
HttpCachePolicyBase cache = context.HttpContext.Response.Cache;
cache.SetCacheability(bundleResponse.Cacheability);
cache.SetOmitVaryStar(true);
cache.SetExpires(DateTime.Now.AddYears(1));
cache.SetValidUntilExpires(true);
cache.SetLastModified(DateTime.Now);
cache.VaryByHeaders["User-Agent"] = true;
}
示例10: GenerateBundleJS
private async static void GenerateBundleJS(ScriptBundle scriptBundle, BundleCollection bundles)
{
string bundleOutputPath = Path.Combine(HttpRuntime.AppDomainAppPath, BundleOutputFile);
BundleContext context = new BundleContext(new HttpContextWrapper(HttpContext.Current), bundles, ScriptsBundleVirtualPath);
System.Text.StringBuilder fileSpacer = new System.Text.StringBuilder();
try
{
using (StreamWriter outputStream = new StreamWriter(bundleOutputPath))
{
outputStream.BaseStream.Seek(0, SeekOrigin.End);
System.Collections.Generic.List<string> filePaths = PrepareFileList(scriptBundle.EnumerateFiles(context));
foreach (string filePath in filePaths)
{
string fileSpacerText = BuildFileSpacer(fileSpacer, filePath);
await outputStream.WriteAsync(fileSpacerText);
using (StreamReader jsFileStream = new StreamReader(filePath))
{
await outputStream.WriteAsync(await jsFileStream.ReadToEndAsync());
}
}
}
}
catch (System.NullReferenceException nullEx)
{
string error = nullEx.Message;
}
}
示例11: Process
public void Process(BundleContext context, BundleResponse response)
{
if (!response.Files.Any(f => f.VirtualFile.VirtualPath.ToLowerInvariant().Contains("jquery")))
{
response.Content = CopyrigthText + response.Content;
}
}
示例12: Process
public void Process(BundleContext context, BundleResponse bundle)
{
context.HttpContext.Response.Cache.SetLastModifiedFromFileDependencies();
var lessParser = new Parser();
ILessEngine lessEngine = CreateLessEngine(lessParser);
var content = new StringBuilder();
var bundleFiles = new List<BundleFile>();
foreach (var bundleFile in bundle.Files)
{
bundleFiles.Add(bundleFile);
SetCurrentFilePath(lessParser, bundleFile.VirtualFile.VirtualPath);
using (var reader = new StreamReader(VirtualPathProvider.OpenFile(bundleFile.VirtualFile.VirtualPath)))
{
content.Append(lessEngine.TransformToCss(reader.ReadToEnd(), bundleFile.VirtualFile.VirtualPath));
content.AppendLine();
bundleFiles.AddRange(GetFileDependencies(lessParser));
}
}
if (BundleTable.EnableOptimizations)
{
// include imports in bundle files to register cache dependencies
bundle.Files = bundleFiles.Distinct().ToList();
}
bundle.ContentType = "text/css";
bundle.Content = content.ToString();
}
示例13: Process
/// <summary>
/// The implementation of the <see cref="IBundleTransform"/> interface
/// </summary>
/// <param name="context"></param>
/// <param name="response"></param>
public void Process(BundleContext context, BundleResponse response)
{
if (null == context)
{
throw new ArgumentNullException("context");
}
if (null == response)
{
throw new ArgumentNullException("response");
}
var urlMatcher = new Regex(@"url\((['""]?)(.+?)\1\)", RegexOptions.IgnoreCase);
var content = new StringBuilder();
foreach (var fileInfo in response.Files)
{
if (fileInfo.Directory == null)
{
continue;
}
var fileContent = _fileProvider.ReadAllText(fileInfo.FullName);
var directory = fileInfo.Directory.FullName;
content.Append(urlMatcher.Replace(fileContent, match => ProcessMatch(match, directory)));
}
context.HttpContext.Response.Cache.SetLastModifiedFromFileDependencies();
response.Content = content.ToString();
response.ContentType = CssContentType;
}
示例14: Process
public void Process(BundleContext context, BundleResponse response)
{
Assert.ArgumentNotNull(response, "response");
response.Content = new CssCompressor().Compress(response.Content);
response.ContentType = "text/css";
}
示例15: Process
public void Process(BundleContext context, BundleResponse response)
{
var strBundleResponse = new StringBuilder();
// Javascript module for Angular that uses templateCache
strBundleResponse.AppendFormat(
@"angular.module('{0}').run(['$templateCache',function(t){{",
_moduleName);
foreach (var file in response.Files)
{
string content;
//Get content
using (var stream = new StreamReader(file.VirtualFile.Open()))
{
content = stream.ReadToEnd();
}
//Remove breaks and escape qoutes
content = Regex.Replace(content, @"\r\n?|\n", "");
content = content.Replace("'", "\\'");
// Create insert statement with template
strBundleResponse.AppendFormat(
@"t.put('{0}','{1}');", file.VirtualFile.VirtualPath.Substring(1), content);
}
strBundleResponse.Append(@"}]);");
response.Files = new BundleFile[] {};
response.Content = strBundleResponse.ToString();
response.ContentType = "text/javascript";
}