Load image not in xap Silverlight - silverlight

i'm developing an application and i would load an image that isn't in the clientbin folder, but in a folder placed in my server. I would do something like this
BitmapImage bit = new BitmapImage();
string path = "c:/image.png";
bit.UriSource = new Uri(path, UriKind.Absolute);
identity.Source = bit;
but it doesn't function.Any idea?
Thanks

Try:
Image.Source = New Imaging.BitmapImage(New Uri("http://www.Pic.jpg", UriKind.Absolute))
You do not want to include it in your project or the .xap will get huge.

Silverlight applications run on the client, not on the server, so referencing the path as you had been trying to do, would really point to the path on client machine running the application. However, Silverlight does not have rights to read or write from or to the client's disk anyway, due to sercurity reasons. The Isolated Storage functionality is the exception to that.
Therefore, your option is to try the first answer given by Bill, or a WebService, which is more complex to implement.
ib.

To add to Bill's answer. You can also use server side resources using the following helper method which is derived from the location of the xap file.
public static string GetUrlForResource(string resourcePage)
{
var webUrl = Application.Current.Host.Source.ToString();
//Get ClientBin Directory
var stub = webUrl.Substring(0, webUrl.LastIndexOf("/"));
//Get application root.
stub = stub.Substring(0, stub.LastIndexOf("/") + 1);
//Append the application root to the resource page.
webUrl = stub + resourcePage;
return webUrl;
}
To use it like Bill's answer, use the following:
Image.Source = new Imaging.BitmapImage(new Uri(GetUrlForResource("images/myimage.png"), UriKind.Absolute));

Related

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

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 { }

Loading xap file on demand

I have Silverlight application called MyApp. During startup MyApp loads MyApp.Main.xap module using the following code:
WebClient wc = new WebClient();
wc.OpenReadCompleted += new OpenReadCompletedEventHandler(onMainModuleLoaded);
Uri uri = new Uri("MyApp.Main.xap", UriKind.Relative);
wc.OpenReadAsync(uri);
It works. Within MyApp.Main I would like to load another xap file MyApp.Billing.xap, so I wrote like the same as above
WebClient wc = new WebClient();
wc.OpenReadCompleted += new OpenReadCompletedEventHandler(onBillingModuleLoaded);
Uri uri = new Uri("MyApp.Billing.xap", UriKind.Relative);
wc.OpenReadAsync(uri);
but it throws an error saying the file not found. MyApp.Billing.xap file is inside ClientBin folder and I can download it directly via absolute path in a browser. If I try to download MyApp.Billing.xap not from inside MyApp.Main, but from inside MyApp (instead of MyAPp.Main.xap) it also works fine. What might be the problem?
See if you have more success by using the various properties at Application.Current.Host.Source to put together a complete (absolute) uri, instead of trying to use a relative one (after all, what is it relative to?).

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;

Alternatives to using WebClient.BaseAddress to get base url in Silverlight

In a Silverlight application I sometimes need to connect to the web site where the application is hosted. To avoid hard coding the web site in my Silverlight application I use code like this:
WebClient webClient = new WebClient();
Uri baseUri = new Uri(webClient.BaseAddress);
UriBuilder uriBuilder = new UriBuilder(baseUri.Scheme, baseUri.Host, baseUri.Port);
// Continue building the URL ...
It feels very clunky to create a WebClient instance just to get access to the URL of the XAP file. Are there any alternatives?
Application.Current.Host.Source retrieves the URI of the XAP.
I use,
Uri baseUri = new Uri(Application.Current.Host.Source, "/");
// Example results:
// http://www.example.com:42/
// or
// https://www.example.com/
No string parsing needed!
You can also use this method to create full Urls, for example,
Uri logoImageUri = new Uri(Application.Current.Host.Source, "/images/logo.jpg");
// Example result:
// http://www.example.com/images/logo.jpg
This will build the root url in ASP.NET. You would then need to pass in baseUrl via Silverlight's InitParams and add "ClientBin\silverlight.xap".
// assemble the root web site path
var baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority + Request.ApplicationPath.TrimEnd ('/') + '/';
In my case, I am not working in the main folder. I am working in h||p://localhost:1234/subfolder. That is no problem while working in Visual Studio IDE. But when moving to the server it fails. The following lines
Application.Current.Host.Source
can be replaced through a public function with result like this:
Public Sub AppPathWeb()
Res = Application.Current.Host.Source.AbsoluteUri.Substring(0, Application.Current.Host.Source.AbsoluteUri.LastIndexOf("/") + 1)
Return New Uri(Res)
End Sub
As Result, I can catch my files like this
MyImage = New Uri(AppPathWeb, "HelloWorld.jpg")
And the result is, that on server the url goes to h||p://mydomain.com/mysubfolder/HelloWorld.jpg"
Good luck
goldengel.ch

Silverlight image: load URL dynamically?

I'm tinkering with Silverlight 2.0.
I have some images, which I currently have a static URL for the image source.
Is there a way to dynamically load the image from a URL path for the site that is hosting the control?
Alternatively, a configuration setting, stored in a single place, that holds the base path for the URL, so that each image only holds the filename?
From what I gather you aren't trying to change the image itself dynamically, but rather to correctly determine the location of the image at runtime.
I believe simply prefixing the image relative URL with "../" should get you to the root of your application, not necessarily the site as the application might not be hosted in the root of a site.
If your XAP file is located as follows:
http://somesite.foo/app1/somethingelse/clientbin/MyFoo.xap
And you where trying to link the following image:
http://somesite.foo/app1/somethingelse/images/a/boo.png
Apparently all relative URI's are relative to where the XAP file is located (ClientBin folder typically) and Silverlight appends the current Silverlight client namespace. So if you Silverlight control is in the namespace Whoppa you would need to put all your images in the clientbin/Whoppa/ directory. Not exactly convenient.
The workaround is to use absolute URIs as follows:
new Uri(App.Current.Host.Source, "../images/a/boo.png");
In the code behind or a value converter you can do
Uri uri = new Uri("http://testsvr.com/hello.jpg");
YourImage.Source = new BitmapImage(uri);
// create a new image
Image image = new Image();
// better to keep this in a global config singleton
string hostName = Application.Current.Host.Source.Host;
if (Application.Current.Host.Source.Port != 80)
hostName += ":" + Application.Current.Host.Source.Port;
// set the image source
image.Source = new BitmapImage(new Uri("http://" + hostName + "/cute_kitten112.jpg", UriKind.Absolute));
http://www.silverlightexamples.net/post/How-to-Get-Files-From-Resources-in-Silverlight-20.aspx
using System.Windows.Resources; // StreamResourceInfo
using System.Windows.Media.Imaging; // BitmapImage
....
StreamResourceInfo sr = Application.GetResourceStream(new Uri("SilverlightApplication1;component/MyImage.png", UriKind.Relative));
BitmapImage bmp = new BitmapImage();
bmp.SetSource(sr.Stream);
SilverlightHost.Source will provide you the URL that was used to load the XAP file. You can use this to then construct a relative URL for your images.
So if for example your XAP is hosted on http://foo.bar/ClientBin/bas.xap and your images were stored in http://foo.bar/Images/ you can simply use the Source to grab the host name and protocol to construct the new URI.
img.Source = new BitmapImage(image uri) must work.
img.Source = new BitmapImage(new Uri("/images/my-image.jpg", UriKind.Relative)); will properly resolve to the root of the Silverlight application where as "../images/my-image.jpg" will not.
This is only true in the code-behind when dynamically setting the source of the image. You cannot use this notation (the "/" to designate the root) in the XAML (go fiquire, hope they fix that)
The below code worked for me only when the image is included in the project as a resource file:
img.Source = new BitmapImage(new Uri("/images/my-image.jpg", UriKind.Relative));
I am unable to access URL from absolute URLs. Not even Flickr's farm URL for images.

Resources