XML.save doesn't update my document - c#

I'm writing a program that will allow users to upload a photo, add a caption, and save their work. When saving, they will be updating an telerik-rotator that has a xml data source
I have the part where the user can upload a photo working. When they upload a photo, it puts the new photo in the images folder. And the telerik control works because Default.aspx has the carousel working.
The part I'm struggling with is allowing the user to update dataSource.xml
Here is my code behind.
protected void submit_Click(object sender, EventArgs e)
{
if(NameInput.Text == "")
{
generalError.Text = "All fields must be completed";
}
try
{
//create variables to replace xml
string photoString = photoDropDown.SelectedItem.Text;
string caption = NameInput.Text.ToString();
string location = HttpContext.Current.Server.MapPath("dataSource.xml");
XmlDocument xml = new XmlDocument();
xml.Load(location);
XmlElement newElement = xml.CreateElement("slide");
newElement.InnerXml = "<image>" + photoString + "</image><text>" + caption + "</text>";
xml.DocumentElement.SelectNodes("/rotator")[0].AppendChild(newElement);
xml.PreserveWhitespace = true;
xml.Save("dataSource.xml");
}
catch (Exception ex)
{
generalError.Text = ex.ToString();
generalError.Visible = true;
return;
}
generalError.Text = "It worked!";
generalError.Visible = true;
}
This throws no errors. So xml.Save is saving something. But it is not appending the new node to the xml document. What am I doing wrong?

Related

Listbox Item holds data

Server 1 Server2 Server Config Screen
I am trying to make a video game server manager and I have run into an issue. I want the user to be able to have as many servers as they would like. However I cannot figure out through google searching and just regular messing around how to store the information that the user selects to become associated with the Server they create in the list. Basically when you make Server1 it takes the info you selected from the boxes on the config screen and uses them on the server selection page. But, when you make Server2, the configuration overwrites Server1's configuration. I know my code isn't even setup to be able to do this but I would appreciate a push in the right direction as to which type of code I should use.
Tl:dr I want config options to be associated with ServerX in the server list and each server should have unique settings.
public partial class Form1 : Form
{
//Variables
string srvName;
string mapSelect;
string difSelect;
public Form1()
{
InitializeComponent();
this.srvList.SelectedIndexChanged += new System.EventHandler(this.srvList_SelectedIndexChanged);
}
private void srvList_SelectedIndexChanged(object sender, EventArgs e)
{
if(srvList.SelectedIndex == -1)
{
dltButton.Visible = false;
}
else
{
dltButton.Visible = true;
}
//Text being displayed to the left of the server listbox
mapLabel1.Text = mapSelect;
difLabel1.Text = difSelect;
}
private void crtButton_Click(object sender, EventArgs e)
{
//Add srvName to srvList
srvName = namBox1.Text;
srvList.Items.Add(srvName);
//Selections
mapSelect = mapBox1.Text;
difSelect = difBox1.Text;
//Write to config file
string[] lines = { mapSelect, difSelect };
System.IO.File.WriteAllLines(#"C:\Users\mlynch\Desktop\Test\Test.txt", lines);
//Clear newPanel form
namBox1.Text = String.Empty;
mapBox1.SelectedIndex = -1;
difBox1.SelectedIndex = -1;
//Return to srvList
newPanel.Visible = false;
}
}
You mentioned in a recent comment that you had tried saving to a .txt file but it overwrote it anytime you tried to make an additional one. If you wanted to continue with your .txt approach, you could simply set a global integer variable and append it to each file you save.
//Variables
string srvName;
string mapSelect;
string difSelect;
int serverNumber = 0;
...
serverNumber++;
string filepath = Path.Combine(#"C:\Users\mlynch\Desktop\Test\Test", serverNumber.ToString(), ".txt");
System.IO.File.WriteAllLines(filepath, lines);
I think below source code will give you some idea about the direction. Let us start with some initializations:
public Form1()
{
InitializeComponent();
this.srvList.SelectedIndexChanged += new System.EventHandler(this.srvList_SelectedIndexChanged);
mapBox1.Items.Add("Germany");
mapBox1.Items.Add("Russia");
difBox1.Items.Add("Easy");
difBox1.Items.Add("Difficult");
}
This is the event handler of the "Create Server" button. It takes server parameters from the screen and writes to a file named as the server.
private void crtButton_Click(object sender, EventArgs e)
{
//Add srvName to srvList
srvName = namBox1.Text;
srvList.Items.Add(srvName);
//Selections
mapSelect = mapBox1.Text;
difSelect = difBox1.Text;
//Write to config file
string path = #"C:\Test\" + srvName + ".txt";
StreamWriter sw = new StreamWriter(path);
sw.WriteLine(mapSelect);
sw.WriteLine(difSelect);
sw.Flush();
sw.Close();
//Clear newPanel form
namBox1.Text = String.Empty;
mapBox1.SelectedIndex = -1;
difBox1.SelectedIndex = -1;
//Return to srvList
//newPanel.Visible = false;
}
And finally list box event handler is below. Method reads the server parameters from file and displays on the screen.
private void srvList_SelectedIndexChanged(object sender, EventArgs e)
{
if (srvList.SelectedIndex == -1)
{
dltButton.Visible = false;
}
else
{
dltButton.Visible = true;
}
string path = #"C:\Test\" + srvList.SelectedItem + ".txt";
StreamReader sr = new StreamReader(path);
//Text being displayed to the left of the server listbox
mapLabel1.Text = sr.ReadLine(); // mapSelect;
difLabel1.Text = sr.ReadLine(); // difSelect;
}
Please feel free to ask any questions you have.
I ended up figuring out the issue. Basically I ended up deciding on a write to a txt file and then read from it to display the contents of the file in the server select menu. I also added a delete button so you can delete the servers that you created. it does not have full functionality yet but it is there. So here it what I ended up with and it works perfectly. Thank you all for trying to help.
public partial class Form1 : Form
{
//Variables
string srvName;
string mapSelect;
string mapFile;
string difSelect;
string difFile;
int maxPlayers;
string plrSelect;
string plrFile;
string finalFile;
string basepath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
string fileName = "config.txt";
public Form1()
{
InitializeComponent();
this.srvList.SelectedIndexChanged += new System.EventHandler(this.srvList_SelectedIndexChanged);
}
private void srvList_SelectedIndexChanged(object sender, EventArgs e)
{
//Read Server Selection
string srvSelect = srvList.GetItemText(srvList.SelectedItem);
string srvOut = System.IO.Path.Combine(basepath, srvSelect, fileName);
mapFile = File.ReadLines(srvOut).Skip(1).Take(1).First();
difFile = File.ReadLines(srvOut).Skip(2).Take(1).First();
plrFile = File.ReadLines(srvOut).Skip(3).Take(1).First();
//Display Server Selection
if (srvList.SelectedIndex == -1)
{
dltButton.Visible = false;
}
else
{
dltButton.Visible = true;
mapLabel1.Text = mapFile;
difLabel1.Text = difFile;
plrLabel1.Text = plrFile;
}
private void crtButton_Click(object sender, EventArgs e)
{
//Set Server Name
srvName = namBox1.Text;
string finalpath = System.IO.Path.Combine(basepath, srvName);
//Check if server name is taken
if (System.IO.Directory.Exists(finalpath))
{
MessageBox.Show("A Server by this name already exists");
}
else
{
//Add Server to the Server List
srvList.Items.Add(srvName);
//Server Configuration
mapSelect = mapBox1.Text;
difSelect = difBox1.Text;
maxPlayers = maxBar1.Value * 2;
plrSelect = "" + maxPlayers;
//Clear New Server Form
namBox1.Text = String.Empty;
mapBox1.SelectedIndex = -1;
difBox1.SelectedIndex = -1;
//Create the Server File
Directory.CreateDirectory(finalpath);
finalFile = System.IO.Path.Combine(finalpath, fileName);
File.Create(finalFile).Close();
//Write to config file
string[] lines = { srvName, mapSelect, difSelect, plrSelect };
System.IO.File.WriteAllLines(#finalFile, lines);
//Return to srvList
newPanel.Visible = false;
}
}
}

How to close the tab with a message that "the file does not exist anymore" in c# win form application?

I have created a notepad with a tabbed interface. It is a c# winform application. Now, what I want is this - if the file does not exist anymore, deleted by another program then if I click the related tab, it should show a message that "the file does not exist" and it should close the tab.
private string FolderPath = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // location of document folder
private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
{
if (tabControl1.TabCount == 0)
{
return;
}
else
{
TabPage tpp = tabControl1.SelectedTab;
this.FileOnly = tpp.Text + ".txt"; // I used tab names without extension, that's why adding it back
String str = tpp.Text;
string CorrFolderPath = FolderPath.Replace(#"\", #"\\");
string FolderPathcomplete = CorrFolderPath + "\\My_Note\\"; // this is the location of saving files; the folder contents appear as list box entries in the program
string filename = FolderPathcomplete + FileOnly;
if (str.Contains("New Document"))// the new tabs which are not yest saved has the name New Document 1, 2 etc.
{
return;
}
else
{
if (File.Exists(filename))
{
return;
}
else
{
MessageBox.Show("File does not exist! Closing the tab.");
var tabPage = tabControl1.TabPages[str];
tabControl1.TabPages.RemoveByKey(str);
}
}
}
}
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
TabPage tp = new TabPage("New Document" + count); //creates a new tab page
tp.Name = "New Document" + count;
RichTextBox rtb = new RichTextBox(); //creates a new richtext box object
tp.Controls.Add(rtb); // adds rich text box to the tab page
tabControl1.TabPages.Add(tp); //adds the tab pages to tab control
tabControl1.SelectedTab = tp;
tabControl1.SelectedIndexChanged += tabControl1_SelectedIndexChanged; // it will check whether tab file exists or not
this.FileName = string.Empty;
count++;
}
Consider using a FileSystemWatcher -- where on creation of a new tab, you create a new watcher and monitor for any changes.
See this article for more information:
https://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher(v=vs.110).aspx

issue with 'file browser dialog' when combining files

Currently, I have a browser dialog that opens and allows the user to select a folder in which doc / docx files will be merged into one file. At the moment, it is rigged up to merge files once the 'DialogResult.ok' button is dismissed in the browser dialog. as shown below:
private void browseButton_Click(object sender, EventArgs e)
{
FolderBrowserDialog diagBrowser = new FolderBrowserDialog();
diagBrowser.Description = "Select a folder which contains files needing combined...";
// Default folder, altered when the user selects folder of choice
string selectedFolder = #"C:\";
diagBrowser.SelectedPath = selectedFolder;
// initial file path display
folderPath.Text = diagBrowser.SelectedPath;
if (DialogResult.OK == diagBrowser.ShowDialog())
{
// Grab the folder that was chosen
selectedFolder = diagBrowser.SelectedPath;
folderPath.Text = diagBrowser.SelectedPath;
}
private void combineButton_Click(object sender, EventArgs e)
{
string[] AllDocFolder = Directory.GetFiles(selectedFolder, "*.doc");
string outputFileName = (#"C:\Test\Merge\Combined.docx");
MsWord.Merge(AllDocFolder, outputFileName, true);
// Message displaying how many files are combined.
MessageBox.Show("A total of " + AllDocFolder.Length.ToString() + " documents have been merged", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
the issue i am having is that i want the 'combineButton' to merge the documents as opposed to the 'DialogResult.ok'. When i copy the lines:
string[] AllDocFolder = Directory.GetFiles(selectedFolder, "*.doc");
string outputFileName = (#"C:\Test\Merge\Combined.docx");
MsWord.Merge(AllDocFolder, outputFileName, true);
into the combineButton area, i get an error saying 'the name 'selectedFolder' does not exist in the current context'. This may be a stupid question, but is there a quick way to remedy this?
As far as I understand your problem, you want to split the folder selection and the merging of the documents, right?
So you could put the information about the target directory into a class variable:
public class MyForm
{
private string[] _sourceFiles;
private void browseButton_Click(object sender, EventArgs e)
{
FolderBrowserDialog diagBrowser = new FolderBrowserDialog();
diagBrowser.Description = "Select a folder which contains files needing combined...";
// Default folder, altered when the user selects folder of choice
string selectedFolder = #"C:\";
diagBrowser.SelectedPath = selectedFolder;
// initial file path display
folderPath.Text = diagBrowser.SelectedPath;
if (DialogResult.OK == diagBrowser.ShowDialog())
{
// Grab the folder that was chosen
selectedFolder = diagBrowser.SelectedPath;
folderPath.Text = diagBrowser.SelectedPath;
_sourceFiles = Directory.GetFiles(selectedFolder, "*.doc");
}
}
private void combineButton_Click(object sender, EventArgs e)
{
if (_sourceFiles != null && _sourceFiles.Length > 0)
{
string outputFileName = (#"C:\Test\Merge\Combined.docx");
MsWord.Merge(_sourceFiles, outputFileName, true);
// Message displaying how many files are combined.
MessageBox.Show("A total of " + _sourceFiles.Length.ToString() + " documents have been merged", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}

C# - Open .RPD file (XML file in disguise), Save out as .XML and then open XML in XmlDocument

As the header says - I am trying to Open a .RPD file (which is a XML file in disguise), Save out as .XML and then open XML using XmlDocument to process . . . all in c#.
This code below works until it hits the line string jN = jobName.InnerText; line.
The error I get is:-
System.NullReferenceException: Object reference not set to an instance of an object. at WindowsFormsApplication1.Form1.button1_Click(Object sender, EventArgs e) in XML Display.cs:line 73
Looks to me like it isn't picking up the new XML file correctly - even though it is there?
Can anybody point me in the right direction to get this to work?
// XML reading, writing and pulling out data.
using System;
using System.Windows.Forms;
using System.Xml;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
// set up some variables to use
public string document;
public string material;
public string thickness;
public string sheetx;
public string sheety;
public string used;
public Form1()
{
InitializeComponent();
}
public void label1_Click(object sender, EventArgs e) { }
private void Form1_Load(object sender, EventArgs e) { }
private void outputBox_TextChanged(object sender, EventArgs e) { }
public void button1_Click(object sender, EventArgs e)
{
OpenFileDialog fDialog = new OpenFileDialog();
// Filter for xml files only
fDialog.Filter = "RPD File|*.rpd";
// Filter for starting directory - in this case a network drive.
fDialog.Title = "Please pick your RPD file . . .";
if (fDialog.ShowDialog() == DialogResult.OK)
{
outputBox.AppendText("Converting your RPD into an XML, saving and then loading back in!" + System.Environment.NewLine);
// set up xml document - using the filename used - load the XML
XmlDocument thisOrder1 = new XmlDocument();
string fN = fDialog.FileName;
thisOrder1.Load(fN);
int fileExtPos = fN.LastIndexOf(".");
string nFN = fN.Substring(0, fileExtPos)+".xml";
// make a duplicate of the file - rename it to a XML file
System.IO.File.Copy(fN, nFN, true);
XmlDocument thisOrder = new XmlDocument();
// load up the new XML file.
thisOrder.Load(nFN);
outputBox.AppendText("Done!" + System.Environment.NewLine);
// try and process this file
try
{
// pull in node list
XmlNodeList xmlnode = thisOrder.GetElementsByTagName("Sheet");
XmlNode jobName = thisOrder.DocumentElement.SelectSingleNode("JobName");
// pull jobName in from the XML
string jN = jobName.InnerText;
// replace question marks and extra spaces with nothing
jN = jN.Replace("?", "");
jN = jN.TrimEnd();
// outout the Job Name
outputBox.AppendText("Job Name > " + jN + System.Environment.NewLine);
// find the CR number from - this will have to be updated.
XmlNode crNumber = thisOrder.DocumentElement.SelectSingleNode("RadanSchedule/JobDetails/NestFolder");
string cR = crNumber.InnerText;
cR = cR.Substring(45, 8);
// output CR number and setup ready to show Material and amount used
outputBox.AppendText("CR Number > " + cR + System.Environment.NewLine + System.Environment.NewLine);
outputBox.AppendText("Material\t\t\t\tUsed" + System.Environment.NewLine);
// main routine to pull out data as needed.
try
{
for (int i = 1; i < xmlnode.Count; i++)
{
used = string.Format(xmlnode[i].ChildNodes.Item(11).InnerText);
if (Convert.ToInt32(used) >= 1)
{
material = string.Format(xmlnode[i].ChildNodes.Item(2).InnerText);
thickness = string.Format(xmlnode[i].ChildNodes.Item(3).InnerText);
sheetx = string.Format(xmlnode[i].ChildNodes.Item(5).InnerText);
sheety = string.Format(xmlnode[i].ChildNodes.Item(6).InnerText);
outputBox.AppendText(material + "-" + thickness + "-" + sheetx + "-" + sheety + "\t\t\t" + used + System.Environment.NewLine);
}
}
}
catch
{
// if the data is found to be empty - tell us
outputBox.AppendText("No data found!" + System.Environment.NewLine);
}
}
catch (Exception ex)
{
// if there is a major problem - tell us
outputBox.AppendText("Problem processing new XML file!" + System.Environment.NewLine + "ERROR > " + ex + System.Environment.NewLine);
}
}
}
}
}
Edited the code above to show ALL code.
Thank you.

WPF Save DialogBox (for windows 64)

This is similar to older posts on this site but I keep getting an error message. I want to create a button in C # WPF that opens a dialogbox and saves a text file to be read at a later date. This code works for windows 32, but crashes on windows 64. How can I change this code to get it to work on both systems? I am a beginner at programming.
Microsoft.Win32.SaveFileDialog saveFile = new Microsoft.Win32.SaveFileDialog(); //throws error message here
private void savebutton_Click(object sender, RoutedEventArgs e)
{
saveFile.FileName = Class1.stringjobnum;
saveFile.Filter = "CCurtain (*.cur)|*.cur";
saveFile.FilterIndex = 2;
saveFile.InitialDirectory = "T:\\Tank Baffle Curtain Calculator\\SavedTanks";
saveFile.OverwritePrompt = true;
bool? result = saveFile.ShowDialog();
if (result.HasValue && result.Value)
{
clsSaveFile.s_FilePath = saveFile.FileName;
int iDotLoc = clsSaveFile.s_FilePath.LastIndexOf('.');
string strExtTest = clsSaveFile.s_FilePath.Substring(iDotLoc);
if (strExtTest != ".cur")
clsSaveFile.s_FilePath += ".cur";
FileInfo sourceFile = new FileInfo(clsSaveFile.s_FilePath);
clsSaveFile.saveFile();
}
}
You're setting an invalid FilterIndex, that might have something to do with it.
There is no 2nd filter in the filter string as written:
"CCurtain (*.cur)|*.cur"
Try setting the FilterIndex to 1 or adding another filter to the string.
You should try adding a catch around the statement to get a better idea as to what is going on.
try
{
code here
}
catch (Exception ex)
{
ex.message contains the info
}
Also, check for null:
bool? result = saveFile.ShowDialog();
if (result != null && (result.HasValue && result.Value))
{
// code
}
I would create the dialogbox IN the event. And you don't have two different filters.
private void savebutton_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.SaveFileDialog saveFile = new Microsoft.Win32.SaveFileDialog();
saveFile.FileName = Class1.stringjobnum;
saveFile.Filter = "CCurtain|*.cur";;
saveFile.FilterIndex = 1;
saveFile.InitialDirectory = "T:\\Tank Baffle Curtain Calculator\\SavedTanks";
saveFile.OverwritePrompt = true;
// Show open file dialog box
Nullable<bool> result = saveFile.ShowDialog();
// Process open file dialog box results
if (result == true)
{
string filename = saveFile.FileName;
// are you sure you need to check the extension.
// if so extension is a a fileinfo property
}

Categories