Not a valid resource name of assembly - xamarin

I'm using Xamarin Studio and GTK#(.NET). I have the following problem:
I've made an app, and I need to(dinamically) download web images(favicons) and display them in a Gtk.Image widget. When I try to do this, I get the following error:
System.ArgumentException: 'myfile.ico' is not a valid resource name of assembly 'myApp, Version=1.0.6742.24722, Culture=neutral, PublicKeyToken=null'.
at at Gdk.PixbufLoader.InitFromAssemblyResource(Assembly assembly, String resource)
at at Gdk.PixbufLoader..ctor(Assembly assembly, String resource)
at at Gdk.Pixbuf..ctor(Assembly assembly, String resource)
at at Gdk.Pixbuf.LoadFromResource(String resource)
It works if i add the favicon, after download,in the resource folder, BUT I need to make this dinamically(if I add a new site, I want to see it's icon there..).
The code:
using (WebClient client = new WebClient())
{
client.DownloadFile(new Uri("https://google.com/favicon.ico",
Directory.GetCurrentDirectory() + "\..\..\Res\google.ico");
}
faviconImage.Pixbuf = Gdk.Pixbuf.LoadFromResource("myApp.Res.myfile.ico");
The image is in the folder(i can see it, it's everything ok) but i cannot use it if i don't include it(manually) in the resource folder....
Please help me :'(

Pixbuf.LoadFromResource only loads image data from an embedded assembly resource. You can not add resources to assemblies after they are created.
To create a Pixbuf from a file, use one the its .ator that supports either a file path to the image or one that uses a file stream.
Something like:
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "myDownloadIcon.ico");
var newPixBuf = new PixBuf(filePath):
faviconImage.Pixbuf = newPixBuf;

Related

Add a text file as a resource in Visual Studio 2022

I am creating a WebView2 app (WPF using C#) and I want to have a index.html file as a resource.
The idea is that when I create a project, a new folder is created.
This folder will contain an index.html file for the WebView control to load.
The index.html file then points to project specific data as relative paths.
I would like to have a file embedded in my resources that I can use at runtime like this
`void newProject()
{
string strHTML = /** code to read from resource file **/
createFile(projDir + "\\index.html") /** code to create a new file **/
/** code to write strHTML string to new index.html file **/
}
`
I know I can create a static string to do this, but editing is easier if I have the resource as a file.
Thanks in advance.
D
Update:
I put the file into the resources. Then, I added this code
var assem = Assembly.GetExecutingAssembly();
String[] resources = assem.GetManifestResourceNames();
html = assem.GetManifestResourceStream("index.html")
The resources string array always has two elements regardless of what I have in my resources file.
"WebView2Testing.g.resources"
"WebView2Testing.Properties.Resources.resources"
which has nothing to do with my file.
GetManifestResourceStream("index.html") returns null.
FYI I am using .net6 and WPF Windows app.
Any more ideas?

How to access file stored in shared project in Xamarin Forms?

I have a folder called Documentation inside the shared project, named App2 in this case. How do I access the files stored inside the Documentation folder? Attached image below shows the project structure.
Visual Studio Solution Page
I have tried out following commands but they aren't working :
System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
AppDomain.CurrentDomain.BaseDirectory
System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
If it's troublesome to access the file in that folder, I'm open to hearing other alternatives.
This is how I have done it for JSON files in my shared project (using PCL). As Jason pointed out in the comments, if you are using .NET Standard, you can simply define the GetSharedFile method in your shared project instead of creating platform specific references.
Add the file to the shared project and set it as Embedded Resource
Create an IFileHelper interface in your shared project
public interface IFileHelper {
Stream GetSharedFile(string fileResourceName);
}
Create a new FileHelper class in each project (Android and iOS) with the following
public class FileHelper : IFileHelper {
public Stream GetSharedFile(string fileResourceName) {
Type type = typeof(IFileHelper); // We could use any type here, just needs to be something in your shared project so we get the correct Assembly below
return type.Assembly.GetManifestResourceStream(fileResourceName);
}
}
Add a documentation handler class in your shared project. Something like below (make sure to change the App namespace to match yours):
public class Documentation {
private const string ResourcePath = "App.Documentation.index.html"; // App would be your application's namespace, you may need to play with the Documentation path part to get it working
public string GetDocs() {
IFileHelper helper = DependencyService.Get<IFileHelper>(); // Your platform specific helper will be filled in here
Stream stream = helper.GetSharedFile(ResourcePath);
using (stream)
using (StreamReader reader = new StreamReader(stream)) {
return reader.ReadToEnd(); // This should be the file contents, you could serialize/process it further
}
}
}
I wrote this mostly by hand so let me know if something is not working. If you cannot load your file, I suggest trying to put it into the root of your shared project and then changing ResourcePath in the code above to the following (again using your app's namespace instead of App):
private const string ResourcePath = "App.index.html";

Rotativa component throws error Could not load file or assembly 'System.Web.Mvc, Version=3.0.0.1 while generating the pdf in MVC project

I have used this component to generate a pdf document based out of a dynamic view content. On testing at DEV and Staging environment, it worked fine and on Production environment, it throws below shown error.
Could not load file or assembly 'System.Web.Mvc, Version=3.0.0.1, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
Rotativa Version: 1.0.0.0
System.Web.Mvc Version: 5.2.3.0
I have given the binding redirect in web.config as below.
bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0"
Code:
var pdfLetter = new Rotativa.ViewAsPdf(viewName, viewModel);
pdfLetter.FileName = fileName;
pdfLetter.PageSize = Rotativa.Options.Size.A4;
pdfLetter.PageOrientation = Rotativa.Options.Orientation.Portrait;
pdfLetter.PageMargins = new Rotativa.Options.Margins { Left = 4, Right = 1 };
var letterBytes = pdfLetter.BuildPdf(ControllerContext);
return letterBytes;
Web Application is not referencing the 3.0.0.1 version anywhere and still it throws the error. Tried to check the available Stack Overflow threads to fix.
Does anyone encountered this same problem and have any workaround to fix?
There was config value mismatch for MVC redirect between two environments and system was not able to recognize it. Fixed the issue by creating the web.config redirect section from the scratch.

How to decode a bitmap from a local file deployed with Android application

I am going through http://developer.xamarin.com/guides/cross-platform/xamarin-forms/working-with/images/
and trying to get the Local Images working with Android however I am experiencing some issues when attempting to do something in normal monodroid just as a further test. I'm using a SharedProject, just for reference.
I have added the test image at Resources/drawable (test1.png), and also setting the Build Action as AndroidResource as it describes, and if I do the following in Xamarin.Forms it works:-
Xamarin.Forms.Image myimage = new Image();
myimage.Source = ImageSource.FromFile("test1.png");
However, if I try and retrieve the same file via the following it comes back as null.
Android.Graphics.Bitmap objBitmapImage = Android.Graphics.BitmapFactory.DecodeFile("test1.png")
Does anyone know why this is null and how to correct?
The Xamarin.Forms FileImageSource has a fallback mode as it covers two different scenarios.
First it will check whether the file exists in the file system via the BitmapFactory.DecodeFile.
Should the file not exist as specified in the File property, then it will use BitmapFactory.DecodeResource to try and load the resource content as a secondary alternative.
FileImageSource for Android therefore isn't only just for files that exist in the file system but also for retrieving named resources also.
This link indicates that Android Resources are compiled into the application and therefore wouldn't be part of the file system as physical files.
Since test1.png is a Drawable you should use BitmapFactory.DecodeResource ()
string scr = "#drawable/test1.png";
ImageView iv = new ImageView(context);
Bitmap bm = BitmapFactory.DecodeFile(src);
if (bm != null)
iv.SetImageBitmap(bm);

How to read Asset Files using VS & Monodroid

I've been trying to implement this example using C# and Monodroid, but am having difficulties reading and writing an Asset file:
http://docs.xamarin.com/android/advanced_topics/using_android_assets
I am using the emulator, not a device.
First of all, I am having trouble finding the namespace for Assets.Open. What I ultimately found was
const string lfn = MyAssetFile.txt;
System.IO.StreamReader(Android.Content.Res.Resources.System.Assets.Open(lfn);
Is this the correct namespace?
Second of all, my Asset file is marked as AndroidAsset and "Copy Always" in the VS "Properties" pane, but my attempts to read the file always fail (File Not Found) using this statement:
string settings = "";
using (StreamReader sr = new System.IO.StreamReader (Android.Content.Res.Resources.System.Assets.Open(lfn))) settings = sr.ReadToEnd();
Do I have my VS settings wrong so that the asset file not being copied onto the emulator, or is it being copied OK but my code to open/read it is wrong?
You must use:
const string lfn = "MyAssetFile.txt";
string settings = string.Empty;
// context could be ApplicationContext, Activity or
// any other object of type Context
using (var input = context.Assets.Open(lfn))
using (StreamReader sr = new System.IO.StreamReader(input))
{
settings = sr.ReadToEnd();
}
If I remember correctly, as I haven't got an IDE at the moment, Android.Content.Res.Resources.System.Assets references the Android assets not your project assets. You want to use your projects assets so you need to use the AssetManager from your Activities or Contexts.
For example: the Activity class has a property called Assets. This is what you use. OR you use a View's Context.Assets property.
Or just simply add at the top:
using System.IO;
and it will work.
Xamarin team forget sometimes to mention using stuff.

Resources