Say we are building a ASP.net Server Control which contains a lot of images, style sheets and its own .htm help files which also reference several images of their own. This can create a lot of clutter when it comes to packaging and deploying the Server Control. Also due to the many files and folders which categorize and hold all of those images, style sheets and help files there is always the possibility a curios developer using your Server Control might try to rearrange things or substitute content of their own thus breaking the control or maliciously altering the control. In order to clean all this up and solve a lot of these issues in a single blow we can simply embed all these resources right into our assembly (.dll). By doing this we tightly package all resources used by the Server Control and can potentially limit our deployment to just a single assembly (.dll).
So how do we do this? It’s quite easy just follow the steps outlined below.
Step 1: You need to decide which resources you want to have embedded in the assembly. In the example project I chose to embed the style sheet (FancyButtonStyle.css) which defines the way my FancyButton will look as well as the Solution Explorerbackground image (Thundercats.pnd) that is defined within the style sheet. You embed them into the assembly by selecting the file in the Solution Explorer and viewing the properties of the file. In the Properties window there is a property ‘Build Action’ set it to Embedded Resource.
Step 2: Next each of those embedded resources need to be declared in the AssemblyInfo.cs file. Using the WebResource keyword you place the fully qualified path to the resource you are embedding as the first parameter then as the second the mime-type. The third parameter defines whether or not substitution needs to take place within the newly defined resource. What this means is that within resources of mime-type “text” you can define script tags which also define that there are embedded resource url’s within the file. For example within the style sheet ‘FancyButtonStyle.css’ we defined a background-image which has a url property of another embedded resource, the Thundercats.png file. The PerformSubstitution tells .net to parse through the text resources after it is pulled from the assembly and look for script tags which hold the names of embedded resources which need to have their URL generated and inserted into the document. (see thumbnails: AssemblyInfo.cs, Stylesheet)
Step 3: Now write the code within your control’s RenderContents method which will pull out the embedded resources’ URL’s and use them within the HTML to be rendered for the control. (see thumbnail: Render Contents Method)