Data Save in File except Database - c#

I am new to Windows form application I want to Save Data in file except in (Sql) or database.I tried many things and I am able to store only one value in text file using it
TextWriter txt = new System.IO.StreamWriter("E:\\Tahir\\ScaleSystemDataSave\\First.txt");
txt.Write(txtFirsrWeight.Text);
txt.Close();
but I Want to Store an Object in file how can I Do it My object is like this
private void btnSave_Click(object sender, EventArgs e)
{
FirstTime obj = new FirstTime();
obj.CardNo = txtCardNo.Text;
obj.DateTime = txtDateTimePicker.Value;
obj.VehicleNo = txtVehicalNo.Text;
obj.WeightType = Convert.ToString(cbxWeigtType.SelectedItem);
obj.FirstWeight = txtFirsrWeight.Text;
if (rbtWithDriver.Checked == true)
{
obj.IsDriver = (int)Status.WithDriver;
}
else if (rbtWithouDriver.Checked == true)
{
obj.IsDriver = (int)Status.withOutDriver;
}
}

You have 2 options available to you.
Format the text file yourself like a comma delimited file and then read the file back in, parse it and assign the values back to your object.
Use a known serialization technique such as XML or JSON.
Below is an example of JSON serialization that achieves what you need.
var first = new FirstTime()
{
CardNo = "121515611",
Date = DateTime.Now.Date,
VehicleNo = "MNRG23434",
WeightType = "MyWeight",
FirstWeight = "FirstWeight"
};
var fileText = JsonConvert.SerializeObject(first);
TextWriter txt = new StreamWriter("C:\\First.txt");
txt.Write(fileText);
txt.Close();
var fileStream = File.Open("C:\\First.txt",FileMode.Open);
var fileReader = new StreamReader(fileStream);
var contents = fileReader.ReadToEnd();
var restoredObject = JsonConvert.DeserializeObject<FirstTime>(contents);
This stores the data in format as per the below
{"CardNo":"121515611","Date":"2017-03-16T00:00:00+00:00","VehicleNo":"MNRG23434","WeightType":"MyWeight","FirstWeight":"FirstWeight"}
Hope that helps you.

Related

How to copy data from HTML div in Selenium C#?

I want to copy alter table data from webpage div and paste it into a .txtfile, screenshot is attached below:
Below is the HTML for above screenshot:
Can i do this by storing this in a variable like below but how can i copy all data at once in a variable from div ?
string value = driver.FindElement(By.XPath("//td[#style='padding:0px;
white-space: nowrap;']")).Text;
Below is the code of my test case in which i am selecting a file to convert from a tool after conversion i want to store the alter table script in a separate .txt file for which i created a create function to create file :
public void TestMethod1()
{
try
{
string dir = #"D:\test\input"; //path
var directory = new DirectoryInfo(dir); //folder ko access
foreach (FileInfo file in directory.GetFiles()) //loop
IWebDriver driver = new ChromeDriver(); //driver object
driver.Navigate().GoToUrl("http:abcurl//convPLSQL.html");
//site url
driver.Manage().Window.Maximize(); //browser maximize
string param = dir.Replace("/", "\\"); // ye code file
param += "\\";
param += file.Name;
driver.FindElement(By.Id("fileuploader")).SendKeys(param);
driver.FindElement(By.Id("keyinput")).SendKeys("convUser001");//Key
driver.FindElement(By.Id("translatebutton")).Click();//Translate Button
driver.FindElement(By.LinkText("Download Results")).Click();//Download
// string data= driver.FindElement(By.XPath("//td[#style='padding:0px;
// white-space:nowrap;']")).Text;
create(); // call create function to create .txt file
}
public void create()
{
try
{
string fileName = #"D:\test\output\Mahesh.txt";
// Check if file already exists. If yes, delete it.
if (System.IO.File.Exists(fileName))
{
System.IO.File.Delete(fileName);
}
// Create a new file
using (FileStream fs = System.IO.File.Create(fileName))
{
// Add some text to file
Byte[] title = new UTF8Encoding(true).GetBytes("New Text File");
fs.Write(title, 0, title.Length);
byte[] author = new UTF8Encoding(true).GetBytes("Mahesh Chand");
fs.Write(author, 0, author.Length);
}
// Open the stream and read it back.
using (StreamReader sr = System.IO.File.OpenText(fileName))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
System.Console.WriteLine(s);
}
}
Get all child elements of div containing the spans having the needed text. Something like:
var spans = driver.FindElements(By.XPath("//td/div[2]/span"));
Then concatenate text from each span element. Replace special characters like "&nbsp" with space. Use string builder or add text to string generic collection and join later if the text is big.
Example:
var text = string.Empty;
foreach(var span in spans)
{
text += span.Text.Replace("&nbsp", " ");
}

Unable to bind data to DataGridView by using BindingList in WinForm application

I am reading data from excel file (.csv) and storing that data to List<String>. I want to display this data to DataGridView but for some reason I am seeing total length of String in Grid.
Following is my code :
CODE:
private void btnImportFile_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "CSV (Comma delimited) (*.csv)|*.csv";
dialog.FilterIndex = 1;
dialog.Multiselect = false;
var userClickedOK = dialog.ShowDialog();
if (userClickedOK.ToString().Equals("OK"))
{
this.lblImportedFileName.Text = dialog.SafeFileName;
System.IO.Stream fileStream = dialog.OpenFile();
using (System.IO.StreamReader reader = new System.IO.StreamReader(fileStream))
{
var list = new List<String>();
var line = String.Empty;
while ((line = reader.ReadLine()) != null) //Reading value and adding it to the list.
{
list.Add(line);
}
BindingList<String> view = new BindingList<String>(list);
this.gridExcelResults.DataSource = view; // Binding list to grid
//Also tried
this.gridExcelResults.DataSource = list; // This also gives me same result.
}
}
}
OUTPUT:
EXCEL DATA:
EXPECTED RESULT:
I just want to display these three fields on Grid. What am I doing wrong here?
See this question:
How to bind a List<string> to a DataGridView control?
In your case you are using a BindingList<string> but the logic is the same. The DataGridView is looking for object properties to bind, String however, only has the property length.

Retrieve the data from Text File

I have a little project. What I am doing is, taking inputs from users and saving it in a text file. Its working good.
private void btbsave_Click(object sender, EventArgs e)
{
//Create Directory
DirectoryInfo dd = new DirectoryInfo("C://Program Files/UserInfo");
dd.Create();
//To save the inputs
StreamWriter sw = new StreamWriter("C://Program Files/UserInfo/UserInfo.txt", true);
sw.WriteLine(txtname.Text);
sw.WriteLine(txtage.Text);
sw.Flush();
sw.Close();
//Conformation
MessageBox.Show("Credentials Saved");
//To Clear the text box after data saved
txtname.Text = string.Empty;
txtage.Text = string.Empty;
//Focus
txturl.Focus();
}
And now, I want to retrieve the data depending on the inputs. This part is difficult for me, can you guys help me out?
private void btnsearch_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader("C://Program Files/UserInfo/UserInfo.txt");
String mystring = sr.ReadToEnd();
//No idea how to retrive now plz help!
}
Brief description of my project:
Take some values from users like UserName and Age. Save them in a text file.
I need to retrieve values based on user UserName. I should then get UserName along with his Age and insert these values into 2 different readonly text boxes.
Personally I'd advise you to rethink your approach, but here's what you're looking for:
string sUserToSearch = "username";
string sAgeToSearch = "22";
string[] readText = File.ReadAllLines("UserInfo.txt");
for (int i = 0; i < readText.count-2; i++) {
if(readText[i] == sUserToSearch && readText[i+1] == sAgeToSearch);
// Found it!
}
I don't know what you're trying to do, but if I got you correct, you should read more on Serialization
First you have to seperate your data at the time, you insert them to your textfile
private void WriteUserToFile(User user, string path)
{
using(var sw = new StreamWriter(path, true))
{
sw.WriteLine(user.Name + ";" + user.Age);
}
}
Now you have a file like this:
User1;10
User2;20
User3;45
Now you have the possibility to split your data:
private IEnumerable<User> ReadUsersFromTextFile(string path)
{
var users = new List<User>();
using(var sr = new StringReader(path)
{
do
{
var strings = sr.ReadLine().split(';');
var user = new User();
user.Name = strings[0];
user.Age = strings[1];
users.Add(user);
}while(!sr.EndOfStream)
}
return users;
}

Telerik RenderReport

I have some problems with Telerik reports.
Feels like i have missed something...
I wanna create a list of reports, and then write them to ONE file.
But when i write it out i only get one page.
The writer writer over page 1 all foreach, so it just write one page.
But i want several pages... in this case 10.
Have tried write with FileStream, File and more...
Does anyone have a good idea?
public void WriteToFile()
{
string path = #"C:\";
string test = "test";
var report = new Report2();
var procceser = new ReportProcessor();
var list = new List<RenderingResult>();
for (int i = 0; i < 10; i++)
{
var res = procceser.RenderReport("PDF", report, null);
list.Add(res);
}
string filePath = Path.Combine(path, test);
var Writer = new BinaryWriter(File.Create(filePath));
foreach (var renderingResult in list)
{
Writer.Write(renderingResult.DocumentBytes);
}
Writer.Flush();
Writer.Close();
}

Convert XML response to .CSV file

I have the following code,
I am sending an array of data to a web service, the response from the web service gets displayed currently in a web form as shown below.
private void Form1_Load(object sender, EventArgs e)
{
int ASent;
int CSent;
webservice.Results returned = convert();
txtResult.Text = System.Convert.ToString(returned.status);
txtMoreRes1.Text = returned.errorDetails[0].errorDetails;
txtMoreRes2.Text = returned.errorDetails[1].errorDetails;
txtMoreRes3.Text = returned.errorDetails[2].errorDetails;
txtMoreRes4.Text = returned.errorDetails[3].errorDetails;
date.Text = System.Convert.ToString(DateTime.Today);
time.Text = System.Convert.ToString(DateTime.Now.TimeOfDay);
}
What I now need is for the results 'returned' to be converted from an xml response into a .csv file. Then have the code save that .csv to a location on the C drive. How can I change my code to do this?
Thanks for your time!
StringBuilder SbCSV = new StringBuilder();
int ActualSent;
int CommitmentSent;
webservice.summaryResults returned = convert(out ActualSent, out CommitmentSent);
//txtResult.Text = System.Convert.ToString(returned.status);
SbCSV.Append(System.Convert.ToString(returned.status));
//txtMoreRes1.Text = returned.errorDetails[0].errorDetails;
SbCSV.Append("," + returned.errorDetails[0].errorDetails);
//txtMoreRes2.Text = returned.errorDetails[1].errorDetails;
SbCSV.Append("," + returned.errorDetails[1].errorDetails);
// Similary ...
txtMoreRes3.Text = returned.errorDetails[2].errorDetails;
txtMoreRes4.Text = returned.errorDetails[3].errorDetails;
actualSum.Text = System.Convert.ToString(returned.actualSum);
commitmentSum.Text = System.Convert.ToString(returned.commitmentSum);
date.Text = System.Convert.ToString(DateTime.Today);
time.Text = System.Convert.ToString(DateTime.Now.TimeOfDay);
actualsumsent.Text = ActualSent.ToString();
commitmentsumsent.Text = CommitmentSent.ToString();
errorposition1.Text = System.Convert.ToString(returned.errorDetails[0].errorPosition);
errorposition2.Text = System.Convert.ToString(returned.errorDetails[1].errorPosition);
errorposition3.Text = System.Convert.ToString(returned.errorDetails[2].errorPosition);
errorposition4.Text = System.Convert.ToString(returned.errorDetails[3].errorPosition);
TextWriter Tw = new StreamWriter("Your_FilePath_Name.csv");
Tw.Write(SbCSV.ToString());
Tw.Close();
Tw.Dispose();
You could also use FileHelpers to do this stuff.
You must create a class named MyClass with attributes that match your .csv format (each column = one attribute)
you build a List of such class objects and convert to csv this way using FileHelper :
FileHelperEngine engine = new FileHelperEngine(typeof(MyClass));
MyClass[] res = null; //Fill your array here from your code.
// To Write Use:
engine.WriteFile("FileOut.txt", res);
You can also do this with an XML Transformation.

Categories