List XML Serialization - c#

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?

Related

Why does media source not work with Safefilenames?

I want to add filenames (without the full path) to the ListBox.
The code below is working smoothly, but when when I change FileNames to SafeFileNames (for hiding item location) it's not working anymore.
XAML
<MediaElement x:Name="mePlayer" Margin="64,0,90,61"/>
<ListBox x:Name="listbox4" Background="Salmon" BorderBrush="Black" BorderThickness="3"/>
CS
private void load_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
ofd.DefaultExt = ".mp3";
ofd.Filter = "All|*.*";
ofd.Multiselect = true;
Nullable<bool> result = ofd.ShowDialog();
if (result == true)
{
for (int i = 0; i < ofd.FileNames.Length; i++)
{
listbox4.Items.Add(ofd.FileNames[i].ToString());
listbox4.SelectedItem = ofd.FileName;
mePlayer.Source = new Uri(
listbox4.SelectedItem.ToString(),
UriKind.RelativeOrAbsolute);
mePlayer.LoadedBehavior = MediaState.Play;
}
}
}
This code should work for you. Please read the comments in the code before you proceed.
private Dictionary<string, string> fileDictionary = new Dictionary<string, string>();
private void load_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
ofd.DefaultExt = ".mp3";
ofd.Filter = "All|*.*";
ofd.Multiselect = true;
Nullable<bool> result = ofd.ShowDialog();
if (result == true)
{
for (int i = 0; i < ofd.FileNames.Length; i++)
{
var filePath = ofd.FileNames[i];
var fileName = System.IO.Path.GetFileName(filePath);
fileDictionary.Add(fileName, filePath);
// not sure about this logic. You may need to reconsider what you are trying to do here.
//Instead of doing this, create a click event for the list box and get the selected file path to be played from the dictionary.
listbox4.Items.Add(fileName);
}
}
}
private void listbox4_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (listbox4.SelectedItem != null)
{
var selectedFile = listbox4.SelectedItem.ToString();
string selectedFilePath;
fileDictionary.TryGetValue(selectedFile, out selectedFilePath);
if (!string.IsNullOrEmpty(selectedFilePath))
{
mePlayer.Source = new Uri(selectedFilePath, UriKind.RelativeOrAbsolute);
mePlayer.LoadedBehavior = MediaState.Play;
}
}
}

Load JSON File to ListBox and TextBox C#

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 have a query about checked list boxes in c#

I have set up a program that so far can browse for the location of a file that possesses data in a text file holding the locations of other files which then shows me if they exist, are missing or are a duplicate inside listboxes. The next step is to enable the user to select files in the checked list boxes and being given the option to either move or copy. I have already made buttons which allow this but I want to be able to use them for the checked boxes I the list boxes.(p.s) please ignore any comments I have made in the code they are just previous attempts of doing other things in the code.
My code so far:
namespace File_existence
{
public partial class fileForm : Form
{
private string _filelistlocation;
public fileForm()
{
InitializeComponent();
}
private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
public void fileForm_Load(object sender, System.EventArgs e)
{
_filelistlocation = textBox1.Text;
}
private void button1_Click(object sender, System.EventArgs e)
{
//GetDuplicates();
checkedListBox1.Items.Clear();
listBox2.Items.Clear();
ReadFromList();
}
private void GetDuplicates()
{
DirectoryInfo directoryToCheck = new DirectoryInfo(#"C:\\temp");
FileInfo[] files = directoryToCheck.GetFiles("*.*", SearchOption.AllDirectories);
var duplicates = files.GroupBy(x => x.Name)
.Where(group => group.Count() > 1)
.Select(group => group.Key);
if (duplicates.Count() > 0)
{
MessageBox.Show("The file exists");
FileStream s2 = new FileStream(_filelistlocation, FileMode.Open, FileAccess.Read, FileShare.Read);
// open _filelistlocation
// foreach line in _filelistlocation
// concatenate pat hand filename
//
}
}
public void ReadFromList()
{
int lineCounter = 0;
int badlineCounter = 0;
using (StreamReader sr = new StreamReader(_filelistlocation))
{
String line;
while ((line = sr.ReadLine()) != null)
{
string[] values = line.Split('\t');
if (values.Length == 2)
{
string fullpath = string.Concat(values[1], "\\", values[0]);
if (File.Exists(fullpath))
checkedListBox1.Items.Add(fullpath);
else
listBox2.Items.Add(fullpath);
++lineCounter;
}
else
++badlineCounter;
//Console.WriteLine(line);
}
}
}
//StreamReader files= new StreamReader(File)();
private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
}
private void button2_Click(object sender, System.EventArgs e)
{
FolderBrowserDialog folderBrowserDlg = new FolderBrowserDialog();
folderBrowserDlg.ShowNewFolderButton = true;
DialogResult dlgResult = folderBrowserDlg.ShowDialog();
if (dlgResult.Equals(DialogResult.OK))
{
textBox1.Text = folderBrowserDlg.SelectedPath;
Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
}
try
{
string fileName = "filetest1.txt";
string sourcePath = #"C:\Temp\Trade files\removed";
string targetPath = #"C:\Temp\Trade files\queued";
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath,fileName);
System.IO.File.Copy(sourceFile, destFile, true);
}
catch (IOException exc)
{
MessageBox.Show(exc.Message);
}
}
private void button3_Click(object sender, System.EventArgs e)
{
try
{
string sourceFile = #"C:\Temp\Trade Files\queued\filetest1.txt";
string destinationFile = #"C:\Temp\Trade Files\processed\filetest1.txt";
System.IO.File.Move(sourceFile, destinationFile);
}
catch(IOException ex){
MessageBox.Show(ex.Message);//"File not found"
}
}
private void button4_Click(object sender, System.EventArgs e)
{
OpenFileDialog fileBrowserDlg = new OpenFileDialog();
//folderBrowserDlg.ShowNewFolderButton = true;
//folderBrowserDlg.SelectedPath = _filelistlocation;
fileBrowserDlg.FileName = textBox1.Text;
DialogResult dlgResult = fileBrowserDlg.ShowDialog();
if (dlgResult.Equals(DialogResult.OK))
{
textBox1.Text = fileBrowserDlg.FileName;
File_existence.Properties.Settings.Default.Save();
// Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
}
}
private void button5_Click(object sender, System.EventArgs e)
{
if (!textBox1.Text.Equals(String.Empty))
{
if (System.IO.Directory.GetFiles(textBox1.Text).Length > 0)
{
foreach (string file in System.IO.Directory.GetFiles(textBox1.Text))
{
checkedListBox1.Items.Add(file);
}
}
else
{
checkedListBox1.Items.Add(String.Format("No file found: {0}", textBox1.Text));
}
}
}
}
}
The task I need to do is that the files that appear in the checked list box need to usually be moved or copied to another directory. That is fine as I can already do that with what I have coded, but what it does is it will move or copy all of the files in the checked list box. What I want to do is enable the user to only be able to select which files they what to move or copy through checking the checked list box so that only those files will be moved or copied.
EDIT: Could it be checkedListBox.checked items?

Unable to attribute button to XSLT Transformation (C#)

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";

how to pass file path to a variable using openfiledialog control?

I have this code here which i use in order to upload some stuff in a windows form:
public Form1()
{
InitializeComponent();
}
private void btnLoad_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
System.Windows.Forms.DialogResult dr = ofd.ShowDialog();
if (dr == DialogResult.OK)
{
userSelectedFilePath = ofd.FileName;
}
}
public string userSelectedFilePath
{
get
{ return tbFilePath.Text;
}
set
{tbFilePath.Text = value;
}
}
private void btn_compare_Click(object sender, EventArgs e)
{
string Xml1 = tbFilePath.Text;
string Xml2 = System.IO.File.ReadAllText(#"C:");
compare.comparison(Xml1, Xml2);
}
Apparently i'm doing something wrong because i'm not passing the tbFilePath.Text which i need when i have: string Xml1 = tbFilePath.Text;
What is it?
What you probably want is to compare the contents of 2 files.
As siride said your code does not make sense(see his comment)
Add this method to your class
private string FindFile()
{
OpenFileDialog ofd = new OpenFileDialog();
string _xmlPath1 = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
System.Windows.Forms.DialogResult dr = ofd.ShowDialog();
if (dr == DialogResult.OK)
return ofd.FileName;
else
return null;
}
And then you can do this:
private void btn_compare_Click(object sender, EventArgs e)
{
string x1 = System.IO.File.ReadAllText(FindFile(), Encoding.UTF8);
string x2 = System.IO.File.ReadAllText(FindFile(), Encoding.UTF8);
//Or if you already have the second file
//string x2 = System.IO.File.ReadAllText(#"C:\YourPath\someFileName.xml", Encoding.UTF8);
compare.comparison(x1, x2);
}

Categories

Resources