I need some idea for the Design of the following Program/Function.
My Program calculates Prices for Tools.
Every Tool has a Diameter and a List of Productionsteps to build this tool.
To get the Production Steps the program reads a XML File with 56 Productionsteps at the begin and creates an object for every Step. After the Creation it adds that object in a List.
The Konstruktor of the Tool knows what Steps are required to build the tool and get them out of the List of the Main Program and adds them to the List of the Tool.
Pseudo Code:
main.cs
List<ProductionStep> listOfAllProductionstep = readAllPS(../pfad/);
Tool abc = new Tool();
tool.cs
private List<ProductionStep> psList;
public Tool() {
foreach (ProductionStep ps in listOfAllProductionstep) {
switch(ps.Name) {
case "Abc":
psList.Add(ps);
break;
...
}
}
}
The Problem is now, each of the 56 Productionstep has it own formular to calculate the cost for this step.
My first idea was to use a Switch Case construct in the calculatePrice Function of the tool. But i have to check every step with the 56 availiable Steps to get the Right Formular for this step.
Now my Question. Is there a better solution to this?
Mabe you are looking for something like this:
class ProductionStep
{
public string name;
public decimal calculatCosts()
{
return 100;
}
}
List<ProductionStep> listOfAllProductionstep;
private void button5_Click(object sender, EventArgs e)
{
List<ProductionStep> psList = new List<ProductionStep>();
psList.Add(listOfAllProductionstep.Find(o => o.name == "Abc"));
psList.Add(listOfAllProductionstep.Find(o => o.name == "Def"));
decimal totalCosts = 0;
foreach (ProductionStep ps in psList)
totalCosts += ps.calculatCosts();
}
Related
Good day fellow helpers, i have following problem:
(running MS Visual Community Edition 2015)
private void button4_Click(object sender, EventArgs e) // Senden
{
serialPort2.WriteLine("SR,00,002\r\n");
textBox1.Text = "gesendet";
textBox3.Text = "";
try
{
System.IO.StreamReader file = new System.IO.StreamReader("C:\\blub.txt");
String line = file.ReadToEnd();
string Hallo = line; \\in the beginning there is "0" in the file
file.Close();
decimal counter = Convert.ToDecimal(Hallo); \\just for testing
counter++;
string b = serialPort2.ReadLine();
string[] b1 = Regex.Split(b, "SR,00,002,"); \\cuts off unwanted input from device
decimal b2 = decimal.Parse(b1[1]); \\number like -3000
System.IO.StreamWriter test = new System.IO.StreamWriter("C:\\blub.txt");
test.WriteLine(counter);
test.Close();
textBox7.Text = "Das ist counter:" + counter;
}
catch (TimeoutException)
{
textBox3.Text = "Timeout";
throw;
}
}
Now, the Serialport is a device that returns a lengthmeasurment. As it is a bit weird, or just the way its build it start with a negitve number (between -5000 and -3370). Now as i want to get measurement on the screen that is realistic i want to set the value to 0 and calculate the difference.
Means: I start the programm - press send - get a value (say -3000) - press send again (after pushing the seonsor in) and get the value that its been pushed in > 0 by adding the difference to 0.
I only learned to store values externally when i had a C course a year back like i did within my programm. Is there a way to store the value from the first measurement in the programm so i can use it on the next send/try?
The counter was just for testing and I would exchange it for the "decimal b2"
I hope there is an easy fix for that, not really a pro with C# yet but i'm eager to learn. I thank the willing helpers in advance, MfG, Chris
OK, I will simplify this in order to show concept so it will not have all the code you are actually using.
So, what you want is to click on button, get some values and store them for next click.
Value is stored in variable. If you have variable in function that is handler for click event, as soon as function completes execution, value will be destroyed.
So, what you need is to create variable in outer scope (class level). Your function is already in class of the form so let's get to code:
class Form1
{
string BetweenClickStorage;
private void button4_Click(object sender, EventArgs e)
{
//Load data here
BetweenClickStorage = LoadedData;
}
}
After this, when you click again on the button, value will still be in BetweenClickStorage. It will be also available to all other buttons click handlers and other code in that form.
If I'm understanding your question correctly, the answer is simply to declare a variable outside the try/catch:
//declare variable //
var measurement;
// TRY #1 //
try
{
//assign value to the variable here
}
catch
{
}
// TRY #2 //
try
{
// reference variable here
}
catch
{
}
I am trying to figure out the most efficient way to calculate first, second, and third place for a simple C# program in which the purpose is to find the winner, 2nd place, and 3rd place and show their names accordingly however, my code seems way to large for such a simple task. I am new and I an using If statements to complete the required calculation but, I know there is a better way. Can someone enlighten me?
Here is my current code and where I stopped after realizing the amount a code this is going to take.
private void calculateButton_Click(object sender, EventArgs e)
{
// Define Name and Time Variables
string runnerone = runnerOneNameTextBox.Text; // Runner One Name
string runnertwo = runnerTwoNameTextBox.Text; // Runner Two Name
string runnerthree = runnerThreeNameTextBox.Text; // Runner Three Name
double runnerOneTime = double.Parse(runnerOneTimeTextBox.Text); // Runner One Time
double runnerTwoTime = double.Parse(runnerTwoTimeTextBox.Text); // Runner Two Time
double runnerThreeTime = double.Parse(runnerThreeTimeTextBox.Text); // Runner Three Time
//-------------------------------------------------------------------------
// Start of the If statement to calculate who is first, second, and third.
//-------------------------------------------------------------------------
// FIRST PLACE CODE:
if (runnerOneTime > runnerTwoTime && runnerOneTime > runnerThreeTime) // Runner One is greater than everyone
{
firstPlaceLabel.Text = runnerOneNameTextBox.Text;
firstPlaceTrophyLabel.Text = runnerOneNameTextBox.Text;
}
else if (runnerOneTime == runnerTwoTime && runnerOneTime > runnerThreeTime) // Runner one is equal to runner two
{
firstPlaceLabel.Text = runnerOneNameTextBox.Text;
firstPlaceLabel.Text = runnerTwoNameTextBox.Text;
firstPlaceTrophyLabel.Text = runnerOneNameTextBox.Text;
firstPlaceTrophyLabel.Text = runnerTwoNameTextBox.Text;
}
else if (runnerOneTime > runnerTwoTime && runnerOneTime == runnerThreeTime)
}
}
}
You have a list of three runners, so let the .NET list sorting functionality come to your rescue:
private class RunnersAndTimes
{
public string Name {get};
public double Time {get};
public RunnersAndTimes(string name, double time)
{
Time = time;
Name = name;
}
}
...
private void calculateButton_Click(object sender, EventArgs e)
{
var runnersAndTimes = new List<RunnersAndTimes> {
new RunnersAndTimes(runnerOneNameTextBox.Text,
double.Parse(runnerOneTimeTextBox.Text)),
new RunnersAndTimes(runnerTwoNameTextBox.Text,
double.Parse(runnerTwoTimeTextBox.Text)),
new RunnersAndTimes(runnerThreeNameTextBox.Text,
double.Parse(runnerThreeTimeTextBox.Text))
};
var orderedRunners = runnersAndTimes.OrderBy(runner => runner.Time).ToList();
firstPlaceLabel.Text = orderedRunners[0];
secondPlaceLabel.Text = orderedRunners[1];
thirdPlaceLabel.Text = orderedRunners[2];
}
I'm have a combobox listing some single byte cmds that can be sent to some custom hardware I've developed. With the C# code below, users can currently select commands from the cbCANcmd by name only. I also found ways to display the values only, but prefer to display both name and number.
How can I display both hex value & cmd in the cb dropdown? e.g. 0d - CommsSoftReset
And still able to type in un-enumerated values, like 05, for unlisted commands?
Can I hide more dangerous items easily(i.e. 09-WipeAllFlash), but still numerically enter them as per #2 above?
Note: The enum is from a straight C language .h file, and the header is changing more times daily than the c# app. For this reason, I'm hoping to avoid adding [Description()] for each value, or dramatically change the formatting, since it will have to be copied and redone many times as we continue development)
P.S. I normally write only in simple C, for the 8bit micro receiving these commands..As this is my first test app in c#, please be gentle :)
enum COMMS_MESSAGE_ID_t : byte
{
CommsRAMRead = 0x00,
CommsRAMWrite = 0x01,
CommsCommitRAMbufferToFlash = 0x02,
CommsWipeAllFlash = 0x0c,
CommsSoftReset = 0x0d,
CommsGetVersion = 0xff
}
private void SendTab_Enter(object sender, EventArgs e)
{
//need to populate the pulldowns with the available commands
cbCANcmd.DataSource = Enum.GetValues(typeof(COMMS_MESSAGE_ID_t));
}
private void SendDownlinkCmd_Click(object sender, EventArgs e)
{
// send the command selected in the send tab's combobox
byte CANcmd = (byte)(COMMS_MESSAGE_ID_t)cbCANcmd.SelectedValue;//first byte
}
If this is a WinForms app, here is a possible solution for #1. If this works, we can move on from there.
public partial class Form1 : Form
{
private void Form1_Load(object sender, EventArgs e)
{
foreach (var val in Enum.GetNames(typeof(COMMS_MESSAGE_ID_t)))
{
cbCANcmd.Items.Add(new CommsMessage(val));
}
}
}
public class CommsMessage
{
public string Name { get; set; }
public COMMS_MESSAGE_ID_t Message { get; set; }
public CommsMessage(string msgName)
{
Name = msgName;
Message = (COMMS_MESSAGE_ID_t)Enum.Parse(typeof (COMMS_MESSAGE_ID_t), msgName);
}
public override string ToString()
{
return string.Format("{0:x} - {1}", Message, Name);
}
}
Then, any time you get the value of the ComboBox.SelectedItem, you can do something like:
COMMS_MESSAGE_ID_t msg = (cbCANcmd.SelectedItem as CommsMessage).Message;
I've left out lots of exception handling that you should probably do, but I hope this is helpful.
I just want to know how to use the updated rate throughout the whole program. Here's my code so far for reference...
//Form 1
private void update_Click(object sender, EventArgs e)
{
if (fromcountry.Text == tocountry.Text)
{
MessageBox.Show(" Please Choose Two Different Currencies To Use This Function", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
btnconvert.Enabled = true;
Exchange_Rate frm = new Exchange_Rate();
frm.Show(this);
}
}
//Form 1 one of the comboboxes for selecting 2nd country
private void tocountry_SelectedIndexChanged(object sender, EventArgs e)
{
btnupdate.Enabled = true;
btnconvert.Enabled = true;
txtvalue.Enabled = true;
exchange();
}
private void exchange()
{
if (fromcountry.Text == tocountry.Text)
{
lblexchange.Text = "1";
}
else if (fromcountry.Text == "SGD - Singapore Dollar" && tocountry.Text == "USD - US Dollar")
{
lblexchange.Text = "1.26";
}
else if (fromcountry.Text == "SGD - Singapore Dollar" && tocountry.Text == "MYR - Malaysian Ringgit")
{
lblexchange.Text = "2.35";
}
else if (fromcountry.Text == "SGD - Singapore Dollar" && tocountry.Text == "EUR - Euro")
{
lblexchange.Text = "0.60";
}
//Form 2
private void btnok_Click(object sender, EventArgs e)
{
try
{
double exchange;
exchange = Double.Parse(txtcurrent.Text);
var frm = (currencyconverter)this.Owner;
frm.PassValue(txtcurrent.Text);
this.Close();
}
catch
{
MessageBox.Show("Please Enter Numbers", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
txtcurrent.Text = "";
}
}
I know by using if-else method it's too vague to get rates at the start of the program and I'm just a student learning simple programming. But still I need to know how use the updated rate when I press the same conversion again. If there's not enough info, I can help you get more coding
You can use a shared currency object to hold information about rate of the currency
public class Currency
{
private Currency(string name)
{
Name = name;
}
public string Name {get; private set;}
public decimal Rate {get; private set;}
private void SetRate(decimal rate)
{
Rate = rate;
OnRateChanged(this);
}
public static event EventHandler RateCanged;
private static OnRateChanged(Currency currency)
{
var handler = RateChanged;
if(handler != null)
{
handler(currency, EventArgs.Empty);
}
}
private Dictionary<string, Currency> currencies = new Dictionary<string, Currency>();
public static Currency GetCurrency(string name)
{
Currency currency;
if(!currencies.TryGetValue(name, out currency))
{
currency = new Currency(name);
currencies[name] = currency;
}
}
}
So you had a simple shared rate's storage, you can use it everywere
class Form1
{
public Form1()
{
...
Currency.RateChanged += RateChanged;
}
private void RateChanged(object source, EventArgs e)
{
labelRate.Text = Currency.GetCurrency("USD").Rate;
}
}
class Form2
{
public Form2()
{
...
rateTextBox.Text = Currency.GetCurrency("USD").Rate.ToString();
}
void updateButtin_Click()
{
Currency.GetCurrency("USD").SetRate(decimal.Parse(rateTextBox.Rate));
}
}
There are a number of different ways to achieve this and it's going to be impossible to answer in full without making a design decision for you. The approaches which spring to mind are either using a configuration file, database or some external source.
As you've pointed out you need to have some way of storing these values outside your application so if an conversion rate changes you can update it in your software without rewriting your code.
You need to make a decision on how to do this.
Database
A database is probably the most flexible, however it will require you to maintain it. There are countless mechanisms to access a database from ADO.NET, through Linq2SQL or NHibernate.
External Source
I'm sure there are various online sources you could get currency data from, either a webservice or RSS feed you could access - it could be worth reading up on these?
Configuration
Personally this is the approach I'd suggest. As you're clearly not very experienced I'd suggest the easier solution of config, work on your database skills - in the future it will be a no brainer for you.
I would use the AppSettings section of the config file similar to here.
You would add an App.Config file to your application, this would store the conversion rates so you can update them without needing to rewrite your tool. You can create a new file by right clicking on the project and adding New Item, then Configuration File.
You'll also need to add a reference onto System.Configuration as it's not referenced by default.
There is a section in the config file called AppSettings, this is a simple section for key/value type properties. We're going to create a set of app settings, one for each conversion rate. For example:
You can then use your countries to generate this key. For Example:
string settingKey = string.Concat(fromcountry.Text, "_", tocountry.Text);
You can access this configuration value using the ConfigurationManager:
decimal rate = decimal.Parse(ConfigurationManager.AppSettings[settingKey]);
Once you've got the rate you'll be able to perform your multiplication to calculate the correct values.
Please bear in mind there's no error handling in here - what happens if there country is not known or the config doesn't contain the exchange rate!
If you are not using actual currency data and just a static data, then here are the steps to improve:
Have one currency as base currency. Usually it's USD with value 1
Store all the rates for all the currencies in a collection [Key,Value] in USD.
Here the Key is your Currency Code eg, SGD and value is its rate in USD.
Now you can pass the selected dropdown value as Key to retrieve the value eg, Currencies[toCountry.Code]
Now to get the rate. You can divide like this to get value of FromCountry in terms of ToCountry
var FromCountryRate = Currencies[FromCountry.Value]/Currencies[ToCountry.Value];
What would be the best way to develop a text box that remembers the last x number of entries that were put into it. This is a standalone app written with C#.
This is actually fairly easy, especially in terms of showing the "AutoComplete" part of it. In terms of remembering the last x number of entries, you are just going to have to decide on a particular event (or events) that you consider as an entry being completed and write that entry off to a list... an AutoCompleteStringCollection to be precise.
The TextBox class has the 3 following properties that you will need:
AutoCompleteCustomSource
AutoCompleteMode
AutoCompleteSource
Set AutoCompleteMode to SuggestAppend and AutoCompleteSource to CustomSource.
Then at runtime, every time a new entry is made, use the Add() method of AutoCompleteStringCollection to add that entry to the list (and pop off any old ones if you want). You can actually do this operation directly on the AutoCompleteCustomSource property of the TextBox as long as you've already initialized it.
Now, every time you type in the TextBox it will suggest previous entries :)
See this article for a more complete example: http://www.c-sharpcorner.com/UploadFile/mahesh/AutoCompletion02012006113508AM/AutoCompletion.aspx
AutoComplete also has some built in features like FileSystem and URLs (though it only does stuff that was typed into IE...)
#Ethan
I forgot about the fact that you would want to save that so it wasn't a per session only thing :P But yes, you are completely correct.
This is easily done, especially since it's just basic strings, just write out the contents of AutoCompleteCustomSource from the TextBox to a text file, on separate lines.
I had a few minutes, so I wrote up a complete code example...I would've before as I always try to show code, but didn't have time. Anyway, here's the whole thing (minus the designer code).
namespace AutoComplete
{
public partial class Main : Form
{
//so you don't have to address "txtMain.AutoCompleteCustomSource" every time
AutoCompleteStringCollection acsc;
public Main()
{
InitializeComponent();
//Set to use a Custom source
txtMain.AutoCompleteSource = AutoCompleteSource.CustomSource;
//Set to show drop down *and* append current suggestion to end
txtMain.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
//Init string collection.
acsc = new AutoCompleteStringCollection();
//Set txtMain's AutoComplete Source to acsc
txtMain.AutoCompleteCustomSource = acsc;
}
private void txtMain_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//Only keep 10 AutoComplete strings
if (acsc.Count < 10)
{
//Add to collection
acsc.Add(txtMain.Text);
}
else
{
//remove oldest
acsc.RemoveAt(0);
//Add to collection
acsc.Add(txtMain.Text);
}
}
}
private void Main_FormClosed(object sender, FormClosedEventArgs e)
{
//open stream to AutoComplete save file
StreamWriter sw = new StreamWriter("AutoComplete.acs");
//Write AutoCompleteStringCollection to stream
foreach (string s in acsc)
sw.WriteLine(s);
//Flush to file
sw.Flush();
//Clean up
sw.Close();
sw.Dispose();
}
private void Main_Load(object sender, EventArgs e)
{
//open stream to AutoComplete save file
StreamReader sr = new StreamReader("AutoComplete.acs");
//initial read
string line = sr.ReadLine();
//loop until end
while (line != null)
{
//add to AutoCompleteStringCollection
acsc.Add(line);
//read again
line = sr.ReadLine();
}
//Clean up
sr.Close();
sr.Dispose();
}
}
}
This code will work exactly as is, you just need to create the GUI with a TextBox named txtMain and hook up the KeyDown, Closed and Load events to the TextBox and Main form.
Also note that, for this example and to make it simple, I just chose to detect the Enter key being pressed as my trigger to save the string to the collection. There is probably more/different events that would be better, depending on your needs.
Also, the model used for populating the collection is not very "smart." It simply deletes the oldest string when the collection gets to the limit of 10. This is likely not ideal, but works for the example. You would probably want some sort of rating system (especially if you really want it to be Google-ish)
A final note, the suggestions will actually show up in the order they are in the collection. If for some reason you want them to show up differently, just sort the list however you like.
Hope that helps!
I store the completion list in the registry.
The code I use is below. It's reusable, in three steps:
replace the namespace and classname in this code with whatever you use.
Call the FillFormFromRegistry() on the Form's Load event, and call SaveFormToRegistry on the Closing event.
compile this into your project.
You need to decorate the assembly with two attributes: [assembly: AssemblyProduct("...")] and [assembly: AssemblyCompany("...")] . (These attributes are normally set automatically in projects created within Visual Studio, so I don't count this as a step.)
Managing state this way is totally automatic and transparent to the user.
You can use the same pattern to store any sort of state for your WPF or WinForms app. Like state of textboxes, checkboxes, dropdowns. Also you can store/restore the size of the window - really handy - the next time the user runs the app, it opens in the same place, and with the same size, as when they closed it. You can store the number of times an app has been run. Lots of possibilities.
namespace Ionic.ExampleCode
{
public partial class NameOfYourForm
{
private void SaveFormToRegistry()
{
if (AppCuKey != null)
{
// the completion list
var converted = _completions.ToList().ConvertAll(x => x.XmlEscapeIexcl());
string completionString = String.Join("¡", converted.ToArray());
AppCuKey.SetValue(_rvn_Completions, completionString);
}
}
private void FillFormFromRegistry()
{
if (!stateLoaded)
{
if (AppCuKey != null)
{
// get the MRU list of .... whatever
_completions = new System.Windows.Forms.AutoCompleteStringCollection();
string c = (string)AppCuKey.GetValue(_rvn_Completions, "");
if (!String.IsNullOrEmpty(c))
{
string[] items = c.Split('¡');
if (items != null && items.Length > 0)
{
//_completions.AddRange(items);
foreach (string item in items)
_completions.Add(item.XmlUnescapeIexcl());
}
}
// Can also store/retrieve items in the registry for
// - textbox contents
// - checkbox state
// - splitter state
// - and so on
//
stateLoaded = true;
}
}
}
private Microsoft.Win32.RegistryKey AppCuKey
{
get
{
if (_appCuKey == null)
{
_appCuKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(AppRegistryPath, true);
if (_appCuKey == null)
_appCuKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(AppRegistryPath);
}
return _appCuKey;
}
set { _appCuKey = null; }
}
private string _appRegistryPath;
private string AppRegistryPath
{
get
{
if (_appRegistryPath == null)
{
// Use a registry path that depends on the assembly attributes,
// that are presumed to be elsewhere. Example:
//
// [assembly: AssemblyCompany("Dino Chiesa")]
// [assembly: AssemblyProduct("XPathVisualizer")]
var a = System.Reflection.Assembly.GetExecutingAssembly();
object[] attr = a.GetCustomAttributes(typeof(System.Reflection.AssemblyProductAttribute), true);
var p = attr[0] as System.Reflection.AssemblyProductAttribute;
attr = a.GetCustomAttributes(typeof(System.Reflection.AssemblyCompanyAttribute), true);
var c = attr[0] as System.Reflection.AssemblyCompanyAttribute;
_appRegistryPath = String.Format("Software\\{0}\\{1}",
p.Product, c.Company);
}
return _appRegistryPath;
}
}
private Microsoft.Win32.RegistryKey _appCuKey;
private string _rvn_Completions = "Completions";
private readonly int _MaxMruListSize = 14;
private System.Windows.Forms.AutoCompleteStringCollection _completions;
private bool stateLoaded;
}
public static class Extensions
{
public static string XmlEscapeIexcl(this String s)
{
while (s.Contains("¡"))
{
s = s.Replace("¡", "¡");
}
return s;
}
public static string XmlUnescapeIexcl(this String s)
{
while (s.Contains("¡"))
{
s = s.Replace("¡", "¡");
}
return s;
}
public static List<String> ToList(this System.Windows.Forms.AutoCompleteStringCollection coll)
{
var list = new List<String>();
foreach (string item in coll)
{
list.Add(item);
}
return list;
}
}
}
Some people shy away from using the Registry for storing state, but I find it's really easy and convenient. If you like, You can very easily build an installer that removes all the registry keys on uninstall.