Getting Body content from MSMQ - c#

I try to get the content of an item in a MSMQ - Queue.
When I look at that Entry using QueueExplorer the body content is like
[{"$type":"MyProject.MyClass.MyMethod, Messages","CustomerDecision":0,"OrderReferenceoId":"4fdb6be2-bfde-42b0-93fd-47058a326a24"}]
When I try to read the content using the following code, the body just contains weird crap, mostly \0\0 etc.:
message.Formatter = new XmlMessageFormatter();
var reader = new StreamReader(message.BodyStream);
var msgBody = reader.ReadToEnd();
(message is of type System.Messaging.Message)

It was a Coding Issue. The result LOOKED like random rubbish, but just was a unicode characterset. The following solved the problem:
message.Formatter = new BinaryMessageFormatter();
var reader = new StreamReader(message.BodyStream, Encoding.Unicode);
var msgBody = reader.ReadToEnd();

Related

How to set content transfer encoding using MimeKit/MailKit?

I try to send text in attachment. That works well only right now i have encoding problems in the builder.ToMessageBody() statement (see code below) Itry to send an email with text "my text = my subject and Version=1.0" as attachment , but when you open the email the text has been altered to "my text =3D my subject and Version=3D1.0". As you can see the = sign has been encoded to =3D Is there a way to change the encoding?
Thanks
var message = new MimeMessage();
var builder = new BodyBuilder();
builder.TextBody = "";
var xmltext ="my text = my subject and Version=1.0" ;
builder.Attachments.Add("12345.txt", Encoding.ASCII.GetBytes(xmltext), new ContentType("text", "plain"));
message.Body = builder.ToMessageBody();
The Add method actually returns the MimeEntity that it creates, allowing you to make changes to it.
To force the encoding to base64, for example, you can do this:
var attachment = (MimePart) builder.Attachments.Add("12345.txt", Encoding.ASCII.GetBytes(xmltext), new ContentType("text", "plain"));
attachment.ContentTransferEncoding = ContentENcoding.Base64;

HTML to PDF conversion using Aspose

I am new to Aspose but I have successfully converted several file formats into PDF's but I am struck with HTML to PDF conversion. I am able to convert a HTML file into a PDF successfully but the CSS part is not rendering into the generated PDF. Any idea on this? I saved www.google.com as my input HTML file. Here is my controller code.
using Aspose.Pdf.Generator
Pdf pdf = new Pdf();
pdf.HtmlInfo.CharSet = "UTF-8";
Section section = pdf.Sections.Add();
StreamReader r = File.OpenText(#"Local HTML File Path");
Text text2 = new Aspose.Pdf.Generator.Text(section, r.ReadToEnd());
pdf.HtmlInfo.ExternalResourcesBasePath = "Local HTML File Path";
text2.IsHtmlTagSupported = true;
text2.IsFitToPage = true;
section.Paragraphs.Add(text2);
pdf.Save(#"Generated PDF File Path");
Am i missing something? Any kind of help is greatly appreciated.
Thanks
My name is Tilal Ahmad and I am developer evangelist at Aspose.
Please use new DOM approach(Aspose.Pdf.Document) for HTML to PDF conversion. In this approach to render external resources(CSS/Images/Fonts) you need to pass resources path to HtmlLoadOptions() method. Please check following documentation links for the purpose.
Convert HTML to PDF (new DOM)
HtmlLoadOptions options = new HtmlLoadOptions(resourcesPath);
Document pdfDocument = new Document(inputPath, options);
pdfDocument.Save("outputPath");
Convert Webpage to PDF(new DOM)
// Create a request for the URL.
WebRequest request = WebRequest.Create("https:// En.wikipedia.org/wiki/Main_Page");
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Time out in miliseconds before the request times out
// Request.Timeout = 100;
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// 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();
reader.Close();
dataStream.Close();
response.Close();
MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(responseFromServer));
HtmlLoadOptions options = new HtmlLoadOptions("https:// En.wikipedia.org/wiki/");
// Load HTML file
Document pdfDocument = new Document(stream, options);
options.PageInfo.IsLandscape = true;
// Save output as PDF format
pdfDocument.Save(outputPath);
Try using media attribute in each style tag
<style media="print">
and then provide the html file to your Aspose.Pdf Generator.
Try this.. This is working nice for me
var license = new Aspose.Pdf.License();
license.SetLicense("Aspose.Pdf.lic");
var license = new Aspose.Html.License();
license.SetLicense("Aspose.Html.lic");
using (MemoryStream memoryStream = new MemoryStream())
{
var options = new PdfRenderingOptions();
using (PdfDevice pdfDevice = new PdfDevice(options, memoryStream))
{
using (var renderer = new HtmlRenderer())
{
using (HTMLDocument htmlDocument = new HTMLDocument(content, ""))
{
renderer.Render(pdfDevice, htmlDocument);
//Save memoryStream into output pdf file
}
}
}
}
content is string type which is my html content.

How to parse the output from the web service which gives out JSON as output format. And I am using REST

How do I parse the output i.e., responseText?
var httpResponse = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
//read response
var responseText = streamReader.ReadToEnd();
return responseText;
}
And, I know that string is the return type which I have specified as mentioned below.
public string InvokeRequest(RESTInvokeClass objInvoke)
I think the complete output(some 100 lines) which is in the JSON format is completely displaying as a single string stopping me to parse the output.
My question is:
How to receive the output so that I can parse through it?
If you just want to serialize the reponse text to an object that you can traverse through, you can do something like:
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
var riClass = jsSerializer.DeserializeObject(responseText);
foreach(var item in riClass)
{
//Do something with this item
}

Obtaining changed Lines from Difference.DiffFiles C#

Currently I am trying to obtain the number of changed lines between two version of a source files, I currently do this by splitting the string I get from the Streamwriter.
var rev1 = new DiffItemVersionedFile(versionControl, path, VersionSpec.ParseSingleSpec(latestVersion, null));
var rev2 = new DiffItemVersionedFile(versionControl, path, VersionSpec.ParseSingleSpec(previousVersion, null));
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
{
var options = new DiffOptions();
options.Flags = DiffOptionFlags.EnablePreambleHandling;
options.OutputType = DiffOutputType.Unified;
options.TargetEncoding = Encoding.UTF8;
options.SourceEncoding = Encoding.UTF8;
options.StreamWriter = writer;
Difference.DiffFiles(versionControl, rev1, rev2, options, path, true);
writer.Flush();
var diff = Encoding.UTF8.GetString(stream.ToArray());
}
That's what I'm currently obtaining from the Stream, formating
looks a bit awkward, but there should be a more easy way to do this, since there usally is a structured object behind thats accesable.
$/MainProject/Development/Client/SubFolder1/SubFolder2/interface/uEPagesShopInterfaceVariantenVorlagen.pas
CodeLines
## -994,7 +995,7 ##
moreCode
deletedLine
addedLine
more code
## -1692,6 +1693,8 ##
some code
addedLine
addedLine
some more code
May be this is what you are looking for:
http://www.codeproject.com/Articles/6943/A-Generic-Reusable-Diff-Algorithm-in-C-II

Consuming WordPress RSS Feed In ASP.NET

How do I consume my WordPress blog's RSS feed to display my latest blog posts on my homepage? I ran into the following piece of code to do this:
Function GetRSSFeed(strURL as String) as DataTable
'Get the XML data
Dim reader as XmlTextReader = New XmlTextReader(strURL)
'return a new DataSet
Dim ds as DataSet = New DataSet()
ds.ReadXml(reader)
Return ds.Tables(2)
End Function
But it errors out at this line: 'ds.ReadXml(reader)' with the following error:
A column named 'comments' already belongs to this DataTable.
Perhaps it doesn't work since this code is from 2003? Does anyone have a working code sample? Many thanks in advance!
You can use LINQ to XML to read a WordPress RSS feed.
First get the feed. Make a Uri instance out of it.
var rssFeed = new Uri("https://github.com/geersch/feed/");
Then perform a GET request.
var request = (HttpWebRequest) WebRequest.Create(rssFeed);
request.Method = "GET";
var response = (HttpWebResponse) request.GetResponse();
Get the response stream and read it to download the contents of the feed.
using (var reader = new StreamReader(response.GetResponseStream()))
{
var feedContents = reader.ReadToEnd();
//...
}
Still within the above using statement use LINQ to XML to parse the downloaded content and extract the information you need.
var document = XDocument.Parse(feedContents);
var posts = (from p in document.Descendants("item")
select new
{
Title = p.Element("title").Value,
Link = p.Element("link").Value,
Comments = p.Element("comments").Value,
PubDate = DateTime.Parse(p.Element("pubDate").Value)
}).ToList();
Now you can iterate over the results.
foreach(var post in posts)
{
Console.WriteLine(post.Title);
Console.WriteLine(post.Link);
Console.WriteLine(post.Comments);
Console.WriteLine(post.PubDate);
}
Here I just used an anonymous type to capture the output in, but feel free to create your own BlogPost class or something similar which you can use in the LINQ query.
I'm used to C#, so that's why I've used it in my reply. But you can easily convert it. There are some online converters which you can use.
Regarding your issue with the DataSet (which I personally would not use to implement this), it is caused by an item (blog post) having nodes with the same name.
For example:
<comments>...</comments>
<slash:comments>5</slash:comments>
Sure the second one has a different namespace (slash), but DataSet's ReadXml(...) method does not care about namespaces. It tries to create a second column named "comments". That is why you get the exception.
You can still use a DataSet / DataTable if you want to. Just extract the data from the feed using LINQ to XML as shown above.
Then create a DataSet and add a new table to it.
var dataSet = new DataSet();
var blog = new DataTable("Blog");
blog.Columns.Add("Title", typeof(string));
blog.Columns.Add("Link", typeof(string));
blog.Columns.Add("Comments", typeof(string));
dataSet.Tables.Add(blog);
Iterate over the extracted data and add it to the DataTable:
foreach (var post in posts)
{
var newRow = blog.NewRow();
newRow["Title"] = post.Title;
newRow["Link"] = post.Link;
newRow["Comments"] = post.Comments;
blog.Rows.Add(newRow);
}
Voila, we've now fixed your issue by no longer relying on the DataSet's ReadXml(...) method. Download the feed, extract the data you are interested in and persist it.
I would start in the System.ServiceModel.Syndication namespace, there are classes to directly manipulate RSS feeds. In particular, this looks promising:
XmlReader reader = XmlReader.Create("http://your.uri.here/feed.xml");
SyndicationFeed feed = SyndicationFeed.Load(reader);
Then explore the SyndicationFeed class, in particular the Items collection should contain the RSS entries.
I'd start off with the built in classes for RSS/Atom: SyndicationFeed
using (XmlReader reader = XmlReader.Create(url))
{
return SyndicationFeed.Load(reader);
}
This is simply #Christophe Geers's great solution converted to VB, as a function:
Protected Function getWordPressFeed(ByVal strUrl As String) As DataTable
Dim rssFeed = New Uri(strUrl)
Dim request = DirectCast(WebRequest.Create(rssFeed), HttpWebRequest)
request.Method = "GET"
Dim response = DirectCast(request.GetResponse(), HttpWebResponse)
Dim feedContents As String
Using reader = New StreamReader(response.GetResponseStream())
feedContents = reader.ReadToEnd()
End Using
Dim document = XDocument.Parse(feedContents)
Static Dim dcNamespace As XNamespace
dcNamespace = "http://purl.org/dc/elements/1.1/"
Dim posts = (From p In document.Descendants("item") Select New With { _
Key .Title = p.Element("title").Value, _
Key .Link = p.Element("link").Value, _
Key .Author = p.Element(dcNamespace + "creator").Value, _
Key .Description = p.Element("description").Value, _
Key .PubDate = DateTime.Parse(p.Element("pubDate").Value) _
}).ToList()
Dim dataSet = New DataSet()
Dim blog = New DataTable("Blog")
blog.Columns.Add("Title", GetType(String))
blog.Columns.Add("Link", GetType(String))
blog.Columns.Add("Description", GetType(String))
blog.Columns.Add("Author", GetType(String))
blog.Columns.Add("PubDate", GetType(DateTime))
dataSet.Tables.Add(blog)
For Each post In posts
Dim newRow = blog.NewRow()
newRow("Title") = post.Title
newRow("Link") = post.Link
newRow("Description") = post.Description
newRow("Author") = post.Author
newRow("PubDate") = post.PubDate
blog.Rows.Add(newRow)
Next
Return blog
End Function
This is what I use for my wordpress feed reader.
private async void ReadFeed() {
var rssFeed = new Uri("http://truestrengthmd.com/category/blog/feed");
var request = (HttpWebRequest)WebRequest.Create(rssFeed);
request.Method = "GET";
var _response = await request.GetResponseAsync();
var response = (HttpWebResponse)_response;
using (var reader = new StreamReader(response.GetResponseStream()))
{
var feedContents = reader.ReadToEnd();
var document = XDocument.Parse(feedContents);
var posts = (from p in document.Descendants("item")
select new
{
Title = p.Element("title").Value
}).ToList();
foreach (var post in posts)
{
Debug.WriteLine(post.Title);
}
}
}
You can use my Library for this: wprssapi.marcogriep.de
Just a few lines of code. Very easy to do:
//Get an Instance of Wordpress Controller (Singleton)
WordPressFeedController wp = WordPressFeedController.Instance;
//Load all the RSS Articles
wp.LoadRSS("http://www.its-all-about.de/rss");
//Get the Newest Article (Check Docs for other functions)
var rssItem = wp.GetNewestItem();
this.label1.Text = rssItem.Title;
//Text Only, Remove all the HTML Tags - Limit too 300 Chars
this.richTextBox1.Text = wp.RemoveHTMLFromText(rssItem.Summary.Substring(0, 300)) + "...";
//Open RSS Article on Button Click
this.button1.Click += (s, e) => {
Process.Start(rssItem.Id);
};

Categories