Replacing Absolute file path by Resource file path - vb.net

I created an add-in to an existing software (Revit) and I want to embed an image (my company's logo) in the add-in's button.
Here is my current code for it:
'Set the large image shown on button
Dim uriImage As New Uri("\\10.8.60.3\Shared\REVIT\FSElogo.png")
Dim largeImage As New BitmapImage(uriImage)
MainButton.LargeImage = largeImage
It works pretty well and the logo is correctly displayed, however it requires the computer to have access to the server located at \\10.8.60.3. When working from home, we do not have access to this server and Revit throws an error when starting because of it.
So I tried adding the FSElogo.png file to my VB.Net project as a Resource and then tried to use My.Resources to access the image, effectively removing the need for an external image to be used.
Well, I can't get it to work.
I tried replacing the code above by
MainButton.LargeImage = CType(My.Resources.ResourceManager.GetObject("FSElogo.png"), Windows.Media.ImageSource)
But it doesn't work. It doesn't throw an error, but no image is displayed on the button.
If I don't cast my Object to an ImageSource I get an implicit conversion from Object to Image error, and I'm not even sure my ResourceManager is even really returning the object FSElogo.png.
What am I doing wrong here?

I am using the VS provided button with the .BackgroundImage property. Notice that the extension of the file is not included in the resource identifier. If this doesn't work, you will have to explain exactly how you added the resource to your project.
MainButton.BackgroundImage = My.Resources.FSElogo

Related

Is it possible to make WebView control to read local html files?

I'm making an application with WebView control. And I want it to read local html file. But I can't find the right way to make it possible.
At first, I simply tried to use Navigate method and provide the file path in the "file:///~" format string as a parameter, but it didn't work.
https://learn.microsoft.com/ja-jp/windows/communitytoolkit/controls/wpf-winforms/webview-known-issues
This Microsoft page says that WebView control does not recognize "file:///~" protocol.
And it shows the 3 solutions to make WebView control to read local html files.
Use NavigateToLocal() method.
Use NavigateToLocalStreamUri() method.
Use NavigateToString() method.
I tried all of them, but each 3 have some issues that doesn't make it work.
NavigateToLocal method requires a RELATIVE path of the file (not the absolute path), relative from the application executable directory. So files in somewhere else from the application directory cannot be read by this method.
NavigateToLocalStreamUri method is not even implemented according to the page! I once tried it anyway, but it returned an exception and didn't work.
NavigateToString method can render the given html content string, but the external files like css, js, image files included by html codes cannot be loaded, so it does not provide a full function.
I found some sample of using NavigateToLocalStreamUri method and tried it by myself.
(VB.NET)
wvwMain.NavigateToLocalStreamUri(uri, New StreamUriResolver())
Public Class StreamUriResolver : Implements IUriToStreamResolver
Public Function UriToStream(uri As Uri) As Stream Implements IUriToStreamResolver.UriToStream
Return New FileStream(uri.LocalPath, FileMode.Open)
End Function
End Class
By this code, NavigateToLocalStreamUri method returns System.Resources.MissingManifestResourceException.
What I want to realize is very simple.
Using WebView control
Read local html file located anywhere on the local storage
And render the html file completely as an expected result
But I don't see the way right now.
I would appreciate your advises or helps.
The method NavigateToLocalStreamUri will not work. Please see https://learn.microsoft.com/en-us/windows/communitytoolkit/controls/wpf-winforms/webview-known-issues.
You have to use NavigateToLocal, but you will see a warning that it is deprecated. However, it does only work with relative paths. Is it possible for you to restructure your application so that you can use relative paths?
The NavigateToLocal method is the only way that I've found to call local HTML files in Microsoft.Toolkit.Forms.UI.Controls.Web WebView v6.0.
On Visual Studio 2019 Windows 10, the following VB.NET code works on my PC
Imports System.IO
Dim sFileName = Application.StartupPath & "/MyPage.html"
wv.NavigateToString(System.IO.File.ReadAllText(sFileName))
where wv is a WebView object.

The location of .config for geotiler on Windows

I'm working in jupyter notebook on Windows with matplotlib basemaps and I want to use geotiler with the basemaps. I'm writing a program and as part of it, it will generate a map and plot data points on it. However, the maps that my code generates often are over a small part of the world and have no defining features. My solution was to import the geotiler library and display it over the map with an alpha so the maps generated would be identifiable. However, when I use the geotiler.Map() function, I get a message saying that the configuration file does not exist.
The code and the error message
How do I locate the .config folder on Windows, if it exists, and where should I create it if it doesn't? I already tried my user folder but that didn't seem to work. Thanks in advance.
Figured it out.
The read_config() method in the source code tries to get the HOME environment variable, which for Windows is blank, and appends the path for the config to that. Importing os and manually setting the HOME variable to wherever you placed your .config folder seems to do the trick. You can do this with os.environ['HOME'] = 'C:\Users\YourName'.

Databinding uri source of imagebrush

In my application i am binding several properties to a custom user control, and everything works fine, except the images are not showing. For binding i have used the following codes:
Categories.Add(new Models.Category { Name = "Pizza", Count= 4, ImageUri = new Uri("Images/pizza.png", UriKind.Relative) });
I have also tried with different urikinds but the images are never showing.
what could go wrong? The images are in my solutions Images folder.
Use the ms-appx URI scheme:
ImageUri = new Uri("ms-appx:///Images/pizza.png");
Take care to really write ///.
Also make sure that the Build Action of the image file is set to Content, as pointed out in the other answer. Setting Copy to Output Directory does however not seem to be necessary.
Be sure you set the properties of the image so that it is available during runtime. Sometimes if employing Design Time data in Blend, you will see the images in Design Time, but then nothing during run time. The reason is that the images were never deployed with the rest of the solution. Be sure the Build Action on each image is set to Content and I usually set the Copy to Output Directory to Copy if Newer.

Compile image in .exe vb.net

I want to make a simple .exe application in vb.net. The application wont have an installation just pure run on .exe file .
Application has one form and two pictures. When i set the option on image to build action - compile
Unable to open module file 'C:\Users\t3cho\documents\visual studio 2013\Projects\Apps\Apps\Resources\power.png': System Error &H80041feb&
Is there any other way to make an .exe file with images without installation or additional folders.
The easiest way to include images (and other types of resources) into the application is to right-click the project, go to the "Resources"-Tab and add the image there. You can change its name to e.g. MyEmbeddedImage and access it like this
Dim img As Image = Properties.Resources.MyEmbeddedImage
or
Dim img As Image = My.Resources.MyEmbeddedImage
This automatically sets the Build Action to None.
Note: This approach is type-safe and you will get errors at compile time, if the image is missing.
See: My.Resources Object and How to: Add or Remove Resources
If you still want to embed the image "manually", you must set the Build Action to Embedded Resource and access it as #Icemanind describes.
Yes. It's called embedded resources. Set your image's Build Action to Embedded Resource. You can then get the image at runtime like so:
Try
_assembly = [Assembly].GetExecutingAssembly()
_imageStream = _assembly.GetManifestResourceStream("MyNameSpace.MyImage.png")
' Do something with _imageStream
Catch ex As Exception
' Resource not found or something went wrong
End Try

Unraveling the confusion about Embedded Resources

EDIT: Read answer number 1 from Tim Schmelter and then use this question for examples of how to embed resources and access them at runtime.
The subject of embedded resources comes up a lot, especially with people asking how to access the embedded files at runtime. Things get more confusing because Visual Studio gives you 2 different ways of embedding a resource, and different ways of accessing those resources at runtime. The problem is that depending on which method you used to embed the resource, the method you’re trying to use to access the file at runtime might not work. This post is an attempt to clear up all the confusion that I see out there, but I also have a question that nobody can seem to answer factually: Why is the size of my compiled program TWICE the size of the embedded resource (sometimes)? For example if I embed a 20MB file into my project, why does my program compile to 40MB? I haves asked this question in the past and nobody was able to reproduce my results. I found that the reason they were not able to reproduce was because they were embedding the file in a different way. See here:
Method 1:
Double-click on My Project to open the property pages and go to the Resources Tab. Now click Add Resource > Add Existing File. Browse to the file you want to embed. For this example I’m using an executable. You will now see your file on the Resources Tab:
You will also see that a folder named Resources was created under your project and the embedded file has been placed in this folder:
EDIT: THIS NEXT STEP WAS THE PROBLEM. TURNS OUT THAT WHEN YOU ADD A FILE VIA THE RESOURCES TAB YOU SHOULD NOT SET THE BUILD ACTION TO EMBEDDED RESOURCE. Counter intuitive to say the least!
Now with the file selected, look down at the properties window for the file and change the build action to Embedded Resource: (this step should ONLY be performed when you add a file via method 2).
Now compile your program. You will see that the size of your compiled program is at least double the size of your embedded resource. This does not happen with method 2. See here:
Method 2:
Right-click on your project name and choose Add > Existing Item. Browse to your file, and this time you will notice that while it was indeed placed under your project, there was no Resources folder created:
Now once again select the file and change the Build Action to Embedded Resource and compile. This time the size of the compiled program will be as you expected - about the size of the embedded file and not double the size as with method 1.
Which method you use to embed your file will determine which method you can use to access the file at runtime. For method 1 this is very simple, all you have to do is:
My.Computer.FileSystem.WriteAllBytes(Path, My.Resources.ResourceName, Append)
Where Path is the location and name for the file you want to save on the harddrive, ResourceName is the name of the embedded resource that you see in the project window (minus any extension), and Append is whether or not you want to create a new file or overwrite an existing file. So for example, using test.exe from the above images, I could save that file to the C drive like this:
My.Computer.FileSystem.WriteAllBytes(“C:\test.exe”, My.Resources.test, False)
Couldn’t be easier.
Method 2 however doesn’t appear to give you access to My.Resources so it gets a little more complicated. You have to create a Stream to hold the resource, put the stream into a byte array, then write the bytes out to the file system. The simplest way I have found to do this is like this:
Using s As Stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(Project.ResourceName)
Dim bytes(s.Length) As Byte
s.Read(bytes, 0, bytes.Length)
File.WriteAllBytes(OutputFile, bytes)
End Using
With this method ResourceName must contain the file extension AND project name so using our example from above we can just do:
Using s As Stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(WindowsApplication1.test.exe)
Dim bytes(s.Length) As Byte
s.Read(bytes, 0, bytes.Length)
File.WriteAllBytes(“C:\test.exe”, bytes)
End Using
Text-based files are a little different:
Dim output As String
Using sr As StreamReader = New StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(WindowsApplication1.test.txt))
output = sr.ReadToEnd()
End Using
Using sw As StreamWriter = New StreamWriter(“C:\test.txt”)
sw.Write(output)
End Using
Having struggled with this in the past I hope this will help someone. And if you think you can explain factually why method 1 of embedding a resource bloats my compiled program to double its size, I would really appreciate it.
I assume that Method 1 is adding the files twice.
http://www.vbdotnetforums.com/vb-net-general-discussion/42670-visual-basic-net-2008-get-resource-file-io-stream.html#post121923
At least that is the conclusion of the thread above.
Quote:
You went to the Resources page of the project properties and added the files there, right? You then went into the Solution Explorer and change the Build Action of the files to Embedded Resource, right? That's why you were doubling the file size: you were adding each file twice.
There are two different ways to add resources: on the Resources page of the project properties and in the Solution Explorer. You do NOT do both. If you want to use GetManifestResourcestream then you do NOT use the Resources page. You add the files to the project in the Solution Explorer manually, then you set the Build Action to Embedded Resource.
In future, do one or the other, not both.
Add a file to the Resources page of the project properties and then access it via My.Resources. This will automatically add the file to the project in the Solution Explorer but the Build Action will be None and it should be left that way.
Add the file to the project in the Solution Explorer by using Add New Item or Add Existing Item. Set the Build Action of the file to Embedded Resource and then access the resource using GetManifestResourceStream.
Just an update for anyone who wants to use this code. The code actually writes one additional byte to the file due to zero-based declaration of the byte array.
To get an exact copy of the original file change the code to:
Using s As Stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(WindowsApplication1.test.exe)
Dim bytes(s.Length-1) As Byte
s.Read(bytes, 0, bytes.Length)
File.WriteAllBytes(“C:\test.exe”, bytes)
End Using