I am attempting to create an interface that allows me to select 3 XSLT files and merge them together to then be transformed using an XML. I have a working transformation code I am creating a user interface for.
Transformation code:
public static void Transform(string sXmlPath, string sXslPathBody, string sXslPathHead, string sXslPathFoot, string sXslPathMerged)
{
try
{
XNamespace ns = "http://www.w3.org/1999/XSL/Transform";
//load Xml
XPathDocument myXPathDoc = new XPathDocument(sXmlPath);
//Load Body
XElement xslt = XElement.Load(sXslPathBody);
//Add Code To Body
xslt.AddFirst(new XElement(ns + "include", new XAttribute("href", sXslPathFoot)));
xslt.AddFirst(new XElement(ns + "include", new XAttribute("href", sXslPathHead)));
XElement body = xslt.Descendants("body").Single();
body.AddFirst(new XElement(ns + "call-template", new XAttribute("name", "Header")));
body.Add(new XElement(ns + "call-template", new XAttribute("name", "Footer")));
//Save Combined File
//XElement.Save("c:\temp.xlst");
xslt.Save(sXslPathMerged);
XslCompiledTransform myXslTrans = new XslCompiledTransform();
//load Combined File
myXslTrans.Load(sXslPathMerged);
//Merge XML with Combined File
XmlTextWriter myWriter = new XmlTextWriter ("result.html", null);
//transform Xml
myXslTrans.Transform(myXPathDoc, null, myWriter);
myWriter.Close();
}
catch (Exception e)
{
Console.WriteLine("Exception: {0}", e.ToString());
}
}
The Transformation code works fine however I am trying to set each stage to a button which will allow me to select any 3 XSLT files I wish, as well as any XML I wish. Then a button to merge the 3 XSLT files together & create a HTML output.
Code:
public partial class Form1 : Form
{
String HeadFileSelected, BodyFileSelected, FootFileSelected, XmlFileSelected, MergeFiles;
public Form1()
{
InitializeComponent();
}
//Head
private void openFileHead_FileOk(object sender, CancelEventArgs e)
{
}
private void header_Click(object sender, System.EventArgs e)
{
if (openFileHead.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
HeadFileSelected = openFileHead.FileName;
string filename = HeadFileSelected;
textBox2.Text = HeadFileSelected;
}
}
//Body
private void openFileBody_FileOk(object sender, CancelEventArgs e)
{
}
private void body_Click(object sender, System.EventArgs e)
{
if (openFileBody.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
BodyFileSelected = openFileBody.FileName;
string filename = BodyFileSelected;
textBox3.Text = BodyFileSelected;
}
}
//Foot
private void openFileFooter_FileOk(object sender, CancelEventArgs e)
{
}
private void footer_Click(object sender, System.EventArgs e)
{
if (openFileFooter.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
FootFileSelected = openFileFooter.FileName;
string filename = FootFileSelected;
textBox4.Text = FootFileSelected;
}
}
//Xml
private void openFileXml_FileOk(object sender, CancelEventArgs e)
{
}
private void xml_Click(object sender, System.EventArgs e)
{
if (openFileXml.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
XmlFileSelected = openFileXml.FileName;
}
}
//Merge
private void openFileMerge_FileOk(object sender, CancelEventArgs e)
{
}
private void merge_Click(object sender, EventArgs e)
{
//XmlTransformUtil objXMLTrans = new XmlTransformUtil();
XmlTransformUtil.Transform(XmlFileSelected, BodyFileSelected, HeadFileSelected, FootFileSelected, MergeFiles);
}
}
I have managed to get the XML selection & the 3 XSLT selections to work fine it's just the Merge button that is not working as I cannot attribute the String MergeFiles; to Transform(string sXslPathMerged)
I understand why it does not work but I don't now the solution that will give me the result I need.
Managed to figure it out, I needed to define MergeFiles as the saved XSLT which wasn't going anywhere because it was null. Did it by adding the following in my form.
MergeFiles = "C:\\Users\\user\\Desktop\\TEMP.xslt";
Related
How can I delete from a text file in Winforms?
My aim is to delete a selected text from a text box and it can also be deleted in my text file.
Specifically, my need is that if the user delete the text from a text box it also be deleted from text file.
My code is:
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog of = new OpenFileDialog();
of.ShowDialog();
textBox1.Text = of.FileName;
}
private void button2_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader(textBox1.Text);
textBox2.Text = sr.ReadToEnd();
sr.Close();
}
private void button3_Click(object sender, EventArgs e)
{
StreamWriter sw = new StreamWriter(textBox1.Text, true);
sw.WriteLine(textBox2.Text);
sw.Close();
}
private void button4_Click(object sender, EventArgs e)
{
textBox2.SelectedText = "";
string selectedText = "theTextYouWantToDelete";
string fileContent = File.ReadAllText(#"C:\demo\demo.txt");
File.WriteAllText(#"C:\demo\demo.txt",
fileContent.Replace(selectedText, ""));
}
private bool SelectedText(char arg)
{
throw new NotImplementedException();
}
}
As far as I understand it, you should simply be able to write
private void button4_Click(object sender, EventArgs e) {
File.WriteAllText(#"C:\demo.txt", textBox2.Text, ""));
}
This will replace the contents of your file with the current contents of the textbox. Assuming the user has already deleted the needed text from the textbox, it should work correctly.
See the documentation for File.WriteAllText fore more info.
This will replace the selectedText with an empty string
string selectedText = textBox2.Text;
string fileContent = File.ReadAllText(#"C:\demo.txt");
File.WriteAllText(#"C:\demo.txt", fileContent.Replace(selectedText, ""));
I am learning to program in C # so my question is how to call the method from the button3
Look for information on the web but it is not very clear to me why I turn to this site
private void button3_Click_1(object sender, EventArgs e)
{
}
private void export2File(ListView lv, string splitter)
{
string filename = "";
SaveFileDialog sfd = new SaveFileDialog();
sfd.Title = "SaveFileDialog Export2File";
sfd.Filter = "Text File (.txt) | *.txt";
if (sfd.ShowDialog() == DialogResult.OK)
{
filename = sfd.FileName.ToString();
if (filename != "")
{
using (StreamWriter sw = new StreamWriter(filename))
{
foreach (ListViewItem item in lv.Items)
{
sw.WriteLine("{0}{1}{2}", item.SubItems[0].Text, splitter, item.SubItems[1].Text);
}
}
}
}
}
private void button3_Click_1(object sender, EventArgs e)
{
ListView listView1 = new ListView();
string splitter = ",";
export2File(listview1, splitter);
}
You need to pass a reference to the ListView on your Form, and the desired "splitter" into the method. Assuming listView1 and a comma:
private void button3_Click_1(object sender, EventArgs e)
{
export2File(listView1, ",");
}
I'm working on a Windows Form Application. Textbox index can be saved and shown as in ListBox with this code:
private List<FunctionData> funcParamList = new List<FunctionData>();
...
private void addFuncButton_Click(object sender, EventArgs e)
{
FunctionData funcParams = new FunctionData();
funcParams.blabla1name = blabla1.Text;
funcParams.blabla2name = blabla2.Text;
...
if (funcParams.isValid())
{
funcParamList.Add(funcParams);
functionListBox.Items.Add(functionNameBox.Text);
}
Also I collect objects to TextBox again to edit (by clicking ListBox item) with the following code :
private void getParams(FunctionData data)
{
blabla1.Text = data.blabla1name;
blabla2.Text = data.blabla2name;
functionNameBox.Text = data.functionName;
return;
}
private void functionListBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (functionListBox.SelectedItem == null) { return; }
foreach (var obj in funcParamList)
{
if (obj.functionName == functionListBox.SelectedItem.ToString())
{
getParams(obj);
}
}
}
And save them to file as JSON with:
private void saveFileButton_Click(object sender, EventArgs e)
{
fileName = fileNameBox.Text;
string jsonFunc = JsonConvert.SerializeObject(funcParamList);
System.IO.File.WriteAllText(#"<blablapath>\" + fileName + ".txt", jsonFunc);
}
There's 'functionName' object in JSON file that I can use it for showing on ListBox.
My question is: How can I load this file buy Native Load/Open File Dialog and show the objects in ListBox and can edit them again?
And here how I've tried to make it with the following code, but it doesn't work:
private void loadFileButton_Click(object sender, EventArgs e)
{
OpenFileDialog loadFileDialog = new OpenFileDialog();
...
if (loadFileDialog.ShowDialog() == DialogResult.OK)
{
string jsonFileName = loadFileDialog.FileName;
string jsonFile = File.ReadAllText(jsonFileName);
dynamic loadedFile = JsonConvert.DeserializeObject(jsonFile);
//if (functionListBox.SelectedItem == null) { return; }
foreach (var obj in loadedFile)
{
if (obj.functionName != null)
{
functionListBox.Items.Add(obj.functionName);
getParams(obj); // I get exception here
funcParamList.Add(loadedFile);
functionListBox.Refresh();
}
}
}
I've solved the problem by casting 'DeserializeObject' as List and it's done. Here the changes:
...
var loadedFile = JsonConvert.DeserializeObject<List<FunctionData>>(jsonFile);
I am loading a local HTML page using the WebBrowser control.
namespace ConfigEditorWinForms
{
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public partial class ConfigEditorForm : Form
{
String _currentConfigFilePath = null;
public ConfigEditorForm()
{
Load += new EventHandler(ConfigEditorForm_Load);
InitializeComponent();
}
private void ConfigEditorForm_Load(object sender, EventArgs e)
{
webBrowser1.AllowWebBrowserDrop = true;
webBrowser1.IsWebBrowserContextMenuEnabled = false;
webBrowser1.WebBrowserShortcutsEnabled = false;
webBrowser1.ObjectForScripting = this;
//webBrowser1.ScriptErrorsSuppressed = true;
webBrowser1.DocumentCompleted +=
new WebBrowserDocumentCompletedEventHandler(OnDocumentCompleted);
string curDir = Directory.GetCurrentDirectory();
webBrowser1.Url = new Uri(String.Format("file:///{0}/ConfigEditor/ConfigEditor.html", curDir));
}
private void OnDocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
MessageBox.Show("Document completed");
}
public string GetFileContents(String path)
{
return System.IO.File.ReadAllText(path);
}
public void SaveFileContents(String path, String contents)
{
System.IO.File.WriteAllText(path, contents);
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
openFileDialog.InitialDirectory = #"XXX";
openFileDialog.FilterIndex = 1;
openFileDialog.RestoreDirectory = false;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
HtmlDocument doc = webBrowser1.Document;
HtmlElement fileToOpenInput = doc.GetElementById("fileToOpenInput");
fileToOpenInput.InvokeMember("onchange", new object[1] { openFileDialog.FileName });
_currentConfigFilePath = openFileDialog.FileName;
}
}
}
}
On my computer :
The document completed event is fired twice
Opening a file from the menu works fine too
On another computer :
The document completed event is only fired (ONCE) when the executable is run as administrator
Document.Body is null and Document.GetElementById returns null too, despite the document completed event being fired several seconds before.
What's going on please ?
Thank you. :)
I create a list where the user creates an object which will be added to the list.
private List<Tool> toolList = new List<Tool>();
private void buttonAdd_Click(object sender, RoutedEventArgs e)
{
InputDialog input = new InputDialog();
input.ShowDialog();
inputNewTool = input.enteredTxt;
if (inputNewTool != null)
{
System.Windows.Forms.MessageBox.Show("Chose the Tool's directory");
dlg.DefaultExt = ".exe";
dlg.Filter = "Application (.exe)|*.exe";
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Tool tool = new Tool();
tool.Name = inputNewTool;
tool.Path = dlg.FileName;
toolList.Add(tool);
comboBoxTools.Items.Add(tool.Name);
}
}
Prior to this the application draws up a folder with a XML File:
private void buttonCreate_Click(object sender, RoutedEventArgs e)
{
DialogResult result = folderElg.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
textBoxPath.Text = folderElg.SelectedPath;
userConfigurePath = folderElg.SelectedPath;
}
XmlDocument toolConfig = new XmlDocument();
XmlNode myRoot;
myRoot = toolConfig.CreateElement("Tool");
toolConfig.AppendChild(myRoot);
toolConfig.Save(#userConfigurePath + "\\config.xml");
}
If the user creates multiple objects they are in the list. That I verified. These objects should be serialized:
private void Window_Closed(object sender, EventArgs e)
{
foreach (Tool t in toolList)
{
XmlSerializer serializer = new XmlSerializer(t.GetType(), new
XmlRootAttribute("Tools"));
using (var writer = new StreamWriter(#Start.userConfigurePath +
"\\config.xml"))
{
serializer.Serialize(writer.BaseStream, t);
writer.Close();
}
}
}
No matter how many objects are in the list in the XML File is only the last object serialized:
<?xml version="1.0"?>
<Tool xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Name>zest6</Name>
<Path>C:\Program Files\FreePDF_XP\fpsetup.exe</Path>
</Tool>
Why the last serialized objects overwrites the others?