I am trying to iterate the list of files that have been added to a specific bundle.
For instance, if I have a bundle that was created like this:
'_App_Start.vbhtml:
BundleConfig.RegisterBundles(System.Web.Optimization.BundleTable.Bundles)
'BundleConfig.vb:
Imports System.Web.Optimization
Public Class BundleConfig
Public Shared Sub RegisterBundles(ByRef bundles As BundleCollection)
bundles.Add(New ScriptBundle("~/bundles/example").Include(
"~/Scripts/file1.js",
"~/Scripts/file2.js"
))
End Sub
End Class
From other *.vbhtml files in the project, I want to be able to iterate a bundle, "~/bundles/example" in this example, in order to obtain the list of files, "~/Scripts/file1.js" and "~/Scripts/file2.js", in this example.
This is what I have so far:
Dim myBundle As System.Web.Optimization.Bundle
myBundle = BundleTable.Bundles.GetBundleFor("~/bundles/example")
'== Stuck Here:
Dim myContext As BundleContext
myContext = "** Pleae Help **"
Dim myIEnumerable As IEnumerable(Of BundleFile)
myIEnumerable = myBundle.EnumerateFiles(myContext)
Looking at the docs for the Bundle.EnumerateFiles method (https://msdn.microsoft.com/en-us/library/system.web.optimization.bundle.enumeratefiles(v=vs.110).aspx) I see that the first argument is the "BundleContext".
This is where I was stuck! How or where do I get the BundleContext value to pass to the EnumerateFiles method?
Edit - Complete working example that uses the code provided in Tetsuya's answer
Dim myBundle As System.Web.Optimization.Bundle
myBundle = BundleTable.Bundles.GetBundleFor("~/bundles/example")
Dim currentContext As HttpContext = httpContext.Current
Dim httpCtxt As HttpContextWrapper
httpCtxt = New HttpContextWrapper(currentContext)
Dim myContext As BundleContext
myContext = New BundleContext(httpCtxt, BundleTable.Bundles, "~/bundles/example")
Dim myIEnumerable As IEnumerable(Of BundleFile)
myIEnumerable = myBundle.EnumerateFiles(myContext)
Dim filepath As String
For Each bundlefile In myIEnumerable.ToArray
filepath = bundlefile.IncludedVirtualPath
' do stuff ..
Next
According to MSDN docs, BundleContext
is a class which its constructor accepts 3 arguments as shown below:
Public Class BundleContext
Public Sub New (context As HttpContextBase, collection As BundleCollection, bundleVirtualPath As String)
End Class
Hence, you need to pass HttpContext
, BundleTable.Bundles
(this is default BundleCollection
, change to custom bundle collection if you have any) and bundle virtual path to create a BundleContext
instance like this example:
Dim currentContext As HttpContext = HttpContext.Current
Dim contextWrapper As HttpContextWrapper
contextWrapper = New HttpContextWrapper(currentContext)
Dim myContext As BundleContext
myContext = New BundleContext(contextWrapper, BundleTable.Bundles, "~/bundles/example")