I changed the name of my project and when I run it it runs fine but when it reaches the part where it does validation from json I get the following error:
Cannot find embedded resource: hot.json
but when I change the name back to the original name the error goes away. I have tried deleting the old one and then added another json file with different name and I still got the same error.
here is where the error is occurring in my code:
var assembly = Assembly.GetExecutingAssembly();
using (
var stream =
assembly.GetManifestResourceStream(
$"HotStuff.TestResources.Languages.{language}.json"))
{
if (stream == null)
throw new InvalidOperationException($"Cannot find embedded resource: {language}.json");
using (var reader = new StreamReader(stream))
{
var json = JObject.Parse(reader.ReadToEnd()).ToObject<JToken>();
var value = json.SelectToken(key.Replace(" ", "-"));
return value?.ToString() ?? string.Empty;
}
}
Related
I want to write my current state of a game into a JSON file so that once the user comes back they can either resume or start new. I'm creating a hello world to take user input, store it in JSON and load it back in.
I currently can load JsonObject very quickly using this method
public JObject GetJsonData(string jsonFileName, string dirNameJsonLivesIn)
{
if (string.IsNullOrEmpty(jsonFileName))
throw new ArgumentNullException(jsonFileName);
var assembly = typeof(MainPage).GetTypeInfo().Assembly;
var defaultPath = $"{assembly.GetName().Name}.{jsonFileName}";
var extendedPath = $"{assembly.GetName().Name}.{dirNameJsonLivesIn}.{jsonFileName}";
if (string.IsNullOrEmpty(dirNameJsonLivesIn))
extendedPath = defaultPath;
Stream stream = assembly.GetManifestResourceStream(extendedPath);
using (var reader = new StreamReader(stream))
{
var jsonString = reader.ReadToEnd();
return JObject.Parse(jsonString);
}
}
With this method, I can access objects with ["strings"] just like python does very easily and painlessly.
Problem accures when I try to write to the file. I get an error Access denied... I have given permission on the manifest for Write_External_Files or something along the line. Still get the same error. I've also done some research and there has been a few line of code which people recommended to add to the MainActivity.cs but that didn't work either.
Using this method to write file
private void StoreData_Clicked(object sender, EventArgs e)
{
var jsonFileName = "Statefile.json";
var text = entryBox.Text;
var state = new Dictionary<string, string>();
var assembly = typeof(MainPage).GetTypeInfo().Assembly;
var defaultPath = $"{assembly.GetName().Name}.{jsonFileName}";
state.Add("CurrentState", text);
var json = JsonConvert.SerializeObject(state, Formatting.Indented);
File.WriteAllText(defaultPath, json);
}
Could someone explain why this is happening? Why do I have the ability to read the external_resources but not write to them? Oh yeah, I have set my properties to Embedded Resource and also Always Copy.
Update - Error
System.UnauthorizedAccessException
Message=Access to the path "/HelloWorldXamarin.Statefile.json" is denied.
I use stream reader to read sql data. Although resourceName is correct and the resource Build Action property is Embedded Resource it still throws following error on StreamReader:
System.ArgumentNullException: Value cannot be null.
var namespace1 = typeof(Toolbox).Namespace;
var name1 = name.Replace('\\', '.');
string resourceName = $"{typeof(Toolbox).Namespace}.{name1}";
//Innosys.Ap.GetCurrentTimeKey.sql
using (Stream manifestResourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)
)
{
using (StreamReader streamReader = new StreamReader(manifestResourceStream))
return streamReader.ReadToEnd();
}
Following are my debugging results so far.
namespace1 returns the correct name space used for the class from the project i.e. The class from which I call streamReader, resource file.
name1 returns resource file name with extension. ie. myquery.sql
resourcename which basically combines the path and the file name returns from my point of view the correct resouce address. i.e. myNamespace.myquery.sql
I'm trying to read a simple text file using reflection just as a learning case. I'm not getting an error, but I'm also not getting the desired result of "hello world". The variable stream is coming back null.
string output = "";
var asm = Assembly.GetExecutingAssembly();
using (var stream = asm.GetManifestResourceStream("ConsoleApp1.data1.txt"))
{
if (stream != null)
{
var reader = new StreamReader(stream);
output = reader.ReadToEnd();
Console.WriteLine(output);
}
}
You're reading from a manifest resource, which means the text file needs to be embedded in the dll. Right click on the file and choose Properties, then set the Build Action to "Embedded Resource".
I'll explain the problem right away, but first of all...is this achievable?
I have a Document Type in Umbraco where I store data from a Form. I can store everything except the file.
...
content.SetValue("notes", item.Notes);
content.SetValue("curriculum", item.Curriculum); /*this is the file*/
...
I'm adding items like this where SetValue comes from the following namespace namespace Umbraco.Core.Models and this is the function signature void SetValue(string propertyTypeAlias, object value)
And the return error is the following
"String or binary data would be truncated.
↵The statement has been terminated."
Did I missunderstood something? Shouldn't I be sending the base64? I'm adding the image to a media file where it creates a sub-folder with a sequential number. If I try to add an existing folder it appends the file just fine but if I point to a new media sub-folder it also returns an error. Any ideas on how should I approach this?
Thanks in advance
Edit 1: After Cryothic answer I've updated my code with the following
byte[] tempByte = Convert.FromBase64String(item.Curriculum);
var mediaFile = _mediaService.CreateMedia(item.cvExtension, -1, Constants.Conventions.MediaTypes.File);
Stream fileStream = new MemoryStream(tempByte);
var fileName = Path.GetFileNameWithoutExtension(item.cvExtension);
mediaFile.SetValue("umbracoFile", fileName, fileStream);
_mediaService.Save(mediaFile);
and the error happens at mediaFile.SetValue(...).
If I upload a file from umbraco it goes to "http://localhost:3295/media/1679/test.txt" and the next one would go to "http://localhost:3295/media/1680/test.txt". Where do I tell on my request that it has to add to the /media folder and increment? Do I only point to the media folder and umbaco handles the incrementation part?
If I change on SetValue to the following mediaFile.SetValue("curriculum", fileName, fileStream); the request succeeds but the file is not added to the content itself and the file is added to "http://localhost:3295/umbraco/media" instead of "http://localhost:3295/media".
If I try the following - content.SetValue("curriculum", item.cvExtension); - the file is added to the content but with the path "http://localhost:3295/umbraco/test.txt".
I'm not understanding very well how umbraco inserts files into the media folder (outside umbraco) and how you add the media service path to the content service.
Do you need to save base64?
I have done something like that, but using the MediaService.
My project had the option to upload multiple images on mulitple wizard-steps, and I needed to save them all at once. So I looped through the uploaded files (HttpFileCollection) per step. acceptedFiletypes is a string-list with the mimetypes I'd allow.
for (int i = 0; i < files.Count; i++) {
byte[] fileData = null;
UploadedFile uf = null;
try {
if (acceptedFiletypes.Contains(files[i].ContentType)) {
using (var binaryReader = new BinaryReader(files[i].InputStream)) {
fileData = binaryReader.ReadBytes(files[i].ContentLength);
}
if (fileData.Length > 0) {
uf = new UploadedFile {
FileName = files[i].FileName,
FileType = fileType,
FileData = fileData
};
}
}
}
catch { }
if (uf != null) {
projectData.UploadedFiles.Add(uf);
}
}
After the last step, I would loop throug my projectData.UploadedFiles and do the following.
var service = Umbraco.Core.ApplicationContext.Current.Services.MediaService;
var mediaTypeAlias = "Image";
var mediaItem = service.CreateMedia(fileName, parentFolderID, mediaTypeAlias);
Stream fileStream = new MemoryStream(file.FileData);
mediaItem.SetValue("umbracoFile", fileName, fileStream);
service.Save(mediaItem);
I also had a check which would see if the uploaded filename was ending on ".pdf". In that case I'd change the mediaTypeAlias to "File".
I hope this helps.
I am using xamrin.forms, and I am trying to access file and read it.
I have lastusername.txt as text file and I set the build action for it as "Content", actually I am trying to read file as the following:
var filename = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "lastusername.txt");
if (filename != null)
return System.IO.File.ReadAllText(filename);//error occurred here
else
return "";
I get the following Error:
System.IO.FileNotFoundException: Could not find file
Place your file within the Android Assets folder and assign it with a build type of "AndroidAsset".
Since your app's assets are read-only, you can then read it via the AssetManager, saving (copy) it somewhere else if it does not exist (i.e. the first time the app is run):
var fileName = "MyAssetBasedFile.txt";
if (!File.Exists(Path.Combine(CacheDir.Path, fileName)))
{
AssetManager assets = this.Assets;
using (StreamReader sr = new StreamReader(assets.Open(fileName)))
using (StreamWriter sw = new StreamWriter(Path.Combine(CacheDir.Path, fileName), append: false))
sw.Write(sr.ReadToEnd());
}
string content;
using (StreamReader sr = new StreamReader(Path.Combine(CacheDir.Path, fileName)))
{
content = sr.ReadToEnd();
}
Log.Debug("SO", content);
The next time the app runs you will pick up the one in your cache dir.