Read ashx jpg with .Net 4.5 - c#

My goal is to read a jpg file from a ashx Url. I would like to do this with Windows Phone 8 but I'm starting with .Net 4.5 because that might be more simple for me.
Here is an example url:
http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=239959&type=card
If you go to this Url in IE 10 you'll see an image. How do I download the image in .Net 4.5? I have tried using:
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("image/jpg"));
string resourceAddress = "http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=239959&type=card";
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, resourceAddress);
HttpResponseMessage response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseContentRead);
byte[] responseBytes = await response.Content.ReadAsByteArrayAsync();
and also using WebClient
string url = #"http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=220041&type=card";
byte[] imageData;
using (WebClient client = new WebClient())
{
imageData = client.DownloadData(new Uri(url));
}
both of these methods return no data. How do I get the data and format it into a jpg? I am pretty new to using ashx files. I see that they are used easily in Asp.Net web sites but have not been able to find anything that allows to simply download the file. The goal is to download the jpg file and display it in a windows phone 8 application.

Take a look at that URL. You've URL encoded the &, so indeed there's nothing returned from
http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=220041&type=card
this
http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=220041&type=card
however, worked just fine for me in Windows 8 using your first code sample.
By the way, I see you set an Accept header of image/jpg, the ASHX seems to set the Content-type to image/jpeg - it does work though.

Related

Using HttpClient to post large MultipartFormDataContent to IIS server web page

I am trying to upload up to 2GB of data using a HttpClient.
The data is sent through the request body into an aspx page where it is read (horrible, I know but I cannot change this.)
The data is placed in a MultipartFormDataContent and posted like this:
var apiRequest = new MultipartFormDataContent();
apiRequest.Add(new StreamContent(file), fileName, fileName);
apiRequest.Headers.ContentDisposition =
new ContentDispositionHeaderValue("form-data") { Name = fileName, FileName = fileName };
HttpClient client = new HttpClient();
client.Timeout = TimeSpan.FromMinutes(30);
HttpResponseMessage response = null;
try
{
response = client.PostAsync(apiEndPoint, form).Result;
response.EnsureSuccessStatusCode();
string responseBody = response.Content.ReadAsStringAsync().Result;
}
catch (HttpRequestException e)
{
log.LogError($"logging here");
}
Things I have tried :
-HttpClient http version 1.0 instead of default
-HttpClient MaxRequestContentBufferSize
-web.config maxAllowedContentLength
-web.config AspMaxRequestEntityAllowed
-web.config maxRequestLength
Currently, the files get added to the httpClient correctly but I cannot get them to post to the web app. I got up to 900MB through but anything over that simply redirects to the main page and I get HTML from the web app in the response body.
Thanks in advance!
After a lot of hair pulling we found the solution by looking at the IIS logs.
The logs revealed that the Microsoft URLScan tool was blocking the requests.
When the request body was not approved by the scan, IIS would redirect you straight to the main page with no error.
You have to configure a max request length in the urlscan.ini file.
More info here: https://ajaxuploader.com/large-file-upload-iis-debug.htm
The file is located at C:\WINDOWS\system32\inetsrv\urlscan

Http GET method returns file's content with wrong encoding

I have a simple GET request that returns .txt file's content. You can try it out using a browser or fiddler: http://134.17.24.10:8054/Documents/13f37b0c-4b04-42e1-a86b-3658a67770da/1.txt
The encoding of this file is cp-1251. When I try to get it, I see smth like this:
response text view
How can I modify HttpRequest in C# to get the text in the encoding that I want? Or just return only bytes in order to convert them manually. Is it possible with HttpClient?
Another attachment:
If you can't change the charset sent by the server, yes, you can still just request the bytes and then choose which encoding to apply:
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
using (var httpClient = new HttpClient())
{
var response = await httpClient.GetByteArrayAsync(RequestUrl);
var responseString = Encoding.GetEncoding("windows-1251").GetString(response, 0, response.Length - 1);
Console.WriteLine(responseString);
}
References:
How to change the encoding of the HttpClient response
Encoding.GetEncoding can't work in UWP app
The .NET Framework Class Library provides one static property, CodePagesEncodingProvider.Instance, that returns an EncodingProvider object that makes the full set of encodings available on the desktop .NET Framework Class Library available to .NET Core applications.
https://learn.microsoft.com/en-us/dotnet/api/system.text.encodingprovider?redirectedfrom=MSDN&view=netcore-3.1

Windows 8.1 Runtime (C#) - Convert HttpResponseMessage content to BitmapImage

I am adding features to a Windows Phone 8.1 RT app, built using MVVM. I need to be able to download an Image to the device and save/ display it. I can already do this with images from a fixed URL.
We have an accompanying website and API to go with the app. The way it works is the app sends a request to the API to get a download code for the image in question, and then sends this code along with the ID of the document in a request to the website, which verifies the user has access to the document and should then serve up the image if successful. The API and website are already in use with the iOS and Android equivalents of the app, so I know they work.
To retrieve the image, I'm trying to use HttpClient. This is my current code, which is getting a response from the server, with some content and the filename of the image (which look to be correct):
Uri uri = new Uri("<website address>");
Dictionary<string, string> pairs = new Dictionary<string, string>();
pairs.Add("RequestToken", response.DownloadToken);
pairs.Add("DocumentID", "<doc ID>");
HttpFormUrlEncodedContent formContent = new HttpFormUrlEncodedContent(pairs);
HttpClient client = new HttpClient();
HttpResponseMessage response2 = await client.PostAsync(uri, formContent);
var imageContent = response2.Content.ReadAsInputStreamAsync();
I'm trying to write the content to a stream, then convert that to a BitmapImage object, which I can then save to the device and display to the user. It's the conversion I'm struggling with. My plan is to convert the InputStream to a bytearray, then convert that to a Bitmap. The problem is, I can't find any extension methods in 8.1 which will do this, and very little in the way of documentation to help.
Can anyone point me in the right direction here? Maybe there's a better way of doing a conversion from HttpResponseMessage.Content to BitmapImage?
Make sure you are importing the right HttpClient:
using Windows.Web.Http;
And import other necessary namespaces:
using Windows.Storage.Streams;
using Windows.UI.Xaml.Media.Imaging;
Then, as you wrote in your qurestion, get the IInputStream, but make sure to use await with ReadAsInputStreamAsync():
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.PostAsync(uri, formContent);
// Do not forget to use an 'await'.
IInputStream imageStream = await response.Content.ReadAsInputStreamAsync();
Then, copy the IInputStream into an IRandomAccessStream:
InMemoryRandomAccessStream randomAccessStream =
new InMemoryRandomAccessStream();
await RandomAccessStream.CopyAsync(imageStream, randomAccessStream);
This is important, rewind the IRandomAccessStream:
// Rewind.
randomAccessStream.Seek(0);
Finally, create a BitmapImage and assign it to your XAML Image control:
var bitmap = new BitmapImage();
bitmap.SetSource(randomAccessStream);
MyImage.Source = bitmap;
That's all!
If you need a URI to test, try this one:
Uri uri = new Uri("http://heyhttp.org/emoji.png");
HttpResponseMessage response = await client.GetAsync(uri);

How to get files from different folders compress them and return them to mobile client from asp.net web api service

Actually I'm trying to return multiple files(within same response as result to jQuery mobile client request) which include(html, .js, .css, .png images files) altogether at one time so that mobile client can download them as new updates. And I have been asked to make it a POST request rather than a GET request anyway.
Here is my Web API code
[Route("availableupdates")]
[HttpPost]
public HttpResponseMessage FilePackage()
{
HttpResponseMessage response = null;
var localFilePath = Directory.GetFiles(#"C:\Temp\Flower_Shop\Flower_Shop\images\i.png");
if (!File.Exists(localFilePath[0]))
{
response = Request.CreateResponse(HttpStatusCode.Gone);
}
else
{
response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StreamContent(new FileStream(localFilePath[0], FileMode.Open, FileAccess.Read));
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = "i";
}
return response;
}
Now the thing is that all those (html, .js, .css, .png) files are part of another little mobile app (and apparently lying in different folders within same application) which is sitting on the same server as the Web API RESTFUL service itself and in the code above I just hardcoded physical path of one of the image files. I don't know how to get all the files from different folders and sub-folders and compress them together and send them to the client.
Another big thing that I will really appreciate if someone explains me what MIMETYPE will work for the compressed files and do I need to send the compressed files as JSON response as I don't really know that It would be a good idea to send back a JSON response. What will happen to the contents of the files? Will the contents be converted into JSON as well?

Android equivalent of WebClient in .NET

I have a fairly basic application that I wrote in C# NET some time ago and would like to rewrite it for the Android platform. It just uses an API exposed by some web software, and I can access it with just a WebClient in .NET.
WebClient myClient = new WebClient();
//Prepare a Name/Value Collection to hold the post values
NameValueCollection form = new NameValueCollection();
form.Add("username", "bob");
form.Add("password", GetMD5Hash("mypass"));
form.Add("action", "getusers");
// POST data and read response
Byte[] responseData = myClient.UploadValues("https://mysite.com/api.php", form);
string strResponse = Encoding.ASCII.GetString(responseData);
I found the WebKit (android.webkit | Android Developers) but just from quick looking that doesn't seem appropriate.
Does anyone have any sample code of how to port this over?
This could be an equivalent:
List<NameValuePair> form = new ArrayList<NameValuePair>();
form.add(new BasicNameValuePair("username", "bob");
// etc...
// Post data to the server
HttpPost httppost = new HttpPost("https://mysite.com/api.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(httppost);
To summarize HttpClient could replace your WebClient. Then you have to use either HttpPost for posting data or HttpGet for retrieving data. There are some tutorials that you can read to help you understand how you could use these classes like this one.

Categories

Resources