I'm trying to write and read to local storage for Win8. Using a helper I am able to successfully write to my machine, but reading the .xml file gives me a: System.UnauthorizedAccessException occurred in mscorlib.dll error
I created a codepaste so you can see my code.
http://codepaste.net/k9mht5
The code is failing here:
public async static Task<object> LoadData(string path, System.Type type)
{
var _Folder = Windows.Storage.ApplicationData.Current.LocalFolder;
try
{
var _File = await Folder.GetFileAsync(path);
using (IInputStream inStream = await _File.OpenSequentialReadAsync())
{
// Deserialize the Session State
XmlSerializer x = new XmlSerializer(type);
return x.Deserialize(inStream.AsStreamForRead());
}
}
catch (Exception ex)
{
MessageDialog dialog = new MessageDialog(ex.Message.ToString());
dialog.ShowAsync();
return null;
}
}
Specifically on this line:
using (IInputStream inStream = await _File.OpenSequentialReadAsync())
If you have any ideas on what I am doing incorrectly it would help me out a lot.
I am doing this in Release Preview. If there is any other system information I need to give, please let me know.
Ok, here is what I've noticed. In file vehicleViewModel.cs you call SaveList(); and GetList(); one after another. Both of these methods are declared as async void which means fire and forget. My idea is that while SaveList is trying to save, GetList is trying to read one file at the same time. I tried your code and I got the same error too. Try to change SaveList and GetList methods to be async Task and then use await:
await SaveList();
await GetList();
That did the trick for me.
Use the dispatcher it will solve your problem
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
{
// Your UI update code goes here!
_dialogService.ShowMessage(rdm.ErrorMessage);
});
Related
I have been pulling my hair out with this one.
I have a very simple test class that throws this error:
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
System.Text.Json.JsonException: A possible object cycle was detected. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32. Consider using ReferenceHandler.Preserve on JsonSerializerOptions to support cycles.
It doesn't seem to break much, as the put request is successful and the serialize is also successful.
EDIT
I have chased the serialize exception out if it was ever really there. I am starting to think it is a problem with typed HttpClient. It throws the exception that comes out on the console and in the response on Postman. However, it doesn't allow me to catch the exception in the code and the PUT call works. So the exception is happening after the PUT request and is handled before it returns control to my app.
I am going to try to use a standard HttpClientFactor instead of a typed client and see if that works. I know that the JSON exception is a red herring, but it is ugly and breaking the response.
Any suggestions would be welcome.
public virtual async Task<CouchResponse> Create(string id, string db, TObj info)
{
CouchResponse ret = new() { Reason = "Unknown and unExpected error", Ok = false };
HttpResponseMessage rc = null;
if (id is null)
{
return new CouchResponse() { Id = "missing", Ok = false, Rev = "missing" };
}
string url = $"{db}/1";
try
{
// login to Couchdb servwer
await CouchLogin();
try
{
//var jsonInfo = JsonUtils.Serialize<TestJson>(jTest);
var jsonInfo = JsonSerializer.Serialize<TObj>(info, options);
HttpContent content = new StringContent(jsonInfo, Encoding.UTF8,
"application/json");
rc = await client.PutAsync(url, content);
}
catch (Exception eNewton)
{
Console.WriteLine($"Json Exception: {eNewton.Message}");
}
if (rc is not null)
{
var str = await rc.Content.ReadAsStringAsync();
var ret = JsonSerializer.Deserialize<CouchResponse>(str,options);
rc.EnsureSuccessStatusCode();
}
return ret;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
//return ret;
}
return ret;
}
Suggestions?
What a crazy bug. The diagnostic was very missing leading. Everything I was doing in the create method was correct.
What is missed was an await when I called the create method. This made it appear that the sendAsync was having the issue when it was really the controller trying to format the task return as a response. This caused the stack trace in the response message. Thanks for all the help.
Change this
var jsonSerializerSettings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
NullValueHandling = NullValueHandling.Ignore
};
To this
var jsonSerializerSettings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
NullValueHandling = NullValueHandling.Ignore,
MaxDepth = null,
};
I have a strange problem that I don't know why is giving problems:
On client, I have this code:
HttpResponseMessage response = await _httpClient.PostAsync("http://127.0.0.1:5544/api/Blablabla", new StringContent("test"));
On server, I have implemented a custom InputFormatter that have this
public async override Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
{
var request = context.HttpContext.Request;
try
{
using (var reader = new StreamReader(request.Body))
{
var content = await reader.ReadToEndAsync().ConfigureAwait(false);
return await InputFormatterResult.SuccessAsync(content).ConfigureAwait(false);
}
}
catch (Exception e)
{
return await InputFormatterResult.FailureAsync();
}
}
If I try this, the catch exception of the server is fired, giving me an exception of:
An existing connection was forcibly closed by the remote host
But.....
If in the client I make the PostAsync "sync" doing this:
HttpResponseMessage response = _httpClient.PostAsync("http://127.0.0.1:5544/api/Blablabla", new StringContent("test")).Result;
Everything works ok.
What's the problem???
Ok, I fixed it...
The problem was, as you can imagine, that the function that called postasync was async, but the one before was not, and I did not make a .Wait() to that one.
Was nothing related to asp net core, just a problem of async code from sync code.
This method connect given path which has to be xml file and save xml file to somewhere in server. Finally, download xml file from server by calling _downloadFileFromServer method
public async Task SaveFiletoServer(int id, string nud_preparationValue, int nud_divideNumber, string saveConfigPath, string saveConfigName)
{
try
{
await tryToConnect(id, nud_preparationValue, nud_divideNumber);
ReadXml.Save(XDocument,saveConfigPath,saveConfigName, nud_divideNumber);
await _downloadFileFromServer(saveConfigPath, saveConfigName);
}
catch (System.Exception ex)
{
ViewBag.DownloadError = ex.Message;
}
}
this method is using by above method(Download xml file from server).
private async Task _downloadFileFromServer(string saveConfigPath, string saveConfigName)
{
var memory = new MemoryStream();
using (var stream = new FileStream(string.Concat(saveConfigPath,saveConfigName,".xml"), FileMode.Open))
{
stream.CopyTo(memory);
}
memory.Position = 0;
await Task.FromResult(File(memory, "application/xml",string.Concat(saveConfigName,".xml")));
}
If I directly call _downloadFileFromServer method, it works correctly.xml file is downloading. However, when I call SaveFiletoServer method, _downloadFileFromServer method doesn't work correctly. Xml file is not downloading. I don't understand what is wrong.
Problem solved by using html.actionlink instead of ajax in order to download xml file with SaveFiletoServer method
I am using TweetSharp in a Windows Phone project and no matter what I do, I can't post a tweet with media.
I am getting the exception 195: Missing or invalid parameter.
I read that usually this can be a cause of invalid data, like the stream that I provide is invalid.
I have tried other way but nothing works , I get the same exception ...
The sharing code, simplified is like this:
MediaLibrary library = new MediaLibrary();
var picture = library.Pictures[0];
var options = new SendTweetWithMediaOptions
{
Images = new Dictionary<string, Stream> { { picture.Name, picture.GetImage() } },
Status = TweetTextBox.Text,
};
AutentificateTwitterService().SendTweetWithMedia(options, (status, response) =>
_dispatcher.BeginInvoke(() =>
{
DonePosting();
if (response.StatusCode == HttpStatusCode.OK)
{
_lastPostId = status.Id;
}
else
{
MessageBox.Show(String.Format(
"There was an error sending image to Twitter{0}{1}",
Environment.NewLine,
response.Error));
}
}));
I tried sharing with linqtotwitter and worked but TweetSharp is more appropriate for my project.
Finally after some time I've found the problem to this and I am sure to other more WP and SendTweetWithMediaOptions related problems.
The thing is that if you dig into SendTweetWithMedia the way it is now you will get to TwitterService.cs where WithHammock will be called, is just the images are not passed as parrameters, so they get lost right there :)
I did fix this passing the parameters and adding
private void WithHammock<T>(WebMethod method, Action<T, TwitterResponse> action, string path, IDictionary<string, Stream> files, params object[] segments) where T : class
{
var url = ResolveUrlSegments(path, segments.ToList());
var request = PrepareHammockQuery(url);
request.Method = method;
request.QueryHandling = QueryHandling.AppendToParameters;
foreach (var file in files)
{
request.AddFile("media[]", file.Key, file.Value);
}
WithHammockImpl(request, action);
}
I will try and see if I can Pull this so that everyone else can have this fix.
Hope this helps.
I've got a text file that ships with my app and I want to display its contents on the screen. Anyone know how to do that? The usual file IO doesn't seem to work for Metro.
Thanks
Not sure what you've tried, but check this out:
http://msdn.microsoft.com/en-us/library/windows/apps/windows.applicationmodel.package.installedlocation.aspx
With the StorageFolder in hand, you have the whole set of functions to read/write files.
In my app I am reading a XML file that comes with the app, you can tweak it to read any type of file
public class LocalStorage
{
private const string SyndicationFeedCategoriesFileName = "FeedCategories.xml";
private StorageFile _storageFile;
private StorageFolder _storageFolder;
public async Task<XmlDocument> Read_categories_from_disk()
{
try
{
_storageFolder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("Xml");
_storageFile = await _storageFolder.GetFileAsync(SyndicationFeedCategoriesFileName);
var loadSettings = new XmlLoadSettings
{ProhibitDtd = false, ResolveExternals = false};
return await XmlDocument.LoadFromFileAsync(_storageFile, loadSettings);
}
catch (Exception)
{
return null;
}
}
}
View the full source code here http://metrorssreader.codeplex.com/SourceControl/changeset/view/18233#263004
Hope that helps