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

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