Take One – On Premise SharePoint 2010
When you’re deploying User Code / Sandbox Solutions to the SharePoint 2010 Solution Gallery you may want to include things you’d usually distribute in files under the 14 hive.
One of the chief restrictions in the Sandbox is that you cannot access the file system. One approach is to embed the file as a resource.
To accomplish this, select the file in Visual Studio’s Solution Explorer that you’d like to embed:
Next, you’ll need a method to retrieve the embedded resource from the compiled assembly (and yes, this works in the Sandbox )
/// <summary>
/// Gets the embedded resource as string.
/// </summary>
/// <param name="filename">The filename.</param>
/// <returns></returns>
private string getEmbeddedResourceAsString(string filename)
{
string resource = "";
using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(filename))
using (StreamReader reader = new StreamReader(stream))
resource = reader.ReadToEnd();
return resource;
}
The only slightly tricky part is working out the “filename” of the resource inside your assembly. It’s usually in the form: ProjectName.FolderName.Filename.Ext
In my example, I used the following:
string javaScript = getEmbeddedResourceAsString("GoogleMapsWebPart.GoogleMap.GoogleMap.js");
Now I can retrieve the contents of the embedded file and use it without needing to deploy any extra resources.
Take Two – SharePoint Online (Office 365) and On Premise SharePoint 2010
The above method fails in the cloud; Office 365 does not like Assembly.GetExecutingAssembly(), so we need an alternative.
First, you need to add a Resource.resx file. You can do this by right-clicking your Visual Studio project node and going to Properties. Then select the Resources tab, and Add Existing File:
From there, navigate to your chosen file you’d like to embed.
You need to change your code to use syntax like: <ProjectName>.Properties.Resources.<ResourceName>.
My example looks like this:
string javaScript = GoogleMapsWebPart.Properties.Resources.GoogleMap;
You can now access your resources directly from your code without any Office 365 Sandbox errors.