How to parse attachment values with strongGrid inbound webhook - parsing

Hello there I have setup successfully inbound webhook with strongGrid in net core 3.1.
The endpoint gets called and I want to parse value inside the attachment which is csv file.
The code I am using is following
var parser = new WebhookParser();
var inboundEmail = await parser.ParseInboundEmailWebhookAsync(Request.Body).ConfigureAwait(false);
await _emailSender.SendEmailAsyncWithSendGrid("info#mydomain.com", "ParseWebhook1", inboundEmail.Attachments.First().Data.ToString());
Please note I am sending an email as I don t know how to debug webhook with sendgrid as I am not aware of any cli.
but this line apparently is not what I am looking for
inboundEmail.Attachments.First().Data.ToString()
I am getting this on my email
Id = a3e6a543-2aee-4ffe-a36a-a53k95921998, Tag = HttpMultipartParser.MultipartFormDataParser.ParseStreamAsync, Length = 530 bytes
the csv I need to parse has 3 fields Sku productname and quantity I'd like to get sku values.
Any help would be appreciated.

The .Data property contains a Stream and invoking ToString on a stream object does not return its content. The proper way to read the content of a stream in C# is something like this:
var streamReader = new StreamReader(inboundEmail.Attachments.First().Data);
var attachmentContent = await streamReader.ReadToEndAsync().ConfigureAwait(false);
As far as parsing the CSV, there are literally thousands of projects on GitHub and hundreds on NuGet with the keyword 'CSV'. I'm sure one of them will fit your needs.

Related

How to fetch the list of Tags in TFS 2015 Update 3

Is there a way to fetch the list of tags created for a team project, basically we need information such as creation date, created by user etc.
Can we fetch these information using TFS RestApi? If so it would be helpful if code snippets are provided.
There isn't the information of created by user, you can check it in dbo.tbl_TagDefinition table of collection database.
To fetch the list of Tags, you can refer to Giulio’s answer, for example:
[collection URL]/_apis/tagging/scopes/[Team Project ID]/tags?api-version=1.0
To get Team Project ID, you can call this REST API:
[Collection URL]/_apis/projects?api-version=1.0
Simple code for C#:
String MyURI = "[collection URL]/_apis/tagging/scopes/f593de42-d419-4e07-afc7-1f334077c212/tags?api-version=1.0";
WebRequest WReq = WebRequest.Create(MyURI);
WReq.Credentials =
new NetworkCredential("[user name]", "[password]", "[domain"");
WebResponse response = WReq.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
There is a REST API to manage Tags, but there is not auditing information as per your request.
If you want to learn how to call a REST API there is plenty of sources, starting from the Get started page.

Azure blob authorization header

I am trying to use refit to upload to azure blob storage from a Xamarin iOS application. This is the interface configuration I am using for Refit:
[Headers("x-ms-blob-type: BlockBlob")]
[Put("/{fileName}")]
Task<bool> UploadAsync([Body]byte[] content, string sasTokenKey,
[Header("Content-Type")] string contentType);
Where the sasTokenKey parameter looks like this:
"/content-default/1635839001660743375-66f93195-e923-4c8b-a3f1-5f3f9ba9dd32.jpeg?sv=2015-04-05&sr=b&sig=Up26vDxQikFqo%2FDQjRB08YtmK418rZfKx1IHbYKAjIE%3D&se=2015-11-23T18:59:26Z&sp=w"
This is how I am using Refit to call the azure blob server:
var myRefitApi = RestService.For<IMyRefitAPI>("https://myaccount.blob.core.windows.net");
myRefitApi.UploadAsync(photoBytes, sasTokenKey, "image/jpeg"
However I am getting the follow error:
Response status code does not indicate success: 403 (Server failed to
authenticate the request. Make sure the value of Authorization header is
formed correctly including the signature.)
The SAS url is working fine if I call it directly like this
var content = new StreamContent(stream);
content.Headers.Add("Content-Type", "jpeg");
content.Headers.Add("x-ms-blob-type", "BlockBlob");
var task = HttpClient.PutAsync(new Uri(sasTokenUrl), content);
task.Wait();
So basically I am just trying to do the same thing using Refit.
Any idea how to get Refit working with Azure Blob Storage?
Thanks!
[UPDATE] I am now able to upload the bytes to the azure blob server but something seems to be wrong with the byte data because I am not able to view the image. Here is the code I am using to convert to byte array.
byte[] bytes;
using (var ms = new MemoryStream())
{
stream.Position = 0;
stream.CopyTo(ms);
ms.Position = 0;
bytes = ms.ToArray();
}
[UPDATE] Got it fixed by using stream instead of byte array!
I see %2F and %3D and I'm curious if refit is encoding those a second time. Try sending the token without encoding it.
This is incorrect use of Authorization header. You use Authorization header when you want to authorize the requests using account key. If you have the Shared Access Signature then you really don't need this header as the authorization information is included in the SAS itself. You can simply use the SAS URL for uploading files.

WebAPI: Upload picture & get byte array

I want the user to be able to upload a file via my application. I don't have DB access, all my data calls get completed via a web-service that another person is writing. I needed to secure the web service, so I've consumed it & exposed it via WebAPI, & added OAuth security.
Now to my problem.
I've written the following.
public Task<FileResult> Post()
{
if (Request.Content.IsMimeMultipartContent())
{
var task = Request.Content.ReadAsByteArrayAsync().ContinueWith(
o =>
{
var result = this.Client.UploadPicture(this.UserId, o.Result);
if (result.ResultCode == 0)
{
return new FileResult()
{
Message = "Success",
FileId = result.ServerId
};
}
throw new HttpResponseException(...);
});
return task;
}
...
}
I'm pretty much a noob when it comes to WebAPI & multithreading (I'm not sure why this needs to be handled async? I'm sure there is a reason, but for now I'd just like a working example and get to the why later..).
My code is loosely based on some R&D & samples I've found on the net, but i haven't come across a scenario like I'm needing to complete... Yet it doesn't seem like I'm doing something out of the ordinary...
Upload a file to the server, and pass the image byte[] object to either sql or another service?
In this line
var result = this.Client.UploadPicture(this.UserId, o.Result);
I'm uploading a byte[] array of something....
Then later (the retrieval method works, I've managed to retrieve & view a test image)
When retrieving the byte array of the "image" i uploaded i get an array of idk what.. EG, i get a valid result of something, but it ain't no picture. Which leads me to believe that the uploaded data is bogus :|
O_o
How to get the image byte[]?
Mime Multipart is more than just your array of bytes. It also has metadata and boundary stuff. You need to treat it as MultiPartContent and then extract the image byte array out of that.
Filip has a blog post on the subject here.

How to get Response from another channel in mirth

We have two channels called channelA and channelB.
In channelA we have two destinations
a. first destination will invoke the channelB with XML data as input and get the response from the channelB in XML format.
b. retrieve the response of first destination in xml format and process it.
var dest1 = responseMap.get("destination1");
var resMessage = dest1.getMessage();
I am getting channelB response as "Message routed successfully".
How I will get actual XML from channelB instead of "Message routed successfully" message.
We are doing above steps to define generic channels such that we can reuse it in different scenarios in the mirth application.
We using mirth 2.2.1.5861 version.
We are doing something very similar to what you described. In our case, destination1 is a SOAP sender (SOAP uses XML for its send and receive envelopes). Here's the syntax we are successfully using in destination2 JavaScript Writer:
var dest1 = responseMap.get("destination1");
var resMessage = dest1.getStatus().toString();
if (resMessage == "SUCCESS")
{
var stringResponse = dest1.getMessage();
channelMap.put('stringResponse',stringResponse);
var xmlResponse = new XML(stringResponse);
// use e4x notation to parse xmlResponse
}
If your destination1 is not a SOAP sender, then the XML response from channelB might be getting packaged up in some way that you need to extract from "stringResponse." You can see the contents of the channelMap variable "stringResponse" after running the message through the channel. Go to the dashboard, double-click the channel, find a message that has been sent, and then look at the mappings tab. What does the content of "stringResponse" actually look like? Is it just "Message routed successfully?" Or is that text followed by the XML that you're after?
Create ChannelB having source data type as an XML, and put source as a channel reader.
You have to make a single destination on ChannelA as a Channel Writer, and put ChannelB in the details.
This way whatever message you get in the form of an XML in ChannelAwill be routed to ChannelB.

WebRequest to download XML Feed

This is my first time working with a webservice and I tried looking up all the resources on the web but I wasn't able to get it to work.
I have to use this XML in my windows phone application and I want the application to retrieve it when the user wants to. I know how to parse the XML but I am just not able to get the XML from the XML feed.
There are lots of tutorials for this type of problem available on the wider web.
For example, try the 3 line solution from: http://www.codeproject.com/Articles/156610/WP7-WebClient-vs-HttpWebRequest
var client = new WebClient();
client.DownloadStringCompleted += (s, ev) => { responseTextBlock.Text = ev.Result; };
client.DownloadStringAsync(new Uri("http://www.sherdog.com/rss/news.xml"));

Resources