Posts Embedding resources in WebParts
Post
Cancel

Embedding resources in WebParts

Today I came across a requirement of showing an swf file in the webpart. So I thought I will upload the swf file in folder and give its url to the webpart. But then that will be hardcoded path. What will happen if the user deleted that folder or rather deleted that file itself? So my webpart will not run.

So I found some alternative to this and thought of embedding my swf file and js file in webpart itself. I googled on how can I do this, and here are the steps for embedding the files in the webpart itself.

I ll assume that you are ready with the Webpart and you just need to remove the hard coded file’s url’s in your webpart. And i ll be using swfobject.js file in this example you can change the file and the type though, as per your requirements.

– Add swfobject.js file in the same project as webpart.

– Right click on js file select properties and change build action to “Embedded Resource”.

– Make an entry in AssemblyInfo.cs or AssemblyInfo.vb file like

[assembly: WebResource(“ReadENote.swfobject.js”, “text/js”)]

format : [assembly: WebResource(“..”, “”)]

Note : Make sure you specify the namespace along with filename else it will not recognize the file.

– You can access this embedded resource in your webpart code like this

Type t = typeof(); //e.g. Type t = typeof(ReadENote);

string js = “..”; //e.g. string js = “ReadENote.swfobject.js”;

jslocation = Page.ClientScript.GetWebResourceUrl(t, js);

Page.ClientScript.RegisterClientScriptResource(t, js);

This code will embed the specified file, in this case swfobject.js file in my webpart.

Note: you only need to use the last line “Page.ClientScript.RegisterClientScriptResource(t, js);” if you are using the javascript file. If you are using some other file like an image file or swf file, you can use the jslocation in place of your hard coded location.

– my previous code to embed swf file looks like this

strBody = strBody + “var so = new SWFObject(\”notes.swf\”, \”stickies\”, \”250\”, \”250\”, \”9\”, \”#FF6600\”);”;

– my code after using these steps will look like this

Type t = typeof();

string js = “..”;

jslocation = Page.ClientScript.GetWebResourceUrl(t, js);

strBody = strBody + “var so = new SWFObject(\”” + swflocation + “\”, \”stickies\”, \”250\”, \”250\”, \”9\”, \”#FF6600\”);”;

Make these changes, build and deploy your web part.

Enjoy dynamic coding and prevent hard code.

This post is licensed under CC BY 4.0 by the author.