How do I load a dll's config file inside another appdomain - file

I have an application that needs to load an add-on in the form of a dll. The dll needs to take its configuration information from a configuration (app.config) file. I want to dynamically find out the app.config file's name, and the way to do this, as I understand , is AppDomain.CurrentDomain.SetupInformation.ConfigurationFile
However, since it is being hosted INSIDE a parent application, the configuration file that is got from the above piece of code is (parentapplication).exe.config. I am not able to load another appdomain inside the parent application but I'd like to change the configuration file details of the appdomain. How should I be going about this to get the dll's configuration file?

OK, in the end, I managed to hack something together which works for me. Perhaps this will help;
Using the Assembly.GetExecutingAssembly, from the DLL which has the config file I want to read, I can use the .CodeBase to find where the DLL was before I launched a new AppDomain for it. The *.dll
.config is in that same folder.
Then have to convert the URI (as .CodeBase looks like "file://path/assembly.dll") to get the LocalPath for the ConfigurationManager (which doesn't like Uri formatted strings).
try
{
string assemblyName = Assembly.GetExecutingAssembly().GetName().Name;
string originalAssemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
Uri uri = new Uri(String.Format("{0}\\{1}.dll", originalAssemblyPath, assemblyName));
string dllPath = uri.LocalPath;
configuration = ConfigurationManager.OpenExeConfiguration(dllPath);
}
catch { }

Related

Is it possible to use virtual path provider with DotNetNuke?

We have a DNN module that uses Angular as its client side framework.
I'd like to be able to embed all the resources such as html , js ,css ,images and fonts to my module.(actually our module have more than one dll and every one of them has its own resources so that I don't want to copy all of these resource into main module folder every time I want to make a package)
So far I have tried WebResource.axd which was successful to some extent (Here's what I have done)but then I realized that It is somehow impossible to embed html,images and other stuffs rather than js and css (or it isn't?)
Then I decided to try using VirtualPathProvider and I used this open source project that implements an EmbeddedResourcesVirtualProvider.
I have registered this provider using IRouteMapper interface of DNN. Now that I start testing my project I am getting 404 for all of my resources. I tried to debug the project and put some break points over FileExists ,DirectoryExists and GetFile methods of VirtualProvider but the only virtual path that is being asked from VirtaulProvider is "~/Default.aspx" and nothing else
I would like to ask if it is possible to use VirtualParhProvider with DNN ?
We are using DNN 8.
I think you are over complicating things a bit. If you need a virtual provider for your module to work you are doing it wrong (in my opinion).
A module should be a self-contained package that could be deployed on any DNN installation without having to do anything but install the module.
Normally when you buy or download a free module, it comes in a single zip file with all the necessary files contained in that zip. That could be any type of file (.dll, .js, css, .ascx, .aspx etc) is does not matter as long as it's defined in the .dnn installation file.
You can then link to the files in the ascx of your module.
<script type="text/javascript" src="/DesktopModules/YourModulePath/js/file.js"></script>
or
<img src="/DesktopModules/YourModulePath/images/image.jpg">
With WebResource you can embed anything - images, html, fonts etc., so I would suggest continuing with the approach you've already taken.
I downloaded and installed your module in DDN 8 for testing. So the following assumes that setup.
To embed an image you can do this:
In the library MyFramework:
Add a file called image.png to a new folder \content\images\
Set Build Action to Embedded Resource for this image
Add [assembly: System.Web.UI.WebResource("MyFramework.content.images.image.png", "image/png")] to AssemblyInfo.cs
Add protected string myImageUrl { get; private set; } so we can access the URL in the inheriting class
Add myImageUrl = Page.ClientScript.GetWebResourceUrl(typeof(MyModuleBase), "MyFramework.content.images.image.png"); to your OnInit() method
In the consuming project MyModule:
Add <img src="<%=myImageUrl%>"/> to View.ascx
For HTML and similar content type, you can do basically the same as you have already done for the scripts:
In the library MyFramework:
Add a file called myhtml.html to a new folder \content\html\
(in my file I have: <div style="font-weight: bold;font-size: x-large">Some <span style="color: orange">HTML</span></div>)
Set Build Action to Embedded Resource for the html
Add [assembly: System.Web.UI.WebResource("MyFramework.content.html.myhtml.html", "text/html")] to AssemblyInfo.cs
Add protected string MyHtmlUrl { get; private set; } so we can access the HTML in the inheriting class
Add:
var assembly = Assembly.GetExecutingAssembly();
var resourceName = "MyFramework.content.html.myhtml.html";
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
{
using (StreamReader reader = new StreamReader(stream))
{
MyHtmlUrl = reader.ReadToEnd();
}
}
In the consuming project MyModule:
Add <%=MyHtmlUrl%> to View.ascx

Create a directory dynamically inside the "web pages" folder of a java web application

So I'm trying to dynamically create a folder inside the web pages folder.
I'm making a game database. Everytime a game is added I do this:
public void addGame(Game game) throws DatabaseException {
em.getTransaction().begin();
em.persist(game);
em.getTransaction().commit();
File file = new File("C:\\GameDatabaseTestFolder");
file.mkdir();
}
So everything works here.
The file get's created.
But I want to create the folder like this:
public void addGame(Game game) throws DatabaseException {
em.getTransaction().begin();
em.persist(game);
em.getTransaction().commit();
File file = new File(game.getId()+"/screenshots");
file.mkdir();
}
Or something like that. So it will be created where my jsp files are and it will have the id off the game.
I don't understand where the folder is created by default.
thank you in advance,
David
It's by default relative to the "current working directory", i.e. the directory which is currently open at the moment the Java Runtime Environment has started the server. That may be for example /path/to/tomcat/bin, or /path/to/eclipse/workspace/project, etc, depending on how the server is started.
You should now realize that this condition is not controllable from inside the web application.
You also don't want to store it in the expanded WAR folder (there where your JSPs are), because any changes will get lost whenever you redeploy the WAR (with the very simple reason that those files are not contained in the original WAR).
Rather use an absolute path instead. E.g.
String gameWorkFolder = "/path/to/game/work/folder";
new File(gameWorkFolder, game.getId()+"/screenshots");
You can make it configureable by supplying it as a properties file setting or a VM argument.
See also:
Image Upload and Display in JSP
getResourceAsStream() vs FileInputStream

Silverlight: Business Application Needs Access To Files To Print and Move

I have the following requirement for a business application:
(All of this could be on local or server)
Allow user to select folder location
Show contents of folder
Print selected items from folder (*.pdf)
Display which files have been printed
Potentially move printed files to new location (sub-folder of printed)
How can I make this happen in Silverlight?
Kind regards,
ribald
First of all, all but the last item can be done (the way you expect). Due to security protocols, silverlight cannot access the user's drive and manipulate it. The closest you can get is accessing silverlight's application storage which will be of no help to you whatsoever in this case. I will highlight how to do the first 4 items.
Allow user to select folder location & Show contents of folder
public void OnSelectPDF(object sender)
{
//create the open file dialog
OpenFileDialog ofg = new OpenFileDialog();
//filter to show only pdf files
ofg.Filter = "PDF Files|*.pdf";
ofg.ShowDialog();
byte[] _import_file = new byte[0];
//once a file is selected proceed
if (!object.ReferenceEquals(ofg.File, null))
{
try
{
fs = ofg.File.OpenRead();
_import_file = new byte[fs.Length];
fs.Read(_import_file, 0, (int)fs.Length);
}
catch (Exception ex)
{
}
finally
{
if (!object.ReferenceEquals(fs, null))
fs.Close();
}
//do stuff with file - such as upload the file to the server
};
}
If you noticed, in my example, once the file is retrieved, i suggest uploading it to a webserver or somewhere with temporary public access. I would recommend doing this via a web service. E.g
//configure the system file (customn class)
TSystemFile objFile = new TNetworkFile().Initialize();
//get the file description from the Open File Dialog (ofg)
objFile.Description = ofg.File.Extension.Contains(".") ? ofg.File.Extension : "." + ofg.File.Extension;
objFile.FileData = _import_file;
objFile.FileName = ofg.File.Name;
//upload the file
MasterService.ToolingInterface.UploadTemporaryFileAsync(objFile);
Once this file is uploaded, on the async result, most likely returning the temporary file name and upload location, I would foward the call to some javascript method in the browser for it to use the generic "download.aspx?fileName=givenFileName" technique to force a download on the users system which would take care of both saving to a new location and printing. Which is what your are seeking.
Example of the javascript technique (remember to include System.Windows.Browser):
public void OnInvokeDownload(string _destination)
{
//call the browser method/jquery method
//(I use constants to centralize the names of the respective browser methods)
try
{
HtmlWindow window = HtmlPage.Window;
//where BM_INVOKE_DOWNLOAD is something like "invokeDownload"
window.Invoke(Constants.TBrowserMethods.BM_INVOKE_DOWNLOAD, new object[] { _destination});
}
catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); }
}
Ensure you have the javascript method existing either in an included javaScript file or in the same hosting page as your silverlight app. E.g:
function invokeDownload(_destination) {
//some fancy jquery or just the traditional document.location change here
//open a popup window to http://www.myurl.com/downloads/download.aspx? fileName=_destination
}
The code for download.aspx is outside the scope of my answer, as it varies per need and would just lengthen this post (A LOT MORE). But from what I've given, it will "work" for what you're looking for, but maybe not in exactly the way you expected. However, remember that this is primarily due to silverlight restrictions. What this approach does is rather than forcing you to need a pluging to view pdf files in your app, it allows the user computer to play it's part by using the existing adobe pdf reader. In silverlight, most printing, at least to my knowledge is done my using what you call and "ImageVisual" which is a UIElement. To print a pdf directly from silverlight, you need to either be viewing that PDF in a silverlight control, or ask a web service to render the PDF as an image and then place that image in a control. Only then could you print directly. I presented this approach as a lot more clean and direct approach.
One note - with the temp directory, i would recommend doing a clean up by some timespan of the files on the server side everytime a file is being added. Saves you the work of running some task periodically to check the folder and remove old files. ;)

Image Resources in WinForms

I want to store images in a .dll file and use them for my winform application. but Im not able to load .dll content
System.IO.Stream stream;
System.Reflection.Assembly assembly;
Image bitmap;
assembly = System.Reflection.Assembly.LoadFrom(Application.ExecutablePath);
stream = assembly.GetManifestResourceStream("global::template.Properties.Resources.test.png");
bitmap = Image.FromStream(stream);
this.background.titleImage = bitmap; // image box
The most likely problem is that the path you are specifying in GetManifestResourceStream() is not correct.
I find the following helpful to debug these issues:
Open assembly that has the resource embedded into it, in Reflector.
Open the Resources folder.
From the list of resource paths\folders, find the one with your resource in it.
If you cannot find your resource, did you mark it as an embedded resource?
Your resource path will be "Resource folder" + "." + "resource name".
e.g. "PrismDemo.Properties.Resources.resources.app.ico"
You are using the wrong name, "global::" doesn't appear in the manifest resource name. A typical name would be project.test.png if you added the resource to the project and set its Build Action to "Embedded Resource". To avoid guessing at the name, use Ildasm.exe and find the .mresource in the manifest.
However, your name suggests you added the resource in the Project + Properties, Resources tab. Good idea, that auto-generates a property name for the resource. You'd use project.Properties.Resources.test to reference it. You'll get an Image back, no need to use GetManifestResourceStream.
The project name I listed above is the default namespace name you assigned to the project. Project + Properties, Application tab, Default namespace setting.

WPF control hosted in Windows Forms: Is it possible to access resource files?

I have a WPF control hosted in Windows Forms and I would like to access it's resources, specifically images. What is the best way to do that?
I was thinking of using a ResourceDictionary, but I'm not sure how I can access it from within a Windows Form.
This is a standalone WPF control, in a DLL? There are two ways that the resources can be embedded... as part of a .resources file (e.g. the Project's "Resoruces" tab), or as files included as "Embedded Resources"...
To get the assembly reference to the DLL this is usually the easiest:
var ass = typeof(ClassInOtherDll).Assembly;
In the Resources
If this is part of the default project resources, and not a different .resources file included inside the DLL, you can use the default base-name.
var ass = typeof(ClassInTargetDLL).Assembly;
var rm = new ResourceManager("...BaseName...", ass);
BaseName for default project resources is :
C# := Namespace.Properties.Resources
VB := Namespace.Resources
After that you can just call GetObject() and do a cast back:
var myImage = rm.GetObject("check_16");
return myImage as Bitmap;
If you want to find out whats in there, get the assembly reference and call
ass.GetManifestResourceNames()
.resources files can be used with a ResourceManager
embedded resources will just show up as a list. Use the other method for these.
And this is all assuming they default culture =)
As Embedded Resources
You can use the regular methods on the assembly to get an embedded resource. You find it by name, and then Basically you will need to convert the stream back into your desired type.
GetManifestResourceNames()
GetManifestResourceStream(name)
help getting the desired file with a helper function to find files by name.
I usually use these like this:
// called GetMp3 in the post, but it returns a stream. is the same thing
var stream = GetResourceStream("navigation.xml");
var reader = New XmlTextReader(stream);
return reader;
To get an image that is an embedded resource, this works for me:
var stream = GetResoureStram("check_32.png");
var bmp = new Bitmap(stream);
this.MyButton.Image = bmp;

Resources