Help to understand the essence of transfer data to another class.
So,Silverlight application.I have page Home.xaml(and its code-behind Home.xaml.cs).There is the button. when I click on the button the following code is executed:
Home.xaml.cs
private void Button_Click_1(object sender, RoutedEventArgs e)
{
OpenFileDialog opendialog = new OpenFileDialog();
opendialog.Multiselect = true;
bool? dialogResult = opendialog.ShowDialog();
if (dialogResult.HasValue && dialogResult.Value)
{
Stream fileStream = opendialog.File.OpenRead();
StreamReader reader = new StreamReader(fileStream);
............
here i need in such data as reader ,because i want this data stream(reader) to send to some completely another classes (for example, one DataProccess.cs):
DataProccess.cs:
namespace SilverlightApplication1.Models
{
public static class DataProcess
{
{
}
}
that will process the data stream (reader from Home.xaml.cs) using regular expressions and output data will place into collection List<>.
how to implement it. I would be happy for a few lines of code from you? :)
Revised code:
Home.xaml.cs:
private void Button_Click(object sender, EventArgs e)
{
OpenFileDialog opendialog = new OpenFileDialog();
opendialog.Multiselect = true;
bool? dialogResult = opendialog.ShowDialog();
if (dialogResult.HasValue && dialogResult.Value)
{
Stream fileStream = opendialog.File.OpenRead();
var processor = new Processor();
ICollection<object> results = processor.Process(fileStream);
}
}
Processor.cs
public class Processor
{
public ICollection<object> Process(Stream stream)
{
StreamReader reader = new StreamReader(stream);
string pattern = #"set vrouter ""([\w-]+)""";
while (!reader.EndOfStream)
{
var matches =
Regex.Matches(reader.ReadToEnd(), pattern)
.Cast<Match>().Where(m => m.Success)
.Select(m => m.Groups[1].Value)
.Distinct();
foreach (var match in matches)
{
var val = match + Environment.NewLine;
return new Collection<object>().Add(val);; //here error
}
}
//return new Collection<object>(val);
}
}
such error:
Error1/Cannot implicitly convert type 'void' to 'System.Collections.Generic.ICollection'
Create a new class that will process your results
public class Processor
{
public ICollection<object> Process(Stream stream)
{
StreamReader reader = new StreamReader(stream);
// do stuff
return new Collection<object>();
}
}
Then create an instance of it and call the Process method
Stream fileStream = opendialog.File.OpenRead();
var processor = new Processor();
ICollection<object> results = processor.Process(fileStream);
Related
I am creating a program that creates, writes, and saves an xml file. When I try to open the saved file I get an error that says the file cannot be accessed because it is being used by another process. I assumed it was because I didn't close the filestream after I saved the file so I made the correction. I still can't open the file and I receive the same error. I'm not sure what the issue is beyond this point. How can I fix this?
namespace XML_DataSets
{
public partial class FormAddNew : Form
{
XmlSerializer xs;
List<Class1> ls;
//create the DataTable
DataTable dt = new DataTable("Contact");
XDocument xd = new XDocument();
public FormAddNew()
{
InitializeComponent();
ls = new List<Class1>();
xs = new XmlSerializer(typeof(List<Class1>));
//create columns for the DataTable
DataColumn dc1 = new DataColumn("Id");
dc1.DataType = System.Type.GetType("System.Int32");
dc1.AutoIncrement = true;
dc1.AutoIncrementSeed = 1;
dc1.AutoIncrementStep = 1;
//add columns to the DataTable
dt.Columns.Add(dc1);
dt.Columns.Add(new DataColumn("Name"));
dt.Columns.Add(new DataColumn("Age"));
dt.Columns.Add(new DataColumn("Gender"));
//create DataSet
DataSet ds = new DataSet();
ds.DataSetName = "AddressBook";
ds.Tables.Add(dt);
}
private void buttonCreate_Click(object sender, EventArgs e)
{
DataRow row = dt.NewRow();
row["Name"] = textBoxName.Text;
row["Age"] = textBoxAge.Text;
row["Gender"] = textBoxGender.Text;
dt.Rows.Add(row);
dataGridView1.DataSource = dt;
//dt.WriteXml("Contacts.xml");
xd = WriteDt2Xml(dt);
}
public static XDocument WriteDt2Xml(DataTable dt)
{
using (var stream = new MemoryStream())
{
dt.WriteXml(stream);
stream.Position = 0;
XmlReaderSettings settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Fragment;
XmlReader reader = XmlReader.Create(stream, settings);
reader.MoveToContent();
if (reader.IsEmptyElement) { reader.Read(); return null; }
return XDocument.Load(reader);
}
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
Stream input = null;
OpenFileDialog dialog = new OpenFileDialog();
openFileDialog.Filter = "xml file | *.xml";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
if ((input = openFileDialog.OpenFile()) != null)
{
FileStream fs = new FileStream(#openFileDialog.FileName.ToString(), FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
ls = (List<Class1>)xs.Deserialize(fs);
dataGridView1.DataSource = ls;
fs.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "ERROR");
}
}
}
}
}
#Daniel Advise taken well...I refactored the code and see the error you referred to. I checked out the two links you provided as examples. I made corrections but I still get the same result.
First change the way you open the file to:
using (var fs = new FileStream(#openFileDialog.FileName, FileMode.Open, FileAccess.Read))
{
ls = (List<Class1>) xs.Deserialize(fs);
dataGridView1.DataSource = ls;
}
an then try to check (Debug) the entire Exception in openToolStripMenuItem_Click event:
System.InvalidOperationException was caught
HResult=-2146233079
Message=There is an error in XML document (2, 2).
Source=System.Xml
StackTrace:
at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
at System.Xml.Serialization.XmlSerializer.Deserialize(Stream stream)
at WindowsFormsApplication1.FormAddNew.openToolStripMenuItem_Click(Object sender, EventArgs e) in c:\Users\admin\Documents\Visual Studio 2013\Projects\WindowsFormsApplication1\WindowsFormsApplication1\FormAddNew.cs:line 131
InnerException: System.InvalidOperationException
HResult=-2146233079
Message=<AddressBook xmlns=''> was not expected. --The problem!
Source=Microsoft.GeneratedCode
StackTrace:
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderList1.Read3_ArrayOfClass1()
InnerException:
Then read:
xmlns='' was not expected when deserializing nested classes
{"<user xmlns=''> was not expected.} Deserializing Twitter XML
Update:
You need an atomic object when desalinizing like:
public class AddressBook
{
public AddressBook()
{
Contacts = new List<Contact>();
}
public List<Contact> Contacts { get; set; }
}
public class Contact
{
public int Id { get; set; }
public string Name { get; set; }
public string Age { get; set; }
public string Gender { get; set; }
}
and I would suggest to get rid of xDocument, DataSet & DataTable. they add too much complication for nothing. and I guess the reason u r using them because of DataGrid which is minor concern, focus on coding first:
private readonly XmlSerializer xs;
private AddressBook ls;
private int _counter = 0;
public FormAddNew2()
{
InitializeComponent();
ls = new AddressBook();
xs = new XmlSerializer(typeof(AddressBook));
}
private void buttonCreate_Click(object sender, EventArgs e)
{
var addressBookContact2 = new Contact
{
Id = ++_counter,
Name = textBoxName.Text,
Age = textBoxAge.Text,
Gender = textBoxGender.Text
};
ls.Contacts.Add(addressBookContact2);
dataGridView1.DataSource = null; // strangly u need this
dataGridView1.DataSource = ls.Contacts;
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
var saveFileDialog = new SaveFileDialog();
saveFileDialog.InitialDirectory = #"C:\";
saveFileDialog.RestoreDirectory = true;
saveFileDialog.Title = "Select save location file name";
saveFileDialog.Filter = "XML-File | *.xml";
if(saveFileDialog.ShowDialog() == DialogResult.OK)
{
using(var writer = new StreamWriter(saveFileDialog.FileName))
{
xs.Serialize(writer, ls);
MessageBox.Show(saveFileDialog.FileName);
}
}
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
var openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "xml file | *.xml";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
if(openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
using (var reader = new StreamReader(#openFileDialog.FileName))
{
ls = (AddressBook) xs.Deserialize(reader);
_counter = 0;
dataGridView1.DataSource = ls.Contacts;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "ERROR");
}
}
}
i am loading Mp3 Files from folder in Listview. right click option pn listview there is a option of Update tags.when i enter fields data and click update tags it throws ecception Process cant access file it is used by some other process here is my code
private void UpdateTagEditor_RegisterActionEventHandler(object sender, RoutedEventArgs e)
{
var tags = sender as UpdateTags;
string path = tags.targetPath;
string comments = tags.txtTagComment.Text;
string lyrics = tags.txtTagLyrics.Text;
try
{
using (var stream = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.Read))
{
TagLib.Id3v2.Tag.DefaultVersion = 3;
TagLib.Id3v2.Tag.ForceDefaultVersion = true;
TagLib.File tagFile = TagLib.File.Create(path);
tagFile.Tag.Comment = comments;
tagFile.Tag.Lyrics = lyrics;
tagFile.Save();
}
}
catch (Exception exception)
{
}
}
What are you using the Stream for? Nothing it seems. You are trying to create the file twice. Try to remove the stream:
private void UpdateTagEditor_RegisterActionEventHandler(object sender, RoutedEventArgs e)
{
var tags = sender as UpdateTags;
string path = tags.targetPath;
string comments = tags.txtTagComment.Text;
string lyrics = tags.txtTagLyrics.Text;
try
{
TagLib.Id3v2.Tag.DefaultVersion = 3;
TagLib.Id3v2.Tag.ForceDefaultVersion = true;
TagLib.File tagFile = TagLib.File.Create(path);
tagFile.Tag.Comment = comments;
tagFile.Tag.Lyrics = lyrics;
tagFile.Save();
}
catch (Exception exception)
{
}
}
I'm trying to remove out-of-sequence white spaces from a text file to one-space sequence in a winForm i.e.,
From
sagchjvcsj kbschjsdchs sudbjsdbl
sdvbchjbvsdjc kbsadcsadk kskbjdsdcksajdbc
To
sagchjvcsj kbschjsdchs sudbjsdbl
sdvbchjbvsdjc kbsadcsadk kskbjdsdcksajdbc
My implementation is:
private void buttonBrowse_Click(object sender, EventArgs e)
{
Stream myStream;
OpenFileDialog openFileDialogImage = new OpenFileDialog();
openFileDialogImage.Filter = "Text files | .txt";
openFileDialogImage.Multiselect = false;
if (openFileDialogImage.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if ((myStream = openFileDialogImage.OpenFile()) != null)
{
textBoxFileName.Text = openFileDialogImage.FileName;
}
}
}
private void buttonGo_Click(object sender, EventArgs e)
{
string path = textBoxFileName.Text;
string s = string.Empty;
using (StreamReader reader = new StreamReader(path, true))
{
s = reader.ReadToEnd();
}
string[] parts = s.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.ShowDialog();
string pathSave = saveFileDialog.FileName;
File.CreateText(pathSave);
using (StreamWriter sw = new StreamWriter(pathSave))
{
sw.Write(parts);
}
}
}
}
Error that I am getting on line using (StreamWriter sw = new StreamWriter(pathSave)) is:
The process cannot access the file 'E:\test.txt' because it is being used by another process.
I downloaded ProcessWorker to see which process is currently locking Test.txt but I don't see any process using it. Any ideas on how to solve it?
In addition to the other suggestions, your problem is that File.CreateText() will lock so you need to release the lock. I have wrapped the call to File.CreateText() in a using statement to release the lock.
There was an issue with the output of the StreamWriter so I made some changes to get the expected output as per your question.
private void buttonGo_Click(object sender, EventArgs e)
{
string path = textBoxFileName.Text;
string s = string.Empty;
string[] parts;
using (StreamReader reader = new StreamReader(path, true))
{
parts = reader.ReadToEnd().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
}
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.ShowDialog();
string pathSave = saveFileDialog.FileName;
using (File.CreateText(pathSave))
{ }
using (StreamWriter sw = new StreamWriter(pathSave))
{
string result = string.Empty;
foreach (string s in parts)
{
result += s + " ";
}
sw.Write(result);
}
}
I seem to have a problem with two lines of code in my program.
A ThreadStateException occurs at the lines if (o.ShowDialog() == DialogResult.OK) and if(s.ShowDialog() == DialogResult.OK)
The program is supposed to interpret a made up language, but that part of code has not been made yet. Please help, I have no idea what to do!
public class meow : Form
{
TextBox meowbox = new TextBox();
private string titile;
public meow()
{
titile="Tiger goes Meow";
Size = new Size(500, 600);
Text =titile ;
meowbox.Size = new Size(450, 520);
meowbox.Multiline = true;
meowbox.ScrollBars = ScrollBars.Horizontal;
meowbox.WordWrap = true;
meowbox.Location = new Point(25, 10);
//file
MenuItem feow = new MenuItem("File Meow");
MenuItem oeow = new MenuItem("open Meow");
MenuItem seow = new MenuItem("Save Meow");
feow.MenuItems.Add(oeow);
feow.MenuItems.Add(seow);
//run
MenuItem leow = new MenuItem("Meow");
MenuItem ceow = new MenuItem("Check Meow");
MenuItem reow = new MenuItem("Run Meow");
leow.MenuItems.Add(ceow);
leow.MenuItems.Add(reow);
//menu
MainMenu beow = new MainMenu();
Menu = beow;
beow.MenuItems.Add(feow);
beow.MenuItems.Add(leow);
//put it all meow
Controls.Add(meowbox);
//handlers
oeow.Click += new EventHandler(oeow_Click);
seow.Click += new EventHandler(seow_Click);
/*ceow.Click += new EventHandler(ceow_Click);
reow.Click += new EventHandler(reow_Click);*/
}
protected void oeow_Click( object sender, EventArgs e){
Text="Oeow";
OpenFileDialog o = new OpenFileDialog();
if (o.ShowDialog() == DialogResult.OK)
{
Stream file = o.OpenFile();
StreamReader reader = new StreamReader(file);
char[] data = new char[file.Length];
reader.ReadBlock(data, 0, (int)file.Length);
meowbox.Text = new String(data);
reader.Close();
}
Text = titile;
}
protected void seow_Click(object sender, EventArgs e)
{
Text="seow";
SaveFileDialog s = new SaveFileDialog();
if(s.ShowDialog() == DialogResult.OK)
{
StreamWriter writer = new StreamWriter(s.OpenFile());
writer.Write(meowbox.Text);
writer.Close();
}
Text=titile;
}
public static void Main()
{
Application.Run(new meow());
}
}
If the code you posted is your real program, then the problem is that you aren't setting the thread's apartment state correctly. The main Winforms UI thread must be a single-threaded apartment thread.
Try:
[STAThread]
public static void Main()
{
Application.Run(new meow());
}
Note that ideally, you should just create your Winforms project using the template built into Visual Studio. It will configure the thread correctly for you.
Here is my AddReservation Form code. Notice that I call the Piper.WritePiper() method and pass in the Name and Seat that the user enters. I'm not sure why this isn't working. I'm not getting any errors or anything. I am simply just wanting a user to be able to enter their name and seat that they would like to take on the plane and then update the file. Please tell me what I am doing wrong... Thank you in advance!!
public partial class frmAddReservation : Form
{
public frmAddReservation()
{
InitializeComponent();
}
List<Seating> piperSeating = new List<Seating>();
List<Seating> cessnaSeating = new List<Seating>();
private void frmAddReservation_Load(object sender, EventArgs e)
{
piperSeating = Piper.GetPiperReservations();
cessnaSeating = Cessna.GetCessnaReservations();
}
private void btnShowPiper_Click(object sender, EventArgs e)
{
listFlight.Items.Add("Piper Seating Chart:");
listFlight.Items.Add("");
//loop through all the seats
foreach (Seating plane in piperSeating)
{
// add the name of plane to the listbox
listFlight.Items.Add(plane.Name + " " + plane.Seat);
}
}
private void btnAddPiper_Click(object sender, EventArgs e)
{
string Name;
int Seat;
if (DataValid())
{
Name = txtName.Text;
Seat = Convert.ToInt16(txtSeat.Text);
Piper.WritePiper(Name, Seat);
}
}
private bool DataValid()
{
bool isOK = false;
if (CheckSeat(txtSeat))
{
isOK = true;
}
return isOK;
}
private bool CheckSeat(TextBox tbox)
{
bool isOK = true;
try
{
Convert.ToDouble(tbox.Text);
}
catch
{
isOK = false;
}
return isOK;
}
}
Here is my Piper.cs class:
public static class Piper
{
private const string dir = #"Z:\Desktop\Windows 7 Files\C#.net\Reservations\Reservations\Reservations\";
private const string path = dir + "PiperDat.txt";
public static List<Seating> GetPiperReservations()
{
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
StreamReader textIn =
new StreamReader(
new FileStream(path, FileMode.Open, FileAccess.Read));
List<Seating> personList = new List<Seating>();
while (textIn.Peek() != -1)
{
string row = textIn.ReadLine();
string[] columns = row.Split(',');
Seating person = new Seating();
person.Name = columns[0];
person.Seat = Convert.ToInt16(columns[1]);
personList.Add(person);
}
textIn.Close();
return personList;
}
public static void WritePiper(string Name, int Seat)
{
List<Seating> piperSeating = new List<Seating>();
piperSeating = Piper.GetPiperReservations();
StreamWriter textOut =
new StreamWriter(
new FileStream(path, FileMode.Open, FileAccess.Write));
foreach (Seating plane in piperSeating)
{
Name = plane.Name;
Seat = plane.Seat;
textOut.Write(Name + ",");
textOut.WriteLine(Seat);
}
}
}
Look at the WritePiper method.
It just reads the file and then writes it back, without any changes. The values in the parameters are ignored, the parameters are just used as temporary storage for the data when it is written to the file.
You need to include the values in the parameters as an item, either by adding it to the list, or by writing it to the file along with the items in the list.
Example:
Seating person = new Seating();
person.Name = Name;
person.Seat = Seat;
piperSeating.Add(person);
I think the cause of your issue might be having forgotten the closure of the file, in alternative you might force the text to flush with textOut.Flush().
Try adding textOut.Close() at the end of the WritePiper(...) method.