Download Proof of Delivery as PDF in UPS API - ups

UPS provided DeveloperKit to find delivery status. Below is an example for .Net:
TrackService track = new TrackService();
TrackRequest tr = new TrackRequest();
UPSSecurity upss = new UPSSecurity();
UPSSecurityServiceAccessToken upssSvcAccessToken = new UPSSecurityServiceAccessToken();
upssSvcAccessToken.AccessLicenseNumber = "Your access license number";
upss.ServiceAccessToken = upssSvcAccessToken;
UPSSecurityUsernameToken upssUsrNameToken = new UPSSecurityUsernameToken();
upssUsrNameToken.Username = "Your username";
upssUsrNameToken.Password = "Your password";
upss.UsernameToken = upssUsrNameToken;
track.UPSSecurityValue = upss;
RequestType request = new RequestType();
String[] requestOption = { "15" };
request.RequestOption = requestOption;
tr.Request = request;
tr.InquiryNumber = "Your track inquiry number";
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12 | System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Tls11; //This line will ensure the latest security protocol for consuming the web service call.
TrackResponse trackResponse = track.ProcessTrack(tr);
//ResponseType loResponse = trackResponse.Response;
Console.WriteLine("The transaction was a " + trackResponse.Response.ResponseStatus.Description);
Console.WriteLine("Shipment Service " + trackResponse.Shipment[0].Service.Description);
Console.ReadKey();
This code works fine, and returns shipment details as text. I need to download Proof of Delivery (POD) as PDF.
The manual shows that loading such PDF is possible via object /TrackResponse/Shipment/Document/Content.
However, the object Document is not available under trackResponse.Shipment. Response option 15 used in the request means that Signature Tracking only is ON.
Any ideas how to get the Proof of Delivery as a PDF file?

UPS sends Proof of Delivery (POD) in HTML format only. Conversion to PDF needs to be done by the developer.
HTML code comes in:
trackResponse.Shipment[0].Package[0].Activity[0].Document[0].Content
That value needs to be decoded:
byte[] data = Convert.FromBase64String(trackResponse.Shipment[0].Package[0].Activity[0].Document[0].Content);
string decodedString = Encoding.UTF8.GetString(data);
Then decoded string needs to be converted to PDF. I used a third-party library, available through NuGet.

Related

Microsoft Graph API - OneNote - Create Page Issue - System.IO.Stream.get_ReadTimeout()

Tried Graph API directly for creating page, Is it the right way/possible or else we should use only HttpClient to create page.
Also I couldn't see C# code example for create page under request,
https://learn.microsoft.com/en-us/graph/api/section-post-pages?view=graph-rest-1.0#request
Errors
InvalidOperationException: Timeouts are not supported on this stream.
System.IO.Stream.get_ReadTimeout()
JsonSerializationException: Error getting value from 'ReadTimeout' on 'System.IO.MemoryStream'.
Newtonsoft.Json.Serialization.ExpressionValueProvider.GetValue(object target)
Code
var page = new OnenotePage
{
Title = "Graph API Notes Page",
Content = new MemoryStream(Encoding.UTF8.GetBytes("Created Date - " + DateTime.Now))
};
await graphClient
.Sites[siteId]
.Onenote
.Sections[sectionId]
.Pages
.Request()
.AddAsync(page);
You can use the below code to add content to OneNote page
string notesContent = $"<!DOCTYPE html><html><head><title>{NotebookTitle}</title></head><body>{NotebookContent}</body></html>";
return await GraphClient.Me.Onenote.Sections[SectionId].Pages.Request().AddAsync(notesContent, "text/html");

HTML5 audio seek is not working properly. Throws Response Content-Length mismatch Exception

I'm trying to stream audio file to Angular application where is html5 audio element and src set to my api end point (example. /audio/234). My backend is implemented with .NET Core 2.0. I have implemented already this kind of streaming: .NET Core| MVC pass audio file to html5 player. Enable seeking
Seek works if I don't seek to end of file immediately when audio starts playing. I use audio element's autoplay attribute to start playing immediately audio element has enough data. So in my situation audio element has not yet all the data when I seek so it make new GET to my API. In that situation in my backend log there is this Exception:
fail: Microsoft.AspNetCore.Server.Kestrel[13]
[1] Connection id "0HL9V370HAF39", Request id "0HL9V370HAF39:00000001": An unhandled exception was thrown by the application.
[1] System.InvalidOperationException: Response Content-Length mismatch: too few bytes written (0 of 6126919).
Here is my audio controller GET method.
byte[] audioArray = new byte[0];
//Here I load audio file from cloud
long fSize = audioArray.Length;
long startbyte = 0;
long endbyte = fSize - 1;
int statusCode = 200;
var rangeRequest = Request.Headers["Range"].ToString();
_logger.LogWarning(rangeRequest);
if (rangeRequest != "")
{
string[] range = Request.Headers["Range"].ToString().Split(new char[] { '=', '-' });
startbyte = Convert.ToInt64(range[1]);
if (range.Length > 2 && range[2] != "") endbyte = Convert.ToInt64(range[2]);
if (startbyte != 0 || endbyte != fSize - 1 || range.Length > 2 && range[2] == "")
{ statusCode = 206; }
}
_logger.LogWarning(startbyte.ToString());
long desSize = endbyte - startbyte + 1;
_logger.LogWarning(desSize.ToString());
_logger.LogWarning(fSize.ToString());
Response.StatusCode = statusCode;
Response.ContentType = "audio/mp3";
Response.Headers.Add("Content-Accept", Response.ContentType);
Response.Headers.Add("Content-Length", desSize.ToString());
Response.Headers.Add("Content-Range", string.Format("bytes {0}-{1}/{2}", startbyte, endbyte, fSize));
Response.Headers.Add("Accept-Ranges", "bytes");
Response.Headers.Remove("Cache-Control");
var stream = new MemoryStream(audioArray, (int)startbyte, (int)desSize);
return new FileStreamResult(stream, Response.ContentType)
{
FileDownloadName = track.Name
};
Am I missing some Header or what?
I didn't get this exception with .NET Core 1.1 but I'm not sure is it just coincident and/or bad testing. But if anybody has information is there something changed in .NET Core related to streaming I will appreciate that info.
Now when I research more I found this: https://learn.microsoft.com/en-us/aspnet/core/aspnetcore-2.0 look Enhanced HTTP header support- heading. It says this
If an application visitor requests content with a Range Request header, ASP.NET will recognize that and handle that header. If the requested content can be partially delivered, ASP.NET will appropriately skip and return just the requested set of bytes. You do not need to write any special handlers into your methods to adapt or handle this feature; it is automatically handled for you.
So all I need is some clean up when I move to .NET Core 1.1 to 2.0 because there is already handler for those headers.
byte[] audioArray = new byte[0];
//Here I get my MP3 file from cloud
var stream = new MemoryStream(audioArray);
return new FileStreamResult(stream, "audio/mp3")
{
FileDownloadName = track.Name
};
Problem was in Headers. I don't know exactly which header was incorrect or was my stream initialization incorrect but now It's working. I used this https://stackoverflow.com/a/35920244/8081009 . Only change I make this was renamed it as AudioStreamResult. And then I used it like this:
Response.ContentType = "audio/mp3";
Response.Headers.Add("Content-Accept", Response.ContentType);
Response.Headers.Remove("Cache-Control");
var stream = new MemoryStream(audioArray);
return new AudioStreamResult(stream, Response.ContentType)
{
FileDownloadName = track.Name
};
Notice that I pass full stream to AudioStreamResult.
var stream = new MemoryStream(audioArray);

How can I send files / pictures to Report Portal with .net client?

I'd like to send a binary attachment to Report Portal with .net client. How can I do it?
Example is in Tests project.
https://github.com/reportportal/client-net/blob/master/ReportPortal.Client.Tests/LogItem/LogItem.cs
Find CreateLogWithAttach test and see code.
var data = new byte[] { 1, 2, 3 };
var log = Service.AddLogItem(new AddLogItemRequest
{
TestItemId = _testId,
Text = "Log1",
Time = DateTime.UtcNow,
Level = LogLevel.Info,
Attach = new Attach("file1", "application/octet-stream", data)
});
Related documentation: Log Data in ReportPortal

EWS - FileAttachment Content is empty / byte[0]

I have written a WebAPI controller method that finds a mail by its unique ID from ExchangeOnline. I wrote a small model class in order to store some attributes of a mail like the subject, the sender, the date received and so on.
Now I also want to access file attachments if the mail has such attachments. Therefore, I wrote this code (just the relevant part):
List<AttachmentItem> attDataContainer = new List<AttachmentItem>();
EmailMessage originalMail = EmailMessage.Bind(service, new ItemId(uniqueID), new PropertySet(ItemSchema.Attachments));
foreach (Attachment att in originalMail.Attachments)
{
if (att is FileAttachment && !att.IsInline)
{
FileAttachment fa = att as FileAttachment;
fa.Load();
attDataContainer.Add(
new AttachmentItem
{
ID = fa.Id,
Name = fa.Name,
ContentID = fa.ContentId,
ContentType = fa.ContentType,
ContentLocation = fa.ContentLocation,
Content = Convert.ToBase64String(fa.Content),
Size = fa.Size
});
}
}
The method indeed finds the attachments and displays all of the attributes you can see in the "AttachmentItem" object - BUT NOT the fa.Content attribute.
I have crwaled almost any document I could find on this (especially the *.Load() part as well as much examples. But in my case I get "byte[0]" when debugging the output.
Do you have any idea for me what could be the reason for this?
PS: By the way, I have version v2.0.50727 of Microsoft.Exchange.WebServices referenced.
Best regards and thanks in advance,
Marco
When you call the load method on the Attachment that should make a GetAttachment request to the server which will return the data for that Attachment. If you enable tracing https://msdn.microsoft.com/en-us/library/office/dn495632(v=exchg.150).aspx that should allow you to follow the underlying SOAP requests which should help with troubleshooting (eg you can see what the server is returning which is important).
The other thing to check is that is this is a real attachment vs a One Drive attachment which could be the case on ExchangeOnline.

search embeded webpage source in vb.net

I wrote a program that includes an embedded web browser that loads a website which have a changing part (the part changes about 2 times a week and it have no regular timing pattern) that I want to search for a particular part in the opened webpage source code after refreshing the webpage in a specified time interval.
I found many things similar to my question but this is what I want and those questions doesn't have:
search embedded webpage source (they searching the webpage without embedding, and I had to embed it because I had to login before I see the particular page)
so this is the procedure I'm trying to do:
1- open a website in embedded web browser
2- after user logged in, with a press of button in program, it hides the embedded
web browser and start to refresh the page in a time interval (like
every minute) and search if the particular code changed in the source of
that opened webpage
any other/better Ideas appreciated
thanks
Many years ago I wrote an app to reintegrate forum posts from several pages into one and I struggled with the login issue too and thought it was only possible using an embedded browser. As it turns out, it's possible to use System.Net in .NET to handle web pages that need a login as you can pull the cookies out and keep them on hand. I would suggest you do that and move away from the embedded browser.
Unfortunately I wrote the code in C# originally, but as it's .NET and is mostly classes-based, it shouldn't be too difficult to port over.
The Basic Principle
Find out what information is included in the POST when you login, which you can do in Chrome with developer mode on (F12). Convert that to a byteArray, POST it to the page, store the cookies and make another call with the cookie data later on. You will need a class variable to hold the cookies.
Code:
private void Login()
{
byte[] byteArray = Encoding.UTF8.GetBytes("username=" + username + "&password=" + password + "&autologin=on&login=Log+in"); // Found by investigation
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("yourURL");
request.AllowAutoRedirect = false;
request.CookieContainer = new CookieContainer();
request.Method = "POST";
request.ContentLength = byteArray.Length;
request.ContentType = "application/x-www-form-urlencoded";
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
if (((HttpWebResponse)response).StatusCode == HttpStatusCode.Found)
{
// Well done, your login has been accepted
loginDone = true;
cookies = request.CookieContainer;
}
else
{
// If at first you don't succeed...
}
response.Close();
}
private string GetResponseHTML(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AllowAutoRedirect = false;
// Add cookies from Login()
request.CookieContainer = cookies;
request.ContentType = "application/x-www-form-urlencoded";
WebResponse response = request.GetResponse();
string sResponse = "";
StreamReader reader = null;
if (((HttpWebResponse)response).StatusCode == HttpStatusCode.OK)
{
reader = new StreamReader(response.GetResponseStream());
sResponse = reader.ReadToEnd();
reader.Close();
}
response.Close();
return sResponse;
}
Hope that helps.
I had to change to C# and I found what I was looking for:
string webPageSource = webBrowser1.DocumentText;
That gave me the source of web page opened in webBrowser1 control.