Saving an image via web service - vb.net

Alright, long story short. I'm developing software similar to the devices UPS delivery divers use. We have to ways to get a proof of delivery(POD). The first is a signature and the second is a picture taken by the camera.
Now the device that is capturing these images sends them to a web service we have which then goes and saves them on the server. The device saves these two as different file types, png for the signature and jpg for the picture, but the web service saves them as jpg files. Currently the signatures are working but the pictures keep throwing an exception "generic exception occurred gdi+".
I don't understand why one will save just fine but the other keeps throwing the error message. Especially since they both use the same code when they are on the server side.
I've gone searched throw the stack overflow and haven't found anything that solves my issue and I've googled to no avail. Anyone have any suggestions on what to do to get the pictures to save?
Device logic to turn the image into a string so it can be sent to the web service.
**Picture from camera logic**
Using MS As New System.IO.MemoryStream(), BM As New Bitmap(ImagePath)
BM.Save(MS, System.Drawing.Imaging.ImageFormat.Jpeg)
ImageString = Convert.ToBase64String(MS.ToArray())
End Using
**Signature logic**
Using MS As New System.IO.MemoryStream(), BM As New Bitmap(ImagePath)
BM.Save(MS, System.Drawing.Imaging.ImageFormat.png)
ImageString = Convert.ToBase64String(MS.ToArray())
End Using
Web Service logic to turn image back into string, then save it as jpeg.
Dim Image As Drawing.Bitmap = Nothing
Dim ByteImage As Byte()
If ImageString.IsNullOrEmpty = False Then
ByteImage = Convert.FromBase64String(ImageString)
Using stream As New MemoryStream(ByteImage, 0, ByteImage.Length)
stream.Write(ByteImage, 0, ByteImage.Length)
Image = CType(Drawing.Bitmap.FromStream(stream, True), Drawing.Bitmap)
End Using
Image.Save(FileLocation,Drawing.Imaging.ImageFormat.Jpeg)
End If
That Image.Save is what is throwing the exception.

It appears that you save the image to some media on the phone, then you read it again and send it. Don't do that. Just save it, base 64 encode the whole file, send that base 64 encoded string.

Related

Webview2 - URL to Image

Background
I am relatively new to using the Webview2 control instead of the built in Webbrowser one. I have successfully made some javascripts that help me log in and authenticate myself to a particular website. Within a table from this website, there are a bunch of images.
My end goal is to have a datatable on my application that has all of these images displayed. So far I have all of the source URLs for each image but just need to convert them to the actual images themselves.
How I used to be able to do it using built in Webbrowser Control
Private Async Function GetBitmapFromLink(ByVal ImagePath As String) As Task(Of Image)
Dim request As System.Net.WebRequest = System.Net.WebRequest.Create(ImagePath)
Dim response As System.Net.WebResponse = Await request.GetResponseAsync()
Dim responseStream As System.IO.Stream = response.GetResponseStream()
Dim Img As New Bitmap(responseStream)
Return Img
End Function
Goal
I would like to be able to do a similar function using the Webview2 control instead but am having a hard time finding similar functions. For example, there is no Webview2.WebRequest. I am guessing that similar functions exist in Webview2 but I am just not able to find them.
My question is: How do I make a similar image download function like the one I have shown for the old built in Webbrowser control?
WebView2 does not have a mechanism to start a web request. However, it does have CoreWebView2.WebResourceResponseReceived which you can use to monitor the responses to web requests made from within the WebView2.
You may be able to CoreWebView2.ExecuteScriptAsync to inject script to start background web requests via fetch() or new Request() and then watch for the result of those with CoreWebView2.WebResourceResponseReceived. In the CoreWebView2WebResourceResponseReceivedEventArgs there is a Response property that has a GetContentAsync() async method that gives you the response stream.

How can i generate and download PDFs in Flask without saving them in my Webapp?

im trying to get a PDF with the ReportLab Module which works fine so far. My problem is that im saving the PDF with the .build()-method in my Webapps directory. What i want is that i can send the PDF for downloading without saving it before. That is somehow possible with the wkhtmltopdf module, but i dont want to use any other servers for this.
The process would be like: User presses a button 'download as pdf', a pdf is generated and instant returned as a download without saving it first.
Do you know if this is possible?
You want to create the PDF server side, return it to the client, without saving the PDF (for example, in S3)?
Yes, this is possible, you create the PDF in memory using
buffer = io.BytesIO()
myPDF = canvas.Canvas(buffer, pagesize=letter)
Then after creating your pdf you save it using
myPDF.save()
buffer.seek(0)
Then when you are ready to return the PDF as a reponse you can return it with:
response = HttpResponse(buffer, content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="{}"'.format("myFile.pdf")
return response

"Microsoft Edge PDF inline issue" Same Issue Again

I'm still having the same issue that was previously reported and answered under Microsoft Edge PDF inline issue even though I'm not using the pre-release version of Win 10, but the latest downloaded though Windows Update.
After upgrading my Win 8.1 Machine to Win 10, and tested my ASP.NET application, I faced an issue with displaying inline pdf files.
Here's my C# code in my ASP.NET application:
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition","inline;filename=some.pdf");
Response.BinaryWrite(pdfArray);
Response.End();
The above works on all browsers, except on Edge where it gives me the following error:
Couldn’t open PDF
Something’s keeping this PDF from opening.
What am I doing wrong?
Copied from my workaround on Microsoft Connect.
WARNING: This is a complete hack and runs the risk of breaking if/when Microsoft ever fixes this issue.
You'll see that Edge issues two requests whenever you view a PDF. To me, it looks like the browser is sending the initial request and then the PDF viewer is issuing its own request when it is opened. If you look at the headers in that second request, you'll see an odd DLNA header coming down, which should just be for media streaming, but that leads me to my workaround...
When the request is received in your handler or page, check if the user agent string contains "Edge/12." If it doesn't, send your PDF back normally. If it does, move on to step #2.
Check if the HTTP Header "GetContentFeatures.DLNA.ORG" exists. If it doesn't, that means that the request came from the browser. Just send back a Content-Type header of "application/pdf" and an empty body. If the header exists, then the request came from the PDF viewer and you can send your PDF back normally.
Basically, the handler treats that first request as a HEAD request and then responds with the full PDF if we determine that the request is coming from the PDF viewer. The risk we run here is if Microsoft removes that DLNA header later on, Edge will not render the PDF properly. Hopefully, Microsoft will fix this issue in their browser and this workaround will not be necessary.
Thanks Dark Helmet, you saved my day.
I implemented the solution in java. Here is the code that might help others.
String userAgent = request.getHeader("user-agent");
System.out.println(userAgent);
if(userAgent.contains("Edge")){
String dlnaHeader = request.getHeader("getcontentfeatures.dlna.org");
System.out.println(dlnaHeader);
if(dlnaHeader == null ){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] result = baos.toByteArray();
response.setContentType("application/pdf");
response.setHeader("Content-disposition","inline; ");
response.setContentLength(result.length);
ServletOutputStream sos = response.getOutputStream();
sos.write(result);
return null;
}
}
Thanks guys, I just want to put my VB.NET solution here based on your workaround.
Response.Clear()
Response.ClearHeaders()
Response.ClearContent()
Response.Buffer = True
If Request.Headers.Item("User-Agent").Contains("Edge") _
AndAlso IsNothing(Request.Headers.Item("GetContentFeatures.DLNA.ORG")) Then
'Edge? Send empty output if special header not exist
Response.ContentType = "application/pdf"
Dim bTemp As Byte()
Response.BinaryWrite(bTemp) 'Empty output
Response.Flush()
Response.SuppressContent = True
HttpContext.Current.ApplicationInstance.CompleteRequest()
End If
'Normal process:
Response.ContentType = "application/pdf"
Response.BinaryWrite(pdfArray)
Response.Flush()
Response.SuppressContent = True
HttpContext.Current.ApplicationInstance.CompleteRequest()
With Edge 16.16299 (Windows Fall Creator Update) there were made changes here. We did the workaround described in this issue and it worked "well". But now with the new version of Edge (16.16299) it isn’t working anymore and it happens, that the PDFs are corrupted (0 bytes large). Take care if you implemented this workaround somewhere.
What you also take care of is that Edge is doing two requests like before.

How can I embed a swf object in a vb.net winform?

I have a swf object that I would like to embed using the COM Shockwave Flash Object control. I've searched around, but I've only found answers that involve using file or internet URLs. As I am using the One-Click publishing method, I would like to have a way to embed my flash object as a resource file into my application.
Thanks,
Matt
I've done something similar in the past but loading from a DB table rather than a resource
Swf is a AxShockwaveFlash Object on the Form to display the flash item.
If you add your resource as a .swf and set the FileType to binary it should return it as a byte array which you can then use in the memorystream constructor
Using ms As New IO.MemoryStream(my.resources.TheFlashFile), fs As New IO.MemoryStream()
Using bwriter As New IO.BinaryWriter(fs)
' Write length of stream for flash AxHost.State
bwriter.Write(8 + ms.ToArray.Length)
bwriter.Write(&H55665566)
' Length of flash movie file
bwriter.Write(ms.ToArray.Length)
bwriter.Write(ms.ToArray)
fs.Seek(0, IO.SeekOrigin.Begin)
swf.OcxState = New AxHost.State(fs, 1, False, Nothing)
End Using
End Using

vb.net - WebBrowser1.Navigate tries to download JSON file

I am trying to navigate to a website with json data using the webbrowser controls but it keeps prompting me to download the file instead of properly navigating to the page as firefox would.
I have tried doing a regular navigate:
frmBrowser.WebBrowser1.Navigate("http://us.wowarmory.com/auctionhouse/money.json")
As well as editing the header content type with many different types:
frmBrowser.WebBrowser1.Navigate("http://us.wowarmory.com/auctionhouse/money.json", "", Nothing, "Content-Type: text/plain" & vbCrLf)
But cant seem to get it working.. Keep in mind I need to use the webbrowser to navigate as you have to be logged in to access this file.
Edit: Also, manually editing my computers registry won't work as I need to distribute this program.
Edit2: Just wanted to add that this code would work if it were the same session, but since it webclient creates a new session it doesn't work
Dim oWeb As New System.Net.WebClient()
oWeb.Headers.Add("Content-Type", "application/x-www-form-urlencoded")
Dim bytArguments As Byte() = System.Text.Encoding.ASCII.GetBytes(params)
Dim bytRetData As Byte() = oWeb.UploadData(url, "POST", bytArguments)
Return System.Text.Encoding.ASCII.GetString(bytRetData)
If your application will allow it, just rename it to money.json.html or something similar. Will download without a problem.