How can I see the XML output of following C# code? I can see that it uses XElement, but where I can locate the XML file or the output?
private void Form1_Load(object sender, EventArgs e)
{
XElement doc = new XElement("searchresults"); // root element
//create
XElement result = new XElement("result",
new XElement("Resulthead", "AltaVista"),
new XElement("ResultURL", "www.altavista.com/"),
new XElement("Description", "AltaVista provides the most comprehensive search experience on the Web! ... "),
new XElement("DisplayURL", "www.altavista.com/")
);
doc.Add(result);
//add another search result
result = new XElement("result",
new XElement("Resulthead", "Dogpile Web Search"),
new XElement("ResultURL", "www.dogpile.com/"),
new XElement("Description", "All the best search engines piled into one. All the best search engines piled into one."),
new XElement("DisplayURL", "www.dogpile.com/")
);
doc.Add(result);
string xmlString = doc.ToString(SaveOptions.DisableFormatting);
}
Your result only exists inside your "xmlString" variable - it's not being written anywhere, neither onto the console / window, nor into a file.
You'll have to add a
doc.Save(#"C:\your-xml-file-name.xml");
line at the end of your method to save the contents to a file on disk.
Make sure to use a full path, or check in your current directory where the app is running (i.e. in (yourappname)\bin\debug, most likely).
Marc
That code is not writing XML anywhere but memory (the xmlString variable).
You could try calling XElement.Save() and get it on a file:
doc.Save(#"filename.xml");
Or use the debugger and look at the variables.
Or, if you prefer, simply put it in a TextBox:
textBox.Text = xmlString;
Be warned it may not be nicely formatted...
Related
Is there a way to do it? I already tried with monotorrent, but due to the lack of up-to-date documentation i coudn't get it to work. I've already tried this with monotorrent, but still i can't find a way to get the .torrent file or even start the download to get the .torrent ...
The following piece of code was made that question as base, but it doesn't save anything to "D:\A" or to "D:\TorrentSave"
private void GerarTorrent(string magnet)
{
MonoTorrent.Client.TorrentManager b = new MonoTorrent.Client.TorrentManager(new MonoTorrent.MagnetLink(magnet), "D:\\A", new MonoTorrent.Client.TorrentSettings(), "D:\\TorrentSave");
MonoTorrent.Client.EngineSettings engineSettings = new MonoTorrent.Client.EngineSettings();
MonoTorrent.Client.ClientEngine clientEngine = new MonoTorrent.Client.ClientEngine(engineSettings);
clientEngine.Register(b);
clientEngine.StartAll();
b.Start();
}
To generate the .torrent, it doesn't have to be monotorrent, in fact the only usage of this api would be for that, generating .torrent files from a magnet link...
EDIT: Updated code with my attempt on doing what Fᴀʀʜᴀɴ Aɴᴀᴍ said:
private void GerarTorrent(string hash)
{
MonoTorrent.Client.TorrentManager b = new MonoTorrent.Client.TorrentManager(MonoTorrent.InfoHash.FromHex(hash), "D:\\A", new MonoTorrent.Client.TorrentSettings(), "D:\\TorrentSave", new List<List<string>>());
MonoTorrent.Client.EngineSettings engineSettings = new MonoTorrent.Client.EngineSettings();
MonoTorrent.Client.ClientEngine clientEngine = new MonoTorrent.Client.ClientEngine(engineSettings);
clientEngine.Register(b);
clientEngine.StartAll();
b.Start();
}
Hash used = "5FC86BA08451CF4221E0091F31AF1A52C2219009"
You need to pass only the hash and not the entire magnet link to the TorrentManager constructor.
A magnet link looks like this:
magnet:?xt=urn:btih:18981bc9759950b4715ad46adcaf514e6a773cfe
So, a more generalized form:
magnet:?xt=urn:btih:<hash>
You need to extract this <hash> and pass it to the constructor:
manager = new TorrentManager(InfoHash.FromHex(hash), downloadsPath, torrentDefaults, downloadsPathForTorrent, new List<List<string>>());
I have the following code which tries to read data from a text file (so users can modify easily) and auto format a paragraph based on a the words in the text document plus variables in the form. I have the file "body" going into a field. my body text file has the following data in it
"contents: " + contents
I was hoping based on that to get
contents: Item 1, 2, etc.
based on my input. I only get exactly whats in the text doc despite putting "". What am I doing wrong? I was hoping to get variables in addition to my text.
string readSettings(string name)
{
string path = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "/Yuneec_Repair_Inv";
try
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader(path + "/" + name + ".txt"))
{
string data = sr.ReadToEnd();
return data;
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The settings file for " + name + " could not be read:");
Console.WriteLine(e.Message);
string content = "error";
return content;
}
}
private void Form1_Load(object sender, EventArgs e)
{
createSettings("Email");
createSettings("Subject");
createSettings("Body");
yuneecEmail = readSettings("Email");
subject = readSettings("Subject");
body = readSettings("Body");
}
private void button2_Click(object sender, EventArgs e)
{
bodyTextBox.Text = body;
}
If you want to provide the ability for your users to customize certain parts of the text you should use some "indicator" that you know before hand, that can be searched and parsed out, something like everything in between # and # is something you will read as a string.
Hello #Mr Douglas#,
Today is #DayOfTheWeek#.....
At that point your user can replace whatever they need in between the # and # symbols and you read that (for example using Regular Expressions) and use that as your "variable" text.
Let me know if this is what you are after and I can provide some C# code as an example.
Ok, this is the example code for that:
StreamReader sr = new StreamReader(#"C:\temp\settings.txt");
var set = sr.ReadToEnd();
var settings = new Regex(#"(?<=\[)(.*?)(?=\])").Matches(set);
foreach (var setting in settings)
{
Console.WriteLine("Parameter read from settings file is " + setting);
}
Console.WriteLine("Press any key to finish program...");
Console.ReadKey();
And this is the source of the text file:
Hello [MrReceiver],
This is [User] from [Company] something else, not very versatile using this as an example :)
[Signature]
Hope this helps!
When you read text from a file as a string, you get a string of text, nothing more.
There's no part of the system which assumes it's C#, parses, compiles and executes it in the current scope, casts the result to text and gives you the result of that.
That would be mostly not what people want, and would be a big security risk - the last thing you want is to execute arbitrary code from outside your program with no checks.
If you need a templating engine, you need to build one - e.g. read in the string, process the string looking for keywords, e.g. %content%, then add the data in where they are - or find a template processing library and integrate it.
I am trying to do highlighting on the search results. Here is the relevant part of my code.
QueryScorer scorer = new QueryScorer(q);
Lucene.Net.Search.Highlight.IFormatter formatter = new SimpleHTMLFormatter("<b>", "</b>");
Lucene.Net.Search.Highlight.Highlighter highlighter = new Highlighter(formatter, scorer);
highlighter.TextFragmenter = new SimpleFragmenter(800);
Lucene.Net.Util.Version vers = new Lucene.Net.Util.Version();
vers = Lucene.Net.Util.Version.LUCENE_30;
TokenStream stream = new StandardAnalyzer(vers).TokenStream(string.Empty, new StringReader(text));
string s = string.Empty;
try
{
s = highlighter.GetBestFragments(stream, text, 10, "...");
}
Here, GetBestFragments method throws a System.MissingMethodException.
I have tried to replace the original Lucene.net dll with Lucene.Net.Contrib but this time, I dont know what I should write instead of TokenStream. It doesnt exist in Lucene.Net.Contrib.* dlls.
I am working on existing code and I need to find out how I can rewrite TokenStream class and GetBestFragments method.
Thanx
The problem was something about deployment, that the new compatible Lucene.dll was replaced by the incompatible Sitecore7 dll.
So, if both lucene.net and lucene.net.contrib dll are referenced, it should work.
Not directly the solution to my question, but this source is worth mentioning again. (About lucene.dll versions) : http://laubplusco.net/sitecore-7-lucen-3-0-highlighted-results/
I'm having an issue updating a RichText box on a SharePoint 2010 list.
_batchElement.InnerXml =
string.Format(
"<Method ID='1' Cmd='New'><Field RichText='True' Name='Other_x0020_Items_x0020_of_x0020'>{0}</Field><Field Name='Overall_x0020_rating_x0020_of_x0'>{1}</Field><Field Name='Do_x0020_you_x0020_wish_x0020_to'>{2}</Field></Method>",
add_Report_Details.Rtf,
arrText,
addreportwish);
And the code to trigger the update:
ListService.UpdateListItems(ListName, _batchElement);
But, given that this xml element cannot have anything starting with a \ it doesn't want to work.
I have tried HTML as well, even passing HTML through agility pack, and it just doesn't work either.
What is the proper method or field name or something to update that richtextbox?
do i need a cdata? or something? I'm very confused, and the doco on MSDN isn't that great for this method.
Pass it through an HTML encode, and it seems to work fine:
private static string SetProperHTML(string sHtml)
{
var sb = new StringBuilder();
var stringWriter = new StringWriter(sb);
string input = sHtml;
var test = new HtmlAgilityPack.HtmlDocument();
test.LoadHtml(input);
test.OptionOutputAsXml = false;
test.OptionCheckSyntax = true;
test.OptionFixNestedTags = true;
test.OptionAutoCloseOnEnd = true;
test.OptionWriteEmptyNodes = true;
test.Save(stringWriter);
Console.WriteLine(sb.ToString());
return WebUtility.HtmlEncode(sb.ToString().Replace(Environment.NewLine, ""));
}
Also want to make sure that your field descriptor is setup properly:
_batchElement.InnerXml =
string.Format(
"<Method ID='1' Cmd='New'><Field Name='Other_x0020_Items_x0020_of_x0020'>{0}</Field><Field Name='Overall_x0020_rating_x0020_of_x0'>{1}</Field><Field Name='Do_x0020_you_x0020_wish_x0020_to'>{2}</Field></Method>",
SetProperHTML(add_Report_Details.Document.Body.InnerHtml),
arrText,
addreportwish);
it's a field like any other, no special child tags needed. As long as the Sp2010 field on the form is setup for 100% full HTML, this should work. There are other HTMLEncoders out there, which may be better than the WebUtility but, for the most part, this should work, given Agility Pack is fixing most of the HTML.
I tried to write some code to import a large customization containing 50+ entities. I used the microsoft article 'ImportXmlWithProgress Message (CrmService) as a bases, but was not getting the output I expected.
The 'job.data' in the following code was not changing from the original parameterxml data. So this implies to me that the import was not sucessful. I imported the same compressed importexportxml using the microsoft web ui, and it worked fine. So I'm wondering why my job.data is not being updated with 'result' attributes for each entity that is imported.
Below is my method to import.
private void ImportEntitySchema()
{
const string parameterXml = #"<importexportxml>
<entities>
{0}
</entities>
<nodes/>
<securityroles/>
<settings/>
<workflows/>
</importexportxml>";
var importRequest = new ImportCompressedXmlWithProgressRequest
{
ImportJobId = Guid.NewGuid(),
CompressedCustomizationXml = GetCompressedCustomizationXmlFromEmbeddedResource(),
ParameterXml = string.Format(parameterXml, string.Join("\n", _entitySchemaEntityNames.Select(item => string.Format("<entity>{0}</entity>", item)).ToArray()))
};
try
{
_crmService.Execute(importRequest);
}
catch (Exception e)
{
//Error resulted from import request
}
// Retrieve the results of the import.
XmlNode node;
do
{
Thread.Sleep(2000);
var job = (importjob)_crmService.Retrieve(EntityName.importjob.ToString(), importRequest.ImportJobId, new AllColumns());
var data = new XmlDocument();
data.LoadXml(job.data);
node = data.SelectSingleNode("importexportxml/entities/entity/#result");
} while (node == null);
//code below here never gets executed because the loop continues infinitely
}
I've been looking, but haven't found any/many [useful] examples on the net of the ImportXmlWithProgress being used. Hopefully someone has used it and has an idea of how to get it working.
I remember having trouble with this message, I just can't remember exactly what the trouble was. How big is your import file? We also brewed an import utility for importing our customizations and I use the ImportCompressedAllXmlRequest synchronously (no timeout) on a BackgroundWorker thread. For large amounts of customizations you may have to look at: http://support.microsoft.com/kb/918609. We typically split up our customizations into a bunch of small imports to avoid this.
Should the XPath be "importexportxml/entities/entity[#result]"?