I have a class in my Silverlight app that (de-)serializes JSON strings to/from an object class.
I use WebClient.OpenReadAsync to get a file that contains this JSON string:
{"FirstName":"Bob","LastName":"Underwood"}
After calling OpenReadAsync however, the retrieved string has a lot of extra characters:
"PK\n\0\0\0\0\0�u�>h��5\0\0\05\0\0\0\t\0\0\0test.json\"{\\\"FirstName\\\":\\\"Gary\\\",\\\"LastName\\\":\\\"MacDonald\\\"}\"PK\0\n\0\0\0\0\0�u�>h��5\0\0\05\0\0\0\t\0\0\0\0\0\0\0\0\0 \0\0\0\0\0\0\0test.jsonPK\0\0\0\0\0\07\0\0\0\\\0\0\0\0\0"
This is the code I'm using to download the JSON:
WebClient client = new WebClient();
client.OpenReadCompleted += client_OpenReadCompleted;
client.OpenReadAsync(new Uri("/someJsonFile.zip", UriKind.Relative));
void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) {
if (e.Error == null) {
StreamReader reader = new StreamReader(e.Result);
string jsonString = reader.ReadToEnd().ToString();
}
else {
addMessage("Error " + e.Error.ToString());
}
}
jsonString ends up with all that extra data, so I can't deserialize it as is.
Another thing to note: the URI points to someJsonFile.zip, but it's really not zipped, when I give the file a extension like .json, or no extension, I get a error that it cannot find the file, but when I give it a extension like .zip, it finds it fine. Is there a way I can use a normal or no extension? I was wondering if this was a configuration issue.
Questions:
Am I doing something wrong in pulling this file and using StreamReader to get the string that's causing me to get all that trash data?
Do I need to do something specific to be able to use WebClient to grab a file with different extensions, like .json, or even no extension at all?
1 - That data stream certainly is a ZIP (PK is the old PKZip marker and the test.json filename is mentioned in its index as well).
Your server may be setup to serve all files compressed (or you may simply be accessing an actual zip file). Please check the server settings.
2 - As for the second question, the WebClient does not care about file types. It is just a stream of data that needs to be interpreted by something that knows what the data is (i.e. your code).
It is only the server that may be configured to serve up different files in different ways.
I was able to figure things out with my domain provider, appears to have been some configuration issues on their end.
Related
I've implemented a file upload in ASP.Net MVC. I've created a view model that received the uploaded file as an HttpPostedFileWrapper and within the controller action I can save the file to disk.
However, I want to perform the actual save in service method which is in a class library that doesn't implement System.Web. I can't therefore pass the HttpPostedFileWrapper object to the service method.
Does anyone know how to achieve this, either by receiving the file as a different object or converting it to something else prior to passing it. The only way I can think of is to read the content of the file into a MemoryStream, and pass this along with the other parameters such as filename individually, but just wondered if there was a better way?
Thanks
The best approach would probably be retrieving the image data (as a byte[]) and the name of the image (as a string) and passing those along to your service, similar to the approach you mentioned :
public void UploadFile(HttpPostedFileWrapper file)
{
// Ensure a file is present
if(file != null)
{
// Store the file data
byte[] data = null;
// Read the file data into an array
using (var reader = new BinaryReader(file.InputStream))
{
data = reader.ReadBytes(file.ContentLength);
}
// Call your service here, passing along the data and file name
UploadFileViaService(file.FileName, data);
}
}
Since a byte[] and a string are very basic primatives, you should have no problem passing them to another service. A Stream is likely to work as well, but they can be prone to issues like being closed, whereas a byte[] will already have all of your content.
I have this xml file: http://www.studiovincent.net/list.xml
I need copy whole content in other xml file.
I tryed this code:
string sourcefile = "http://www.studiovincent.net/list.xml";
string destinationfile = "test.xml";
System.IO.File.Copy(sourcefile, destinationfile);
But not work, because I get this error: URI formats are not supported.
How Can I solve this problem?
File.Copy() does not support the http:// protocol, hence the URI formats are not supported error.
You can work around this by reading in the contents of the page into a string, and then writing it to a file.
WebClient client = new WebClient();
string contents = client.DownloadString("http://www.studiovincent.net/list.xml");
// write contents to test.xml
System.IO.File.WriteAllText ("test.xml", contents);
Note that WriteAllText() will create test.xml if it doesn't exist, and overwrite it if it does. You will also want to wrap the above code in a try / catch block and catch and handle the appropriate excpetions.
I would recommend using WebClient.DownloadFile. Downloading a string and then saving it could cause problems with character set mapping.
WebClient client = new WebClient();
client.DownloadFile("http://www.studiovincent.net/list.xml", "test.xml");
This copies the file directly rather than converting the data to a string, which might do some string conversions (for example, the file is Unicode, and WebClient thinks it's UTF-8) and then copying to a file.
Please be gentle. I am not a terribly proficient developer!
So this is the last thing I need to fix in my Windows Phone 7.5 app before I consider it done. In short, the data sources on the menus are driven by an xml file. That file is stored locally with the app. I would like to store that file somewhere on the Internet). Currently if I need to make a change to this xml file, I have to re-submit the app to the Marketplace taking about 5 days before the change goes live. How 2003 of me.
So I can't figure out what they are expecting returned in the code below. I've hacked away and it always give some error I don't understand.
I've set the filename variable to a URL of a file on the Internet but apparently that is not supported. So I either need a new way for that whole section to work or a way to convert the hosted filename converted into something that will work.
private static void FirstLaunch()
{
// On the first launch, just add everything from the OPML file
string filename;
//This file should really be hosted on the Internet somewhere.
filename = "/RSSReader;component/LyncNews-opml.xml";
StreamResourceInfo xml = App.GetResourceStream(new Uri(filename, UriKind.Relative));
List<RSSPage> rssPages = ParseOPML(xml.Stream);
}
You can set it to a URL, but you'll need to download the content, not through App.GetResourceStream. Try WebClient, it's easy and simple.
A simple usage:
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Client_DownloadStringCompleted);
Uri token = new Uri("your url");
client.DownloadStringAsync(token);
and handle xml parsing in the event.
Okay so I want to download a file from a website, but the file is lacking an extension.
(it's an image file, I know this much, but the link does not provide the actual extension)
When I use webrequest, or webclient to download the file I get a "404 file not found" exception.
WebClient wc = new WebClient();
Stream strm = wc.DownloadFile("http://some_site.some_domain/some_image.","C:/some_directory/save_name.some_extention");
Notice the lack of extention at the end of the URL.
The site in question displays the image fine in a webbrowser, but when viewing just the image there is no extension and thus it's treated an unknown file (not showing an image).
So simply put: how do I download a file if there is no extention specified?
Thanks in advance!
So you're trying to determine what extension to give the file after downloading? If the URL doesn't have one you would have to inspect the actual data of the file.
You might be able to inspect the beginning of the file and see if it matches known valid file types. For instance, PNGs seem to have 'PNG' as bytes 2-4 (at least in the ones I've inspected). By looking at that data you should be able to determine the format with a fairly high accuracy.
This would be my best suggestion, if this doesn't work I don't know how to solve you problem...
List<string> fileExtensions = new List<string>(){"png","gif","bmp","jpg"}// other known image file extensions here...
WebClient wc = new WebClient();
foreach(var extension in fileExtensions)
{
try
{ wc.DownloadFile("http://some_site.some_domain/some_image."+extension,"C:/some_directory/save_name."+extension);
break;
}
catch {}
}
This would just be a work around, I guess... Not a real solution...
I have a text file with a list of 300,000 words and the frequency with wich they occur. Each line is in the format Word:FequencyOfOccurence.
I want this information to be accessible from within the C# code. I can't hard code the list since it is too long, and I'm not sure how to go about accessing it from a file on the server. Ideally I'd ideally like the information to be downloaded only if it's used (To save on bandwidth) but this is not a high priority as the file is not too big and internet speeds are always increasing.
It doesn't need to be useable for binding.
The information does not need to be editable once the project has been built.
Here is another alternative. Zip the file up and stick it in the clientBin folder next to the apllication XAP. Then at the point in the app where the content is needed do something like this:-
public void GetWordFrequencyResource(Action<string> callback)
{
WebClient client = new WebClient();
client.OpenReadAsync += (s, args) =>
{
try
{
var zipRes = new StreamResourceInfo(args.Result, null)
var txtRes = Application.GetResourceStream(zipRes, new Uri("WordFrequency.txt", UriKind.Relative));
string result = new StreamReader(txtRes.Stream).ReadToEnd();
callback(result);
}
catch
{
callback(null); //Fetch failed.
}
}
client.OpenReadAsync(new Uri("WordFrequency.zip", UriKind.Relative"));
}
Usage:-
var wordFrequency = new Dictionary<string, int>();
GetWordFrequencyResource(s =>
{
// Code here to burst string into dictionary.
});
// Note code here is asynchronous with the building of the dictionary don't attempt to
// use the dictionary here.
The above code allows you to store the file in an efficient zip format but not in the XAP itself. Hence you can download it on demand. It makes use of the fact that a XAP is a zip file so Application.GetResourceStream which is designed to pull resources from XAP files can be used on a zip file.
BTW, I'm not actually suggesting you use a dictionary, I'm just using a dictionary as simple example. In reality I would imagine the file is in sorted order. If that is the case you could use a KeyValuePair<string, int> for each entry but create a custom collection type that holds them in an array or List and then use some Binary search methods to index into it.
Based on your comments, you could download the word list file if you are required to have a very thin server layer. The XAP file containing your Silverlight application is nothing more than a ZIP file with all the referenced files for your Silverlight client layer. Try adding the word list as content that gets compiled into the XAP and see how big the file gets. Text usually compresses really well. In general, though, you'll want to be friendly with your users in how much memory your application consumes. Loading a huge text file into memory, in addition to everything else you need in your app, may untimately make your app a resource hog.
A better practice, in general, would be to call a web service. The service could would perform whatever look up logic you need. Here's a blog post from a quick search that should get you started: (This was written for SL2, but should apply the same for SL3.)
Calling web services with Silverlight 2
Even better would be to store your list in a SQL Server. It will be much easier and quicker to query.
You could create a WCF service on the server side that will send the data to the Silverlight application. Once you retrieve the information you could cache it in-memory inside the client. Here's an example of calling a WCF service method from Silverlight.
Another possibility is to embed the text file into the Silverlight assembly that is deployed to the client:
using (var stream = Assembly.GetExecutingAssembly()
.GetManifestResourceStream("namespace.data.txt"))
using (var reader = new StreamReader(stream))
{
string data = reader.ReadToEnd();
// Do something with the data
}