Getting empty pdf attachments when trying to create "activitymimeattachment" - c#

I want to attach pdf from url into CRM "activitymimeattachment". Everything works fine but im getting empty pdf attachments (even the size is the same as original pdf). Could it be some problem with Encoding or converting? Maybe somebody could help me with this?
I see that email is created with attachment which is empty, but the size is the same as for original pdf.
Entity attachment = new Entity("activitymimeattachment");
attachment["subject"] = "Attachment";
string fileName = "Invoice.pdf";
attachment["filename"] = fileName;
WebClient wc = new WebClient();
string theTextFile = wc.DownloadString(url);
byte[] fileStream = Encoding.ASCII.GetBytes(theTextFile);
attachment["body"] = Convert.ToBase64String(fileStream);
attachment["mimetype"] = "application/pdf";
attachment["attachmentnumber"] = 1;
attachment["objectid"] = new EntityReference("email", emailguid);
attachment["objecttypecode"] = "email";
service.Create(attachment);

I believe the encoding is issue. The PDF is neither a string nor an ASCII file so these lines are at fault:
string theTextFile = wc.DownloadString(url);
byte[] fileStream = Encoding.ASCII.GetBytes(theTextFile);
I would suggest changing your web client to download a binary file i.e. application/pdf and save the file locally e.g to d:\temp\invoice.pdf.
Then you can do this:
var bytes = File.ReadAllBytes(#"d:\temp\invoice.pdf");
var body = Convert.ToBase64String(bytes);
In short, avoid trying to put the PDF into a string, or using the ASCII encoding to get its byte array. It's a binary file until you convert it to Base64.
Of course you can also probably get your web client to download the file into memory and convert it to Base64 without writing the file locally. I just wanted the simplest example to make the point about the encoding.

Thank You for advice #Aron. I actually have found a solution which is very simnply. I just used another method from WebClient class. The main thing I needed to change DownloadString(url) method into DownloadData(url) method:
WebClient wc = new WebClient();
byte[] theTextFile = wc.DownloadData(url);
attachment["body"] = Convert.ToBase64String(theTextFile);enter code here

Related

Convert image url into image bye in asp.net

for (int i = 0; i < (DataTable)ViewState["Table_RemarksDetails"]).Rows.Count; i++)
{
string url = Image1.ImageUrl;
Byte[] imgByte = GetBytesFromUrl(url);
obj_ICCommon.Userid = username;
obj_ICCommon.Modules = "Transfer-TO";
obj_ICCommon.Invoiceno = TransferNo;
obj_ICCommon.Comments = ((DataTable)ViewState["Table_RemarksDetails"]).Rows[i]["Comments"].ToString();
//obj_ICCommon.Image = imgByte;
string Result = obj_ICCommon.funinsertRemarks();
fun_InsertRemarksImage(TransferNo, imgByte, ((DataTable)ViewState["Table_RemarksDetails"]).Rows[i]["Comments"].ToString());
}
static public byte[] GetBytesFromUrl(string url)
{
byte[] b;
System.Net.HttpWebRequest myReq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
System.Net.WebResponse myResp = myReq.GetResponse();
Stream stream = myResp.GetResponseStream();
//int i;
using (BinaryReader br = new BinaryReader(stream))
{
//i = (int)(stream.Length);
b = br.ReadBytes(500000);
br.Close();
}
myResp.Close();
return b;
}
This code throws an exception url not recognized. My url is in format like "data://image.png" . What to do ? Anyone lets you know. I am struggle in this past 2 days.
I just want to convert the url into byte
. If my code is wrong or any other way is possible to convert url into byte. Please comment me. Thanks in advance
If you want to turn a data URI into a byte image, your input string is not sufficient. Given the following sample data URI:
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="
You would need to:
Trim the data: string from the front.
Split by the ; character to get the image format and encoding type.
If the encoding type is Base64, you would need to use the data obtained in (2) to decode the image string back into a byte array.
If on the other hand, you want to change the image data.png into its corresponding base64 representation, then you would need to make some changes to your code:
Decide what URL's you are going to be reading. If they are web, such as http and https, then your code should be good since you are dealing with web requests. If they are actual file paths, you would need to handle the file URI, so your code would be slightly different.
One that you will have your file, you would need to load it as a byte array.
Create a string with the following: data:image/png;base64,.
Append the base64 representation of the byte array you got in step 2.

Mailkit - Get HTML and Text parts without having full mime message

I want to download text and html parts from mime message and store it in the database and later if needed to download attachments. I need this because I don't want to store the attachments in my database to save disk space and bandwidth. They will be downloaded on demand later. I am not sure if I can do that and still be able to use MimeParser from MimeKit
I am planning to do that:
Get message body structure and find the text and html parts
Download text and html body parts using ImapFolder.GetStream and store in database preserving mime tree structure by saving section names along with headers. Attachment will not be downloaded
Later I want to show the message in the UI but I want to delay parsing until the mail message needs to be shown in the UI.
This is my progress so far
var msgSummaries = remoteFolder.Fetch(new int[] { remoteMessage.Index }, MessageSummaryItems.BodyStructure);
var stream = remoteFolder.GetStream(remoteMessage.Index, msgSummaries[0].HtmlBody.PartSpecifier);
//at this point i am saving the stream to the database and later i am trying to convert it to mime entity like that
var parser = new MimeParser(ParserOptions.Default, stream, true);
var mimeEntity = parser.ParseEntity(cancellationToken);
Unfortunatelly the stream doesn't contain mime part headers and cannot be parsed and I don't see an option to request headers inside GetStream method like this
FETCH 1 (BODY.PEEK[2.MIME] BODY.PEEK[2])
Any suggestions?
Well, first of all, have you tried:
var mimeEntity = remoteFolder.GetBodyPart (remoteMessage.Index, msgSummaries[0].HtmlBody);
or, if you really want to use streams:
var headerStream = remoteFolder.GetStream (remoteMessage.Index, msgSummaries[0].HtmlBody.PartSpecifier + ".MIME");
var contentStream = remoteFolder.GetStream (remoteMessage.Index, msgSummaries[0].HtmlBody.PartSpecifier);
var stream = new MemoryStream ();
headerStream.CopyTo (stream);
headerStream.Dispose ();
contentStream.CopyTo (stream);
contentStream.Dispose ();
stream.Position = 0;
//at this point i am saving the stream to the database and later i am trying to convert it to mime entity like that
var parser = new MimeParser(ParserOptions.Default, stream, true);
var mimeEntity = parser.ParseEntity(cancellationToken);

Creating wav file from RIFF string

I am creating a Voice Authentication system, for that I am using third party API which stores my wav file and when I call GET, it returns the RIFF format encoded string in response.
I am not able to figure out a way to convert this RIFF into a wav file.
I tried below code, it is creating wav file but the wav is currupted:
using (var response = await httpClient.GetAsync(""))
{
string responseData = await response.Content.ReadAsStringAsync();
using (BinaryWriter writer = new BinaryWriter(System.IO.File.Open(#"C:\wavFile.wav", FileMode.Create)))
{
byte[] data = System.Text.Encoding.UTF8.GetBytes(responseData);
writer.Write(data);
}
}
I tried ASCII along with UTF8 but same result. Can anyone help?
You should not read the response as a string. A wave file is binary data which may contain byte sequences which are not valid for strings.
The WebClient (MSDN) can directly download binary data without need of converting it.
using (var webClient = new WebClient())
{
byte[] wave = webClient.DownloadData("...");
}

Extract pdf file on ftp server using itextsharp

I am working on Document management project and I want to extract text from pdf. How can I achieve this. I am using Itextsharp to extract pdf on local system
This is a function I am using for this purpose. Path is a FTP Server Path
public static string ExtractTextFromPdf(string path)
{
using (PdfReader reader = new PdfReader(path))
{
StringBuilder text = new StringBuilder();
for (int i = 1; i <= reader.NumberOfPages; i++)
{
text.Append(PdfTextExtractor.GetTextFromPage(reader, i));
}
return text.ToString();
}
}
It throws an exception
'ftp:\\###\index\500199.pdf not found as file or resource.'
[### is my ftp server]
PdfReader has a bunch of constructor overloads but most of them rely on RandomAccessSourceFactory to convert whatever is passed in into a Stream format. When you pass a string in it is checked if it is a file on disk and if not it is checked if it can be converted to a Uri as one of file:/, http:// or https:// link. This is your first point of failure because none of these checks handle the ftp protocol and you ultimately end up at a local resource loader which doesn't work for you.
You could try converting your string to an explicit Uri but that actually won't work, either:
//This won't work
new PdfReader(new Uri(path))
The reason that this won't work is because iText tells .Net to use CredentialCache.DefaultCredentials when loading remote resources however that concept doesn't exist in the FTP world.
Long story short, when using FTP you'll want to download the files on your own. Depending on their size you'll want to either download them to disk or download them a byte array. Below is a sample of the latter:
Byte[] bytes;
if( path.StartsWith(#"ftp://")) {
var wc = WebRequest.Create(path);
using (var response = wc.GetResponse()) {
using (var responseStream = response.GetResponseStream()) {
bytes = iTextSharp.text.io.StreamUtil.InputStreamToArray(responseStream);
}
}
}
You can then pass either the local file or the byte array to the PdfReader constructor.

Ruby base64 to C# base64

I'm writing a Ruby/Rhomobile application that takes an image, encodes it in base64 and sends to the server(that is running C# on ASP.NET), as part of a bigger XML.
However, once I try to decode the base64 and save it to the hard disk, the resulting file does not work as an image.
Here's the relevant ruby code:
image_element = REXML::Element.new("image")
image_element.text = Base64.encode64(open(Rho::RhoApplication::get_blob_path(self.image_uri)) { |io| io.read })
form_element.add_element(image_element)
And here is my C# code:
var doc = new XmlDocument();
doc.LoadXml(Server.UrlDecode(Request.Form[0]));
var imageBase64 = doc.SelectNodes("//image")[0];
var imageBytes = imageBase64.InnerText;
using(var imgWriter = new FileStream(#"c:\img.jpg",FileMode.Create))
{
imgWriter.Write(imageBytes,0,imageBytes.Length);
}
I would investigate your call to Server.UrlDecode. It seems like that could corrupt your data.
It seems like the "+" sign is of specific concern, per this SO question. Server.UrlDecode uses HttpServerUtility.UrlDecode, and here's the documentation for it.

Categories

Resources