The next generation of the Teknik Services. Written in ASP.NET. https://www.teknik.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

BundleExtensions.cs 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Security.Cryptography;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Web;
  8. using System.Web.Optimization;
  9. using Teknik.Configuration;
  10. namespace Teknik.Helpers
  11. {
  12. public class CdnScriptBundle : Bundle
  13. {
  14. public CdnScriptBundle(string virtualPath, string cdnHost)
  15. : base(virtualPath, null, new IBundleTransform[] { new JsMinify(), new CdnBundleTransform(cdnHost, ".js") })
  16. {
  17. ConcatenationToken = ";";
  18. }
  19. }
  20. public class CdnStyleBundle : Bundle
  21. {
  22. public CdnStyleBundle(string virtualPath, string cdnHost)
  23. : base(virtualPath, null, new IBundleTransform[] { new CssMinify(), new CdnBundleTransform(cdnHost, ".css") })
  24. {
  25. }
  26. }
  27. public class CdnBundleTransform : IBundleTransform
  28. {
  29. public string CdnHost { get; set; }
  30. public string Ext { get; set; }
  31. public CdnBundleTransform(string cdnHost, string ext)
  32. {
  33. CdnHost = cdnHost;
  34. Ext = ext;
  35. }
  36. public virtual void Process(BundleContext context, BundleResponse response)
  37. {
  38. // Don't continue if we aren't using a CDN
  39. if (!context.BundleCollection.UseCdn)
  40. {
  41. return;
  42. }
  43. // Get the directory and filename for the bundle
  44. var dir = VirtualPathUtility.GetDirectory(context.BundleVirtualPath).TrimStart('/').TrimStart('~').TrimStart('/').TrimEnd('/');
  45. var file = VirtualPathUtility.GetFileName(context.BundleVirtualPath);
  46. var group = string.Format("{0}{1}", file, Ext);
  47. if (string.IsNullOrEmpty(CdnHost))
  48. {
  49. return;
  50. }
  51. using (var hashAlgorithm = SHA256.CreateHashAlgorithm())
  52. {
  53. var hash = HttpServerUtility.UrlTokenEncode(hashAlgorithm.ComputeHash(Encoding.Unicode.GetBytes(response.Content)));
  54. context.BundleCollection.GetBundleFor(context.BundleVirtualPath).CdnPath = string.Format("{0}/{1}/{2}?v={3}&group={4}", CdnHost.TrimEnd('/'), dir, file, hash, group);
  55. }
  56. }
  57. }
  58. }