read multiple values from file and place in the right place - c#

I have this code, which does this
click on label object
run the MouseTracker method to get the mouse position
another method (WriteToConfig) is runned
here I check if there is any result then do some work with regex to update or write a new line with values
public partial class Settings : Form
{
public int xTemp;
public int yTemp;
const string ConfigFile = "config.ini";
public string? ConfigRead;
public Settings()
{
InitializeComponent();
}
private void MouseTracker(string name)
{
DialogResult result = MessageBox.Show($"Move your cursor to \"{name}\" slot in your tab \n and press ENTER");
if (result == DialogResult.OK)
{
xTemp = MousePosition.X;
yTemp = MousePosition.Y;
}
}
private void WriteToConfig(string labelName, int number)
{
ConfigRead = File.ReadAllText(ConfigFile);
try
{
string PATTERN = #$"{labelName} = (?<value>[0-9]+)";
Match match = Regex.Match(ConfigRead, PATTERN, RegexOptions.IgnoreCase);
if (match.Success)
{
int index = match.Groups["value"].Index;
int length = match.Groups["value"].Length;
ConfigRead = ConfigRead.Remove(index, length);
ConfigRead = ConfigRead.Insert(index, number.ToString());
File.WriteAllText(ConfigFile, ConfigRead);
}
else
{
string result = $"{labelName} = {number} \n";
ConfigRead = ConfigRead.Insert(ConfigRead.Length, result);
File.WriteAllText(ConfigFile, ConfigRead);
}
}
catch
{
MessageBox.Show($"{labelName} error");
}
}
private void ReadFromConfig()
{
ConfigRead = File.ReadAllText(ConfigFile);
string PATTERN = #"(?<labelName>[a-zA-Z]+) = (?<value>[0-9]+)";
Match match = Regex.Match(ConfigRead, PATTERN, RegexOptions.IgnoreCase);
}
private void orbTransLabel_Click(object sender, EventArgs e)
{
MouseTracker(orbTransLabel.Text.Remove(orbTransLabel.Text.Length - 1, 1));
orbTransXPos.Text = xTemp.ToString();
orbTransYPos.Text = yTemp.ToString();
WriteToConfig("orbTransXPos", int.Parse(orbTransXPos.Text));
WriteToConfig("orbTransYPos", int.Parse(orbTransYPos.Text));
}
now after I open the form, I would like the to read the file and update all the values from form
I started a ReadFromConfig method to read all the data and I'm thinking to match those results with every label and get the value from file with regex and put in the form.
I could need some help if anyone is willing to :D
the config.ini looks like this
orbTransXPos = 717
orbTransYPos = 1225
orbAltXPos = 717
orbAltYPos = 1267
orbAugXPos = 675
orbAugYPos = 1256
orbChanceXPos = 1874
orbChanceYPos = 1620
jewellersXPos = 1363
jewellersYPos = 488
orbFusingXPos = 13
orbFusingYPos = 193
chromXPos = 364
chromYPos = 1562
orbAlchXPos = 2359
orbAlchYPos = 628
chaosOrbXPos = 1125
chaosOrbYPos = 1772
regalOrbXPos = 1292
regalOrbYPos = 367
chiselXPos = 1398
chiselYPos = 1793
scouringXPos = 1074
scouringYPos = 339
wisdomXPos = 1315
wisdomYPos = 1683

Related

Modifying and validating fields in a DataTable c#

I have the following datatable:
the field "court_case" has a different format and is not compact, the expected format would be: XXXX/XX ("4 digits" / "2 digits" )
For example:
12/13 -> 0012/13
2/1 -> 0002/10
/18 -> 0000/18
45/ -> 0045/00
I.e. complete with leading zeros if it is the case for the first part before the "/" and with leading zeros if it is the case after the "/".
private void bt_showDataTable_Click(object sender, EventArgs e)
{
Cursor.Current = Cursors.WaitCursor;
dataGridView2.DataSource = getDataTable();
}
public DataTable getDataTable()
{
DataTable dtTabla = new DataTable();
try
{
MySqlConnection connection = new MySqlConnection();
connection.ConnectionString = configuracion.conexion;
connection.Open();
string query = "SELECT * FROM CC_T.CONSIGNATION WHERE ACCOUNT IN ('error');"; //query from the image above
MySqlCommand mycmd = new MySqlCommand(query, connection);
mycmd.Connection = connection;
MySqlDataReader reader = mycmd.ExecuteReader();
dtTabla.Load(reader);
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
}
return dtTabla;
}
// METHOD TO VALIDATE COURT CASE
public static bool Validar_Cc(string CourtCase)
{
int i = 0;
string part1 = "";
string part2 = "";
bool result1 = false;
bool result2 = false;
if (CourtCase.Contains("/"))
{
part1 = CourtCase.Substring(0, CourtCase.IndexOf('/'));
part2 = CourtCase.Substring(CourtCase.IndexOf('/') + 1, CourtCase.Length - CourtCase.IndexOf('/') - 1);
result1 = int.TryParse(part1, out i);
result2 = int.TryParse(part2, out i);
}
if (!result1 || !result2)
{
return false;
}
else return true;
}
with this validation I only check that what comes for court_case is of type integer. but I do not check a validation of the format like: "XXXX/XX".
here I have to pass the method to validate:
private void btnCORRECT_ERROR_COURTCASE_Click(object sender, EventArgs e)
{
string reply = "";
foreach(DataColumn column in dataGridView2.Rows)
{
//
}
}
I know this is wrong but I don't know how to continue. Any help??
Well technically you want to split the string to 2 parts, handle each separately and add it together with added zeroes. Like:
var inputArray = new string[4] { "12/13", "2/1", "/18", "45/" };
var results = new List<string>();
foreach (var str in inputArray)
{
var parts = str.Split(new string[] { "/" }, StringSplitOptions.None);
var result = parts[0].PadLeft(4, '0') + "/" + parts[1].PadLeft(2, '0');
results.Add(result);
}
You can use string.PadLeft method to append leading zeros 0 (or other char) to some string:
static string AddLeadingZeros(string s, int amount)
{
return s.PadLeft(amount, '0');
}
Usage example:
void FixCourtCases()
{
string[] courtCases = new string[]
{
"6906/2",
"9163/2",
"504/",
"3/",
"9/4",
"4311/",
"0/",
"/6",
"193/0",
"0/2",
};
for (int i = 0; i < courtCases.Length; i++)
{
// Split left and right numbers by '/'
string[] courtCase = courtCases[i].Split(new string[] { "/" }, StringSplitOptions.None);
// Add leading zeros to left and right numbers
string fixedLeftNumber = AddLeadingZeros(courtCase[0], 4);
string fixedRightNumber = AddLeadingZeros(courtCase[1], 2)
// Reassign value with fixed one
courtCases[i] = fixedLeftNumber + "/" + fixedRightNumber;
}
}
it will give you that kind of result:
If you just want to check if the input (CourtCase) has the expected format (xxxx/xx) then you could change the Validar_Cc in this way.
public static bool Validar_Cc(string CourtCase)
{
// First check, the string should be 7 character long, if not then fast exit
if (CourtCase.Length != 7)
return false;
// Second check, try to split at /, if you get back an array with more or
// less than two elements then fast exit
string[] parts = CourtCase.Split('/');
if(parts.Length != 2)
return false;
// Now check if the two elements are numbers or not.
// Again fast exit in case of error
if(!Int32.TryParse(parts[0], out int number1))
return false;
if(!Int32.TryParse(parts[1], out int number2))
return false;
// If you reach this point then the data is correct
return true;
}
This example assumes that you consider correct inputs like '0000/00' or '1234/00' or '0000/88'. If this is not the case then one more checks is needed. Just add these lines after the TryParse block
if(number1 == 0 || number2 == 0)
return false;
And you could call the Validar_CC inside the loop over the grid rows
private void btnCORRECT_ERROR_COURTCASE_Click(object sender, EventArgs e)
{
string reply = "";
foreach(DataGridRow row in dataGridView2.Rows)
{
bool result = Validar_Cc(row.Cells["COURT_CASE"].Value.ToString());
.... do whatever you need to do with false/true results
}
}

Picking specific numbers out of text file and assign to variable

Someone here at works needs some calculations done from some numbers within a text file. I know how to do the calculation but I haven't worked with text file before. So I spent the night reading and wrote a little something for the first number I needed but it doesn't work.
So here is an example of the file.
So that first number that comes after FSD: 0.264 I need to read that number and save to a variable. The number will always be different per file. Then I need the first 3.4572 number read to a variable. and the last number of that column as well which you don't see here but for the example it can be the last one shown in the image of 3.3852 read and saved to a variable.
Maybe I'm making this much harder than it needs to be but this is what I was playing around with
public partial class FrmTravelTime : Form
{
string file = "";
public FrmTravelTime()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
file = openFileDialog1.FileName;
}
}
private void button2_Click(object sender, EventArgs e)
{
var sLines = File.ReadAllLines(file)
.Where(s => !s.StartsWith("FSD:"))
.Where(s => !string.IsNullOrWhiteSpace(s))
.Select(s => new
{
SValue = Regex.Match(s, "(?<=S)[\\d.]*").Value,
})
.ToArray();
string Value = "";
for (int i = 0; i < sLines.Length; i++)
{
if (sLines[i].SValue == "")
{
Value = (sLines[i].SValue);
}
}
}
}
EDIT FOR #Ramankingdom
So if you see here all lines have an ending column of 0.00 until we get to
3.0164 7793 1 0 0.159 0.02
So what I'd like to do, is edit what we did to skip everything that has a column with 0.00 in that last column and make the first non 0.00 the info.firstvalue so in this case 3.0164
Now I tried this on my own and used
var data = lines.Where(line => (!line.Contains(Data_Start_Point_Identifier) && !line.Contains(FSD__Line_Identifier) && !line.EndsWith("0.00"))).ToList();
But that breaks info.startvalue and data = dataWithAvgVolts[dataWithAvgVolts.Count - 1].Split(splitter);
So I'd figured I'd check with you.
So I tried this but I keep getting invalid data error on info.startvalue
FileInfo info = new FileInfo();
var lines = File.ReadAllLines(row.Cells["colfilelocation"].Value.ToString());
var fsdLine = lines.FirstOrDefault(line =>
line.Contains(FSD__Line_Identifier));
info.FSD = fsdLine.Substring(fsdLine.IndexOf(FSD_Identifier) + FSD_Identifier.Length, 7);
var dataWithAvgVolts = lines.SkipWhile(line => !line.Contains(Data_Start_Point_Identifier)).ToList();
int index =1;
while(index < dataWithAvgVolts.Count())
{
var data = dataWithAvgVolts[index].Split(splitter);
if(data.Count() >1)
{
if(!Convert.ToDouble(data[data.Count()-1]) == 0)
{
//set start info
break;
}
}
index++;
}
the reverse loop you can run to set the end value
Here is the code
class Program
{
const string FSD_Identifier = "FSD:";
const string FSD__Line_Identifier = "Drilling Data";
const string Data_Start_Point_Identifier = "AVG_VOLTS";
static readonly char[] splitter = {' ','\t'};
static void Main(string[] args)
{
var result = GetFileInfo("c:\\sample.txt");
}
private static MyFileInfo GetFileInfo(string path)
{
MyFileInfo info = new MyFileInfo();
try
{
var lines = File.ReadAllLines(path);
var fsdLine = lines.FirstOrDefault(line => line.Contains(FSD__Line_Identifier));
info.FSD = fsdLine.Substring(fsdLine.IndexOf(FSD_Identifier) + FSD_Identifier.Length, 10); // take lenght you can specify or your own logic
var dataWithAvgVolts = lines.SkipWhile(line => !line.Contains(Data_Start_Point_Identifier)).ToList<string>();
if (dataWithAvgVolts.Count() > 1)
{
var data = dataWithAvgVolts[1].Split(splitter);
info.startvalue = Convert.ToDouble(data[0]);
data = dataWithAvgVolts[dataWithAvgVolts.Count-1].Split(splitter);
info.endvalue = Convert.ToDouble(data[0]);
}
}
catch (Exception ex)
{
//logging here
}
return info;
}
}
public class MyFileInfo
{
public string FSD;
public double startvalue;
public double endvalue;
}

Set a string on a string referenced by string array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
string db;
ComboBox fieldBox = new ComboBox()
TextBox ValueBox = new TextBox()
ListBox dbValues = new ListBox()
private void LoadDB()
{
//Structure
string myStruct = "NAME\nAGE\nSEX\nSKILL
db = "John\t20\tMale\tNoob\n
Joe\t20\tMale\tMedium\n
Jessica\t27\tFemale\tExpert\n
John\t21\tMale\tMedium
";
//Load struct to combobox
string[] mbstr = myStruct.Split('\n');
for (int i = 0; i < mbstr.Length; i++)
{
fieldBox.Items.Add(mbstr[i]);
}
string[] db2 = db.Split('\n');
for (int i = 1; i < db2.Length - 1; i++)
{
//Display name and age in combobox
dbValues.Items.Add(db2[i].Split('\t')[0] + " - " + db2[i].Split('\t')[1]);
}
}
void ValueBoxKeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode != Keys.Enter)
return;
db.Split('\n')[dbValues.SelectedIndex].Split('\t')[fieldBox.SelectedIndex] = valueBox.Text;
MessageBox.Show("Value set: " +
db.Split('\n')[dbValues.SelectedIndex + 1].Split('\t')[fieldBox.SelectedIndex]
+ " to " + valueBox.Text + ".");
}
This is where it fails:
db.Split('\n')[dbValues.SelectedIndex].Split('\t')[fieldBox.SelectedIndex] = valueBox.Text;
I tried this, and tried to assign to db, but not working though. My original string is unchanged.
I do not want to convert to list and string back, i want to change directly.
How can i do this?
Your first problem is your string: unless you use # escaping you can't have your string cross multiple lines, and if you use # escaping you can't do \t or \n and retain their escaped meaning of tab and newline.
The second problem is a fundamental misunderstanding of the .NET string, string's are immutable. Split will create an array, there is no reference back to the original string, or the second array your splitting. You would need to do something like:
[TestClass]
public class StringTest
{
public TestContext TestContext { get; set; }
[TestMethod]
public void RewriteString()
{
var str = "Garry\t19\tMale\tNoob\n" +
"Joe\t25\tMale\tMedium\n" +
"Gary\t33\tFemale\tExpert";
var rows = str.Split('\n');
var columns = rows[0].Split('\t');
columns[0] = "Jerry";
rows[0] = string.Join("\t", columns);
str = string.Join("\n", rows);
TestContext.WriteLine(str);
}
}
Test Name: RewriteString
Test Outcome: Passed
Result StandardOutput: TestContext Messages:
Jerry 19 Male Noob
Joe 25 Male Medium
Gary 33 Female Expert
Would really hope there would be an easier way to do this, possibly with a Regex?
Now to really look at your (new) question. I have refactored exactly what you have, as I do not know your data situation I'm not entirely sure using a string as a database is a good idea: (this will compile without any references because of the use of dynamic).
public class SomeView
{
string db;
dynamic fieldBox = null;
dynamic valueBox = null;
dynamic dbValues = null;
dynamic MessageBox = null;
private void LoadDB()
{
//Structure
string myStruct = "NAME\nAGE\nSEX\nSKILL";
db = "John\t20\tMale\tNoob\n" +
"Joe\t20\tMale\tMedium\n" +
"Jessica\t27\tFemale\tExpert\n" +
"John\t21\tMale\tMedium";
//Load struct to combobox
string[] mbstr = myStruct.Split('\n');
for (int i = 0; i < mbstr.Length; i++)
{
fieldBox.Items.Add(mbstr[i]);
}
string[] db2 = db .Split('\n');
for (int i = 1; i < db2.Length - 1; i++)
{
var data = db2[i].Split('\t'); //expensive only do once
//Display name and age in combobox
dbValues.Items.Add(data[0] + " - " + data[1]);
}
}
protected string Transform(string value, int row, int column, string replacement, out string old)
{
var rows = value.Split('\n');
var columns = rows[row].Split('\t');
old = columns[column];
columns[column] = replacement;
rows[row] = string.Join("\t", columns);
return string.Join("\n", rows);
}
void ValueBoxKeyDown(object sender, dynamic e)
{
if (e.KeyCode != "enter")
return;
string old;
string newValue = this.Transform(db, dbValues.SelectedIndex, fieldBox.SelectedIndex, valueBox.Text, out old);
MessageBox.Show("Value set: " + old + " to " + valueBox.Text + ".");
}
}
So this is better:
public class SomeView
{
dynamic fieldBox = null;
dynamic valueBox = null;
dynamic dbValues = null;
dynamic MessageBox = null;
private List<Person> People = new List<Person>();
private void LoadDB()
{
//Structure
string myStruct = "NAME\nAGE\nSEX\nSKILL";
string db = "John\t20\tMale\tNoob\n" +
"Joe\t20\tMale\tMedium\n" +
"Jessica\t27\tFemale\tExpert\n" +
"John\t21\tMale\tMedium";
//Load struct to combobox
string[] mbstr = myStruct.Split('\n');
for (int i = 0; i < mbstr.Length; i++)
{
fieldBox.Items.Add(mbstr[i]);
}
People.Clear();
foreach(var row in db.Split('\n'))
{
var columns = row.Split('\t');
Person p = new Person();
p.Name = columns[0];
p.Age = int.Parse(columns[1]);
p.Sex = (Person.Sexs)Enum.Parse(typeof(Person.Sexs), columns[2]);
p.SkillLevel = (Person.SkillLevels)Enum.Parse(typeof(Person.SkillLevels), columns[2]);
People.Add(p);
dbValues.Items.Add(string.Format("{0}-{1}", p.Name, p.Age);
}
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public enum Sexs
{
Male,
Female
}
public Sexs Sex { get; set; }
public enum SkillLevels
{
Noob,
Medium,
Expert
}
public SkillLevels SkillLevel { get; set; }
}
void ValueBoxKeyDown(object sender, dynamic e)
{
if (e.KeyCode != "enter")
return;
Person p = this.People[dbValues.SelectedIndex];
switch((int)fieldBox.SelectedIndex)
{
case 0: p.Name = valueBox.Text; break;
case 1: p.Age = int.Parse(valueBox.Text); break;
case 2: p.Sex = (Person.Sexs)Enum.Parse(typeof(Person.Sexs), valueBox.Text); break;
case 3: p.SkillLevel = (Person.SkillLevels)Enum.Parse(typeof(Person.SkillLevels), valueBox.Text); break;
default: throw new NotImplementedException();
}
MessageBox.Show("Value set: " + old + " to " + valueBox.Text + ".");
}
}
However this is still garbage, since if you have a strongly typed data set you can actually bind this to form controls without directly manipulating the item.
https://msdn.microsoft.com/en-us/library/c8aebh9k(v=vs.110).aspx
You cannot change the return-value of a method returning a string as strings are immutable. What you can do instead is the following:
string myDatabase =
"Garry\t19\tMale\tNoob\n" +
"Joe\t25\tMale\tMedium\n" +
"Gary\t33\tFemale\tExpert";
var tmp = "";
foreach(var line in myString.Split('\n')) {
tmp = tmp + Regex.Replace(line, "^.*?(?=\\t)", myReplaceText);
}
myString = tmp;
This regex will search for everything before the very first tab within every line, replaces it by "Jerry"and and concatenates every so replaced line into myString.

String formatting in C#?

I have some problems to format strings from a List<string>
Here's a picture of the List values:
Now I managed to manipulate some of the values but others not, here's what I used to manipulate:
string prepareStr(string itemToPrepare) {
string first = string.Empty;
string second = string.Empty;
if (itemToPrepare.Contains("\"")) {
first = itemToPrepare.Replace("\"", "");
}
if (first.Contains("-")) {
int beginIndex = first.IndexOf("-");
second = first.Remove(beginIndex, first.Length - beginIndex);
}
return second;
}
Here's a picture of the Result:
I need to get the clear Path without the (-startup , -minimzed , MSRun , double apostrophes).
What am I doing wrong here?
EDIT my updated code:
void getStartUpEntries() {
var startEntries = StartUp.getStartUp();
if (startEntries != null && startEntries.Count != 0) {
for (int i = 0; i < startEntries.Count; i++) {
var splitEntry = startEntries[i].Split(new string[] { "||" }, StringSplitOptions.None);
var str = splitEntry[1];
var match = Regex.Match(str, #"\|\|""(?<path>(?:\""|[^""])*)""");
var finishedPath = match.Groups["path"].ToString();
if (!string.IsNullOrEmpty(finishedPath)) {
if (File.Exists(finishedPath) || Directory.Exists(finishedPath)) {
var _startUpObj = new StartUp(splitEntry[0], finishedPath,
"Aktiviert: ", new Uri("/Images/inWatch.avOK.png", UriKind.RelativeOrAbsolute),
StartUp.getIcon(finishedPath));
_startUpList.Add(_startUpObj);
}
else {
var _startUpObjNo = new StartUp(splitEntry[0], finishedPath,
"Aktiviert: ", new Uri("/Images/inWatch.avOK.png", UriKind.RelativeOrAbsolute),
StartUp.getIcon(string.Empty));
_startUpList.Add(_startUpObjNo);
}
}
var _startUpObjLast = new StartUp(splitEntry[0], splitEntry[1],
"Aktiviert: ", new Uri("/Images/inWatch.avOK.png", UriKind.RelativeOrAbsolute),
StartUp.getIcon(string.Empty));
_startUpList.Add(_startUpObjLast);
}
lstStartUp.ItemsSource = _startUpList.OrderBy(item => item.Name).ToList();
}
You could use a regex to extract the path:
var str = #"0Raptr||""C:\Program Files (x86)\Raptr\raptrstub.exe"" --startup"
var match = Regex.Match(str, #"\|\|""(?<path>(?:\""|[^""])*)""");
Console.WriteLine(match.Groups["path"]);
This will match any (even empty) text (either an escaped quote, or any character which is not a quote) between two quote characters preceeded by two pipe characters.
Similarly, you could simply split on the double quotes as I see that's a repeating occurrence in your examples and take the second item in the split array:
var path = new Regex("\"").Split(s)[1];
This is and update to your logic without using any Regex:
private string prepareStr(string itemToPrepare)
{
string result = null;
string startString = #"\""";
string endString = #"\""";
int startPoint = itemToPrepare.IndexOf(startString);
if (startPoint >= 0)
{
startPoint = startPoint + startString.Length;
int EndPoint = itemToPrepare.IndexOf(endString, startPoint);
if (EndPoint >= 0)
{
result = itemToPrepare.Substring(startPoint, EndPoint - startPoint);
}
}
return result;
}

Having troubles with my math in the program

When I am programming my forum, I am having troubles in differentiating the two digits of information on my csv file.
The issue is: If, there are 2 adults who are wanting to go to a place the price = less
However is it is a single adult the price will equal more.
PROBLEM: The problem that occurs is that ALL my segments think all Adults should get charged less, when some of the transaction charges should show more.
To be precise in information: The File that contains the HolidayTran.CSV has the array[3] that has the information of 1 or 2 adults in the party.
When I carry the function ref double adult is that I am carrying to the top.
Edited - This is the method that my professor at my university wants...yes slow and stupid, but its his practice final, so I am trying to figure out what I am missing.
Yes I understand i am suppose to do my own work, but I hope someone can tell me where my math is wrong in the programming.
Edited # 2 Changed the Variables to help make it clearer. I found the isolated problem, located at the If loop section, of my equation. It has been multiplying everything by two digits instead of 1. How can I create a function where if the message reads either a 1 or a 2, then the proper math would apply?
AdultPricing This function is suppose to choose the proper math, but I tend to lose concept of how to finish off the function proper. If you look at the If loop, you can see where I go wrong...Any Ideas guys?
I am trying to do a if statement bool function, but that is currently not working...I don't know what else is needed atm..
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string[] myfile = File.ReadAllLines(#"C:\temp\customerinfo.csv");
var myquery = from mylines in myfile
let myfield = mylines.Split(',')
let names = myfield[1]
let lastname = myfield[2]
let id = myfield[0]
orderby lastname, names
select new { id, names, lastname };
foreach (var listing in myquery) { cmbcustomerinfo.Items.Add(listing.id + " " + listing.names + " " + listing.lastname); }
}
private void cmbcustomerinfo_SelectedIndexChanged(object sender, EventArgs e)
{
//recalling all private void information at the top of the combobox file, inorder to send information to the listbox.
string tempvariable = "";
string iddvariable = "";
string format1 = "{0,55}{1,5}";
string format2 = "{0,-5:d}{1,15:d}{2,20:c}{3,20:c}";
string format3 = "{0,-15}{1,35:c}{2,20:c}";
string format4 = "{0,-15}{1,72:c}";
getCustomerIDFirstName(out tempvariable, out iddvariable);
getcustomerinfo(iddvariable);
//set the required information to connect to the Holiday Transaction. Where we can connect if the ID found in Holiday Matchs the ID in CustomerInfo.CSV,
//then we can show the data of the dates and pricing of the information
string[] transaction = File.ReadAllLines(#"C:\temp\HolidayTrans.csv");
var TransactionQuery = from myLinesshown in transaction
let myfield2 = myLinesshown.Split(',')
let customerid = myfield2[0]
let datestart = myfield2[1]
let numofadults = byte.Parse(myfield2[2])
let numofkids = byte.Parse(myfield2[3])
where customerid == iddvariable
orderby datestart, customerid
select new
{
customerid,
datestart,
numofadults,
numofkids
};
foreach (var staff1 in TransactionQuery)
{
lstInvoice.Items.Clear();
lstInvoice.Items.Add("Purchase Date EndDate Adult Price Kid Price");
//set up all variables used or to be used.
string idgiven = "";
double KidsSubPricing = 0;
double AdultPricing = 0;
double singleddigit = 0;
double TwinAdultPricing = 0;
double totaladult = 0;
double subtotal = 0;
double subtotal1 = 0;
double kidpricing = 3300;
byte NumberOfDaysSpent = 0;
string EndofDays = "";
DateTime daybegin;
DateTime startthedate;
DateTime datebeginning = DateTime.Now;
//set the basic functionality to find the proper ID and date to be shown that corresponses to the person.
foreach (var transactionfound in TransactionQuery)
{
idgiven = transactionfound.customerid;
datebeginning = DateTime.Parse(transactionfound.datestart);
break;
}
//set the datetime interval to show the proper grouping later on
int xyy = datebeginning.Year;
//This is suppose to show where and how I can seperate the transaction of single and double pricing.
foreach (var transactionfound in TransactionQuery)
{
if (transactionfound.numofadults.ToString().Contains("1"))
{
singleddigit = transactionfound.numofadults;
}
if (transactionfound.numofadults.ToString().Contains("2"))
{
TwinAdultPricing = transactionfound.numofadults;
}
if (transactionfound.customerid == idgiven && DateTime.Parse(transactionfound.datestart).Year == xyy)
{
getpackagepriceinfo(transactionfound.datestart,ref singleddigit, ref TwinAdultPricing, ref NumberOfDaysSpent);
KidsSubPricing = transactionfound.numofkids * kidpricing;
//AdultPricing = transactionfound.numofadults * TwinAdultPricing;
subtotal += KidsSubPricing;
subtotal1 += AdultPricing;
daybegin = DateTime.Parse(transactionfound.datestart);
startthedate = daybegin.AddDays(NumberOfDaysSpent);
EndofDays = startthedate.ToString("d");
lstInvoice.Items.Add(string.Format(format2, daybegin, EndofDays, AdultPricing, KidsSubPricing));
}
else
{
lstInvoice.Items.Add(string.Format(format3, "Subtotal Amount",subtotal1, subtotal));
lstInvoice.Items.Add(" ");
getpackagepriceinfo(transactionfound.datestart,ref singleddigit, ref TwinAdultPricing, ref NumberOfDaysSpent);
KidsSubPricing = transactionfound.numofkids * kidpricing;
//AdultPricing = transactionfound.numofadults * singleddigit;
subtotal += KidsSubPricing;
subtotal1 += AdultPricing;
daybegin = DateTime.Parse(transactionfound.datestart);
startthedate = daybegin.AddDays(NumberOfDaysSpent);
EndofDays = startthedate.ToString("d");
lstInvoice.Items.Add(string.Format(format2, daybegin, EndofDays, AdultPricing, KidsSubPricing));
idgiven = transactionfound.customerid;
xyy = DateTime.Parse(transactionfound.datestart).Year;
}
if (idgiven == "")
{
lstInvoice.Items.Clear();
lstInvoice.Items.Add(string.Format(format1, "Sorry no Transaction Found For" + " ", tempvariable));
}
//else
//{
// lstInvoice.Items.Add(string.Format(format3, "Subtotal Amount", subtotal1, subtotal));
// lstInvoice.Items.Add("");
//}
}lstInvoice.Items.Add(string.Format(format3, "Subtotal Amount", subtotal1, subtotal));
}
}
private void getCustomerIDFirstName(out string tempp, out string idd)
{
string[] temp = cmbcustomerinfo.SelectedItem.ToString().Split(' ');
tempp = temp[1];
idd = temp[0];
}
private void getpackagepriceinfo(string date, ref double CostPerSingleAdult, ref double CostPerTwoAdults, ref byte numofdays1)
{
//set the information here, so we can recall the csv file into the main program.
string[] production = File.ReadAllLines(#"C:\temp\PackagePrice.csv");
var productQuery = from myLinesshown in production
let myfield1 = myLinesshown.Split(',')
let numofdays = byte.Parse(myfield1[0])
let startdateshown = myfield1[1]
let twinadult = myfield1[2]
let singlepricing = myfield1[3]
where startdateshown == date
select new
{
numofdays,
startdateshown,
twinadult,
singlepricing
};
//setting the factor of the private function doubles and bytes to be able to get recalled, back to the top.
foreach (var xyz in productQuery)
{
numofdays1 = xyz.numofdays;
CostPerTwoAdults = double.Parse(xyz.twinadult);
CostPerSingleAdult = double.Parse(xyz.singlepricing);
date = xyz.startdateshown;
break;
}
}
//redo the customer information, so we can recall the string of customer id inorder to recall proper functionality.
private void getcustomerinfo(string customerid){
string[] myfile = File.ReadAllLines(#"C:\temp\customerinfo.csv");
var myquery = from mylines in myfile
let myfield = mylines.Split(',')
let names = myfield[1]
let lastname = myfield[2]
let id = myfield[0]
where id == customerid
select new { id, names, lastname};}
}
}
Fix your variable names.
Refactor your code into smaller and tidier methods.
The problem becomes MUCH Clearer
You have a method called getpackagepriceinfo which takes the parameters
(string date, ref double adult, ref double single12, ref byte numofdays1)
where adult is costPerSingleAdult and single12 is costPerTwoAdults
When calling this method you have passed the variable singleddigit to the now renamed paramter costPerTwoAdults. What does that even mean? Did you realize you haven't used this variable within your code
Put code clarity first. When the code is easy to understand and working correctly, then you can start rewriting sections for speed/memory/reduced LoC/experimental language features/whatever other reason, when you do that write a comment showing the codes original intention so that when a bug gets written in to the new code you can find it quickly.
after edit
That's definitely an improvement. You can see now that you've got the number of adults for each transaction, but you've assigned this number into the variable used for pricing. I think you need to refer back to the specification, which I read as "if there are 2 adults and a two adult price, then charge the twin price. Else if there is no two adult price charge 2 * single adult price, else charge the adult price" your code should read the same.
Decimal adultPrice
if ( twoAdults && twinPrice > 0)
adultPrice = twinPrice;
else if ( twoAdults )
adultPrice = 2 * singlePrice;
else
adultPrice = singlePrice;
Note that this won't work if there are more than 2 adults. Not sure if that meets the specification
SO the new Coding is the following. Thanks to James Barrass I was able to properly fix the coding to work. The problem was the following
numberAdults = byte.Parse(Transaction.NumberofAdults);
if(numberAdults == 2)
adultpricing = AdultCost*2;
else
adultpricing = CostSingle;
Because of the following code above the entire coding is able to properly work now.
private void Form1_Load(object sender, EventArgs e)
{
string[] myfile = File.ReadAllLines(#"C:\temp\customerinfo.csv");
var myQuery = from mylines in myfile
let myfield = mylines.Split(',')
let CustomerID = myfield[0]
let CustomerFirstName = myfield[1]
let CustomerLastName = myfield[2]
orderby CustomerID, CustomerLastName, CustomerFirstName
select new {
CustomerID, CustomerFirstName, CustomerLastName
};
foreach (var customerinfo in myQuery) { cmbCustomer.Items.Add(customerinfo.CustomerID + " " + customerinfo.CustomerFirstName + " " + customerinfo.CustomerLastName); }
}
private void getCustomerFirstandID(out string customerfirst, out string idd)
{
string[] tempp = cmbCustomer.SelectedItem.ToString().Split(' ');
customerfirst = tempp[1];
idd = tempp[0];
}
private void getCustomerInfo(string StatedID)
{
string[] myfile = File.ReadAllLines(#"C:\temp\customerinfo.csv");
var myQuery = from mylines in myfile
let myfield = mylines.Split(',')
let CustomerID = myfield[0]
let CustomerFirstName = myfield[1]
let CustomerLastName = myfield[2]
where CustomerID == StatedID
select new
{
CustomerID,
CustomerFirstName,
CustomerLastName
};
}
private void getPackagePriceInfo(DateTime date, ref double CostofAdults, ref double CostofSingle, ref byte NumberofDaysShown)
{
string[] myGivenFile = File.ReadAllLines(#"C:\temp\PackagePrice.csv");
var myPackageTransaction = from myLinesGiven in myGivenFile
let myFieldShown = myLinesGiven.Split(',')
let NumberofDays = myFieldShown[0]
let StartDate = DateTime.Parse(myFieldShown[1])
let TwinAdult = myFieldShown[2]
let SingleAdult = myFieldShown[3]
where StartDate == date
select new {
NumberofDays, StartDate, TwinAdult, SingleAdult
};
foreach (var Package in myPackageTransaction) {
CostofSingle = double.Parse(Package.SingleAdult);
CostofAdults = double.Parse(Package.TwinAdult);
NumberofDaysShown = byte.Parse(Package.NumberofDays);
date = Package.StartDate;
break;
}
}
private void cmbCustomer_SelectedIndexChanged(object sender, EventArgs e)
{
string customerfirstvariable = "";
string iddvariable = "";
getCustomerFirstandID(out customerfirstvariable, out iddvariable);
getCustomerInfo(iddvariable);
string format1 = "{0,55}{1,5}";
string format2 = "{0,-5:d}{1,15:d}{2,20:c}{3,20:c}";
string format3 = "{0,25}{1,19:c}{2,20:c}";
string format4 = "{0,-15}{1,72:c}";
string[] myGivenFile1 = File.ReadAllLines(#"C:\temp\holidaytrans.csv");
var myHolidayTransaction = from myLinesGiven1 in myGivenFile1
let myFieldShown = myLinesGiven1.Split(',')
let CustomerGivenID = myFieldShown[0]
let PackageStartDate = DateTime.Parse(myFieldShown[1])
let NumberofAdults = myFieldShown[2]
let NumberofKids = myFieldShown[3]
where CustomerGivenID == iddvariable
orderby PackageStartDate
select new
{
CustomerGivenID, PackageStartDate, NumberofAdults, NumberofKids
};
lstInvoice.Items.Clear();
// foreach (var transactionfound in myHolidayTransaction) {
//set up all variables used or to be used.
string EndofDays = "";
DateTime daybegin;
DateTime startthedate;
DateTime datebeginning = DateTime.Now;
string idgiven = "";
double AdultCost = 0;
byte DaysUsed = 0;
double adultpricing = 0;
double KidsPricing = 0;
double KidsCost = 3300;
double subtotal = 0;
double totalamt = 0;
double subtotal1 = 0;
double total1 = 0;
double total = 0;
double CostSingle = 0;
byte numberAdults = 0;
double adultgiven = 0;
int xyz = 0;
foreach (var Transaction in myHolidayTransaction)
{
idgiven = Transaction.CustomerGivenID;
lstInvoice.Items.Add("Purchase Date EndDate Adult Price Kid Price");
datebeginning = Transaction.PackageStartDate;
xyz = datebeginning.Year;
break;
}
foreach (var Transaction in myHolidayTransaction)
{
if (Transaction.PackageStartDate.Year == xyz) {
getPackagePriceInfo(Transaction.PackageStartDate,ref AdultCost, ref CostSingle, ref DaysUsed);
KidsPricing = KidsCost * byte.Parse(Transaction.NumberofKids);
numberAdults = byte.Parse(Transaction.NumberofAdults);
if(numberAdults == 2)
adultpricing = AdultCost*2;
else
adultpricing = CostSingle;
subtotal += KidsPricing;
subtotal1 += adultpricing;
total += KidsPricing;
total1 += adultpricing;
daybegin = Transaction.PackageStartDate;
startthedate = daybegin.AddDays(DaysUsed);
EndofDays = startthedate.ToString("d");
lstInvoice.Items.Add(string.Format(format2, startthedate, EndofDays, adultpricing, KidsPricing));}
else
{
lstInvoice.Items.Add(string.Format(format3, "Subtotal Amount", subtotal1, subtotal));
lstInvoice.Items.Add(" ");
getPackagePriceInfo(Transaction.PackageStartDate, ref AdultCost, ref CostSingle, ref DaysUsed);
KidsPricing = KidsCost * byte.Parse(Transaction.NumberofKids);
numberAdults = byte.Parse(Transaction.NumberofAdults);
if (numberAdults == 2)
adultpricing = AdultCost * 2;
else
adultpricing = CostSingle;
subtotal = KidsPricing;
subtotal1 = adultpricing;
total += KidsPricing;
total1 += adultpricing;
daybegin =Transaction.PackageStartDate;
startthedate = daybegin.AddDays(DaysUsed);
EndofDays = startthedate.ToString("d");
lstInvoice.Items.Add(string.Format(format2, startthedate, EndofDays, adultpricing, KidsPricing));
idgiven = Transaction.CustomerGivenID;
xyz = Transaction.PackageStartDate.Year;
}}
if (idgiven == "")
{
lstInvoice.Items.Clear();
lstInvoice.Items.Add(string.Format(format1, "Sorry no Transaction Found For" + " ", customerfirstvariable));
}
else
lstInvoice.Items.Add(" ");
lstInvoice.Items.Add(string.Format(format3, "Subtotal Amount", subtotal1, subtotal));
lstInvoice.Items.Add(" ");
lstInvoice.Items.Add(string.Format(format3, "Total Amount", total1, total));
}
}
}

Categories