Question

I am building a library that has some dependancies that are not compiled (example: javascript and css files).

What i would like is to have the dependant files automatically created in or copied to the consuming project's structure when the library is referenced - dynamically at reference time.

Through my research i have found ways to do this with pre and post build scripts on the consuming project, but what i really want to do is this:

  • In Consumer, Add Reference to Library
  • Code Executes that Copies all relevant *.js and *.css files from Library's folder structure to Consumer folder structure.
  • If copy is not acheviable, i would be ok with code executing to create the relevant files in Consumer.

Again, i would like to avoid pre and post build scripts if i can - at the end of the day i need the consumer to have in place the js and css files from the library so that the display and execution work without forcing the consumer to manually move these files.

Thanks for any help offered.

Was it helpful?

Solution

As Hans said in his comment: just embed them as resources in the assembly. Doing so for javascript, css, and images is pretty trivial.

  1. Go to the properties on the file (js/css/images) and set it's Copy to Output action to Do Not Copy and Build Action to Embedded Resource
  2. In the AssemblyInfo.cs file of your assembly project add lines such as:

    [assembly: WebResource("MyAssembly.Javascript.MyJavascript.js", "application/javascript", PerformSubstitution = false)]

  3. To inject the javascript into a page (from a user control or whatever located in your assembly) add the following:

    String location = Page.ClientScript.GetWebResourceUrl(this.GetType(), "MyAssembly.Javascript.MyJavascript.js");

    StringBuilder startup = new StringBuilder(String.Empty); startup.Append(@""); startup.Append("");

    Page.Header.Controls.Add(new LiteralControl(startup.ToString()));

Note the PerformSubstitution parameter to the WebResource directive. This allows you to put things like the following in your embedded CSS files:

.ribbonGroupLeft {
    width: 3px;
    height: 85px;
    background-image: url(<%=WebResource("MyAssembly.images.RibbonGroupLeft.png") %>);
    background-repeat: no-repeat;
    overflow: hidden;
    margin: 0px 0px 0px 0px;
    padding: 0px 0px 0px 0px;
}

The URL points to an image located inside the assembly. By setting PerformSubstitution to true .net will automatically set the URL to the correct location.

As a side note, all major control library vendors do something along the lines of the above. Works great, as long as you remember to do step 1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top