Calculate code to a new class.cs - c#

i want to set my code to another class, example: A new class AgeCalculate.cs, How can I get the data from AgeCalculate.cs back to my Button_Click event.
Example:
AgeCalculate Calculate = new AgeCalculate();?
and from the class to Form1 =?
My code is now in button_Click.
double startkapital = 0;
double procentsats = 0;
int år = 0;
double kapital = 0;
startkapital = int.Parse(sKapTxt.Text);
procentsats = int.Parse(proSatsTxt.Text);
kapital = startkapital;
while (kapital < startkapital * 2)
{
kapital = kapital * (1 + procentsats / 100);
år = år + 1;
listBox1.Items.Add("Årtal: " + år);
listBox1.Items.Add("Kapital: " + kapital + "kr ");
listBox1.Items.Add(" ");
}
listBox1.Items.Add("Totalt antal år: " + år + "år ");
listBox1.Items.Add("Total kapital: " + kapital + "kr ");
listBox1.Items.Add(" ");
double exaktaåret = år / ((100 + procentsats) / 100);
listBox1.Items.Add(string.Format("Kapitalet fördubblades efter {0:0} år", exaktaåret));
if (kapital >= 2 * startkapital)
{
listBox1.Visible = true;
}

First, under your button_Click in your code behind C# event you will need to create an object of AgeCalculate.cs. I am not sure whether this is the correct way or not in C# but here it goes:
AgeCalculate calc = new AgeCalculate();
Then you use the object you created to call a function which returns the age calculated like this:
calc.FunctionName;
But before all, make sure in your class AgeCalculate there is a Function which has a return to return calculated age. And then once you do calc.FunctionName the calculated age will be returned.
Example:
In AgeCalculate.cs
public string calc(string value1)
{
//calculate age
String str = calculated age;
return str;
}
In C#
AgeCalculate calculate = new AgeCalculate();
calculate.calc(pass the argument you will use to calculate age);

You can create a public property in your AgeClass and get that property in your button click.

Related

How can user input function in C#

I have made bisection method program in C# Console Application. Bisection method works, but for function which is already written in the code. I want to edit program that user can input function which they want to use for bisection method. For example Console.ReadLine() for input "x^2 + x - 2" and then I want it automatically written after return in the code below.
static double Function(double x)
{
return x*x - 2;
} //this is Function which I used in code.
Here is the whole code. (as i mentioned it works for function which is written in static double Function(double x) part
using System;
namespace MPI
{
class MainClass
{
public static void Main(string[] args)
{
// in [a,b]
double inPoc = 0; //a
double inKraj = 0; //b
double sredina = 0;
double tacnost = 0;
Start:
int i = 0; //brojac
Console.Write("Unesite početak intervala: ");
inPoc = Convert.ToDouble(Console.ReadLine());
Console.Write("Unesite kraj intervala: ");
inKraj = Convert.ToDouble(Console.ReadLine());
Console.Write("Unesite tacnost: ");
tacnost = Convert.ToDouble(Console.ReadLine());
sredina = (inPoc + inKraj) / 2;
if (Function(inPoc) * Function(inKraj) < 0)
{
while ((Math.Abs(inPoc - inKraj)) > tacnost)
{
sredina = (inPoc + inKraj) / 2;
Console.WriteLine("trenutno X: " + sredina);
Console.WriteLine("Funkcija za trenutno x ima vrednost: " + Function(sredina));
Console.WriteLine("");
i++;
if (Function(sredina) < 0)
{
inPoc = sredina;
}
else
{
inKraj = sredina;
}
}
Console.WriteLine("X: " + sredina);
Console.WriteLine("Broj izvrsenih koraka je " + i);
}
else
{
Console.WriteLine("Krajevi intervala funkcije su istog znaka");
Console.WriteLine();
}
goto Start; //sluzi da vrati program na pocetak kako bi ga opet koristili
}
static double Function(double x)
{
return x*x - 2; //primer funkcije
}
}
}
Looks like this question is asking about the same.
There are two solutions to do this:
Solution 1 - just use Flee.
Copy-paste from documentation:
ExpressionContext context = new ExpressionContext();
VariableCollection variables = context.Variables;
variables.Add("a", 100);
variables.Add("b", 1);
variables.Add("c", 24);
IGenericExpression<bool> e = context.CompileGeneric<bool>("(a = 100 OR b > 0) AND c <> 2");
bool result = e.Evaluate();
So you can do the same, just change input/output types and put your input line into the CompileGeneric
Solution 2 - parse input string manually.
So question can be divided to the two parts:
How to parse input string into the expression tree.
How to execute this tree.
For the first item - please check reverse polish notation. It allows to construct computation stack.
Next you will able to compute your expression tree. Each operand (after trimming) will have variable or integer constant. So just replace variable to the actual value and just parse string to the integer.

Unable to plot multiple lines in Fastline chart

I am trying to have a Fastline Chart (type chosen as I get lots of point to plot). I want to plot in the data I just got plus an average on the same chart. Should be easy but I keep getting an error "An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll".
The function is below, if I comment out the second series called [AverageTime"] I compile and work with one line.
Please note the function is async (.net 4.5) which I use for "await Task.Delay(Int32.Parse(txtbx_timing_delay.Text));". Not sure if this has anything to do with it as I presume I have a thread I am waiting for.
Any ideas on how to get round the issue?
private async void btn_timing_send_Click(object sender, EventArgs e)
{
int recursive_counter = 0, num = 0, num2 = 0;
double total_time = 0, average_time = 0, min_time = 0, max_time = 0, ave_plot = 0;
num2 = Int32.Parse(txtbx_iterations.Text); // number of required iterations
/*
* Just a word on timings - Windows is bad at doing timings in lower Microseconds and below so we need to do a few things to try and get
* accurate timings.
*
* As the general rule, when testing comms with completion time in the range of several microseconds it's recommended to implement
* the loop running 10,000...100,000 iterations in order to increase the accuracy of the measurement
*/
string str1 = "";
Stream stm = tcpclnt.GetStream();
byte[] payload;
string ID = txtbx_timing_send_data.Text;
str1 = "No Connection";
ID = ID.ToCharArray().Aggregate("", (result, c) => result += ((!string.IsNullOrEmpty(result) && (result.Length + 1) % 3 == 0) ? " " : "") + c.ToString());//add space every two chars to make hex
payload = ID.Split().Select(s => Convert.ToByte(s, 16)).ToArray(); //split the bytes into the array
if (ckbx_plot.Checked)
{
chrt_timings.Series["ResponseTimes"].ChartType = SeriesChartType.FastLine; //set type
chrt_timings.Series["ResponseTimes"].Color = Color.Blue; //set colour
chrt_timings.Series["AverageTime"].ChartType = SeriesChartType.FastLine; //set type
// chrt_timings.Series["AverageTime"].Color = Color.Red; //set colour
// chrt_timings.Series["AverageTime"].BorderDashStyle = ChartDashStyle.Dash;
chrt_timings.Legends.Clear(); // We do not need a legend
chrt_timings.ChartAreas[0].AxisX.IsMarginVisible = false;
}
do
{
try
{
Stopwatch timer = Stopwatch.StartNew();
long frequency = Stopwatch.Frequency;
long nanosecPerTick = (1000L * 1000L * 1000L) / frequency;
long startTick = timer.ElapsedTicks; //start of timed section
stm.Write(payload, 0, payload.Length);
byte[] input = new byte[tcpclnt.ReceiveBufferSize];
int k = stm.Read(input, 0, tcpclnt.ReceiveBufferSize);
Array.Resize(ref input, k); //crop the array to the amount of items it read in
str1 = string.Join(" ", input.Select(b => string.Format("{0:X2} ", b))); //format as hex bytes
long stopTick = timer.ElapsedTicks; //end of timed section
var timestamp = Convert.ToDouble((stopTick - startTick) * nanosecPerTick) / 1000000;
timer.Reset();
rchtxbox_timings.SelectionColor = Color.LimeGreen;
rchtxbox_timings.AppendText(str1 + "\r");
rchtxbox_timings.SelectionColor = Color.Yellow;
rchtxbox_timings.AppendText(timestamp + "ms\r\r");
rchtxbox_timings.ScrollToCaret();
if (num == 0) min_time = timestamp;
if (num2 > 1)
{
total_time = total_time + timestamp;
if (max_time < timestamp) max_time = timestamp;
if (min_time > timestamp) min_time = timestamp;
}
if (chkBx_LogData.Checked)
{
using (StreamWriter sw = new StreamWriter(timing_filename, true))
{
str1 = str1.Replace(" ", ""); //take out the spaces
sw.WriteLine(str1 + "," + timestamp.ToString() + "\r");
}
}
//Plot graph if required
if (ckbx_plot.Checked)
{
ave_plot = timestamp / num;
if (ckbx_restrict_graph.Checked)
{
if (chrt_timings.Series["ResponseTimes"].Points.Count() >= Convert.ToInt16(txtbx_axispoints.Text)) chrt_timings.Series["ResponseTimes"].Points.RemoveAt(0);
chrt_timings.Series["ResponseTimes"].Points.Add(timestamp);
chrt_timings.Series["ResponseTimes"].ToolTip = timestamp.ToString();
// if (chrt_timings.Series["AverageTime"].Points.Count() >= Convert.ToInt16(txtbx_axispoints.Text)) chrt_timings.Series["Average Time"].Points.RemoveAt(0);
// chrt_timings.Series["AverageTime"].Points.Add(ave_plot);
chrt_timings.ResetAutoValues();
}
else
{
recursive_counter++;
chrt_timings.Series["ResponseTimes"].Points.AddXY(recursive_counter, timestamp);
chrt_timings.Series["ResponseTimes"].ToolTip = timestamp.ToString();
// chrt_timings.Series["AverageTime"].Points.AddXY(ave_plot, timestamp);
}
}
num = num + 1;
timestamp = 0;
await Task.Delay(Int32.Parse(txtbx_timing_delay.Text));
}
catch (Exception d)
{
rchTxtBx_output.AppendText("red..... " + d.StackTrace);
}
} while (num2 > num);
if (num2 > 1)
{
//write out min, max and ave times
average_time = total_time / num;
rchtxbox_timings.SelectionColor = Color.LightBlue;
rchtxbox_timings.AppendText("\rMinimum Time = " + min_time + "\r");
rchtxbox_timings.SelectionColor = Color.LightBlue;
rchtxbox_timings.AppendText("Maximum Time = " + max_time + "\r");
rchtxbox_timings.SelectionColor = Color.LightBlue;
rchtxbox_timings.AppendText("Average Time = " + average_time + "\r\r");
rchtxbox_timings.ScrollToCaret();
}
}
Thanks for help, after much head scratching I solved the issue. I missed one small point and that was I did not have the second series, Series["AverageTime"], declared as a member of the charting canvas.
To fix this I went to the Properties then click on collection and Add the member, AverageTime. Once that was done I could draw its points to the Chart Canvas.
So now I initialise the lines below
if (ckbx_plot.Checked)
{
chrt_timings.Series["ResponseTimes"].ChartType = SeriesChartType.FastLine; //set type
chrt_timings.Series["ResponseTimes"].Color = Color.Blue; //set colour
chrt_timings.Series["AverageTime"].ChartType = SeriesChartType.FastLine; //set type
chrt_timings.Series["AverageTime"].Color = Color.Red; //set colour
chrt_timings.Series["AverageTime"].BorderDashStyle = ChartDashStyle.Dash;
chrt_timings.Legends.Clear(); // We do not need a legend
chrt_timings.ChartAreas[0].AxisX.IsMarginVisible = false;
}
and now I add the data
if (ckbx_restrict_graph.Checked)
{ //shows just set number of points, add a new point remove an old point
if (chrt_timings.Series["ResponseTimes"].Points.Count() >= Convert.ToInt16(txtbx_axispoints.Text)) chrt_timings.Series["ResponseTimes"].Points.RemoveAt(0);
chrt_timings.Series["ResponseTimes"].Points.Add(timestamp);
chrt_timings.Series["ResponseTimes"].ToolTip = timestamp.ToString();
if (chrt_timings.Series["AverageTime"].Points.Count() >= Convert.ToInt16(txtbx_axispoints.Text)) chrt_timings.Series["Average Time"].Points.RemoveAt(0);
chrt_timings.Series["AverageTime"].Points.Add(ave_plot);
chrt_timings.ResetAutoValues();
}
else
{ //squash all points onto the same canvas
recursive_counter++;
chrt_timings.Series["ResponseTimes"].Points.AddXY(recursive_counter, timestamp);
chrt_timings.Series["ResponseTimes"].ToolTip = timestamp.ToString();
chrt_timings.Series["AverageTime"].Points.AddXY(ave_plot, timestamp);
}

calculator using radio buttons

I'm trying to make a simple calculator using radio buttons in asp.net and c#. Two numbers are entered into a textbox each and a submit button is clicked and entered into a label.
The error I get is when the radio button is checked and submit is clicked, I get a runtime error; can anyone please help diagnose why?
This is my code:
int total;
if (rbAdd.Checked)
{
total = Convert.ToInt32(tbNo1.Text) + Convert.ToInt32(tbNo2.Text);
lblAns2.Text = total.ToString();
}
if (rbMult.Checked)
{
total = Convert.ToInt32(tbNo1.Text) * Convert.ToInt32(tbNo2.Text);
lblAns2.Text = total.ToString();
}
Simplified code that still fails the same way:
int total = 0;
int no1 = Convert.ToInt32(tbNo1.Text);
int no2 = Convert.ToInt32(tbNo2.Text);
if (rbAdd.Checked)
{
total = no1 + no2;
}
else if (rbMult.Checked)
{
total = no1 * no2;
}
lblAns2.Text = total.ToString();
I've tried your code and I got error message(Input string was not in a correct format.) only whenever I enter non integer values, because of your convert code Convert.ToInt32(tbNo1.Text);.
Do you want the entered values to be only integer? If so, please try this code instead (Modified from John Saunders code):
int total = 0;
int no1 = Convert.ToInt32(Math.Round(decimal.Parse(tbNo1.Text), 0));
int no2 = Convert.ToInt32(Math.Round(decimal.Parse(tbNo2.Text), 0));
if (rbAdd.Checked)
{
total = no1 + no2;
}
else if (rbMult.Checked)
{
total = no1 * no2;
}
lblAns2.Text = total.ToString();
You also have to validate the entered values as well to protect invalid characters.
Otherwise if you don't need to convert the entered values to be integer you could use this code:
decimal total = 0;
decimal no1 = decimal.Parse(tbNo1.Text);
decimal no2 = decimal.Parse(tbNo2.Text);
if (rbAdd.Checked)
{
total = no1 + no2;
}
else if (rbMult.Checked)
{
total = no1 * no2;
}
lblAns2.Text = total.ToString();

unable to go into while loop in c# (with an OleDbDataReader object)

Please check the comment made in the middle of the code, it shows where is the problem and how I try to solve it ... thanks !
The problem is within the statement: "while ((ObjReader.Read()) && (counter <= 5)) ". I put a breakpoint, but the cursor just doesn't want to enter the while loop !! I have tried to write just above that statement: "ObjReader.Read()" on its own and it reads it normally, but it doesn't want to read it in the while loop ...
public static void Convert(OleDbConnection MyConn, double strike1_run, double time0_run)
{
string value1 = "";
string value2 = "";
string value3 = "";
string T0 = "";
string T1 = "";
string VolT0K1 = "";
string VolT1K1 = "";
string K0 = "";
string K1 = "";
string K2 = "";
double DwOverDt;
string VolT0K0 = "";
string VolT0K2 = "";
double DwOverDy=0;
double DwSqOverDySq = 0;
double YoverW = 0;
double VarianceLoc = 0;
double VolLoc = 0;
// create command
string StrCmd = "SELECT * FROM Table1 WHERE ((strike = #strike_value0 AND strike = #strike_value1 AND strike = #strike_value2) AND (time= #time_value0 AND time= #time_value1)) ";
OleDbCommand Cmd = new OleDbCommand(StrCmd, MyConn);
Cmd.Parameters.Add("#strike_value0", OleDbType.VarChar);
Cmd.Parameters["#strike_value0"].Value = (strike1_run - 0.01).ToString();
Cmd.Parameters.Add("#strike_value1", OleDbType.VarChar);
Cmd.Parameters["#strike_value1"].Value = strike1_run.ToString();
Cmd.Parameters.Add("#strike_value2", OleDbType.VarChar);
Cmd.Parameters["#strike_value2"].Value = (strike1_run + 0.01).ToString();
Cmd.Parameters.Add("#time_value0", OleDbType.VarChar);
Cmd.Parameters["#time_value0"].Value = time0_run.ToString();
Cmd.Parameters.Add("#time_value1", OleDbType.VarChar);
Cmd.Parameters["#time_value1"].Value = (time0_run + 1).ToString();
OleDbDataReader ObjReader = Cmd.ExecuteReader(); // I put a breakpoint here - no issue
if (ObjReader != null) // I put a breakpoint here - no issue
{
int counter = 0;
while ((ObjReader.Read()) && (counter <= 5)) //HERE is the problem: I put a breakpoint here, the cursor just doesn't want to enter the while loop !! I have tried to write just above that statement: "ObjReader.Read()" on its own and it reads it normally, but it doesn't want to read it in the while loop ...
{
value1 = ObjReader.GetValue(1).ToString(); //time column value
value2 = ObjReader.GetValue(2).ToString(); //strike column value
value3 = ObjReader.GetValue(3).ToString(); //vol column value
counter++;
Console.WriteLine("counter= " + counter);
switch (counter)
{
case 1:
K0 = value2;
VolT0K0 = value3;
break;
case 2:
T0 = value1;
K1 = value2;
VolT0K1 = value3;
break;
case 3:
K2 = value2;
VolT0K2 = value3;
break;
case 4:
break;
case 5:
T1 = value1;
VolT1K1 = value3;
Console.WriteLine("Time: " + T0 + " - " + T1 + "\n" + "Strike: " + K0 + " - " + K1 + " - " + K2 + "\n" + "Vol: " + VolT0K1 + " - " + VolT1K1);
break;
default:
break;
}
}
}
ObjReader.Close();
}
Probably your query is returning zero rows. This will cause Read() to return false. When dealing with time intervals, it is very easy to get it backwards and get zero rows. The problem is you have two DIFFERENT time values, and you're comparing them to the same column. One column can never be simultaneously equal to two different values! So, you're getting zero rows back. Also, try to avoid using the * in your queries - list only the columns you need and save network overhead.
Your query probably needs to be a RANGE query, not an equals...
string StrCmd = "SELECT time, strike, vol FROM Table1 WHERE ((strike = #strike_value0 AND strike = #strike_value1 AND strike = #strike_value2) AND (time >= #time_value0 AND time <= #time_value1)) ";
Note that you're doing the same thing with the "strike" column - requiring it to be equal to two different values at the same time - if those two values aren't the same, you will always get zero rows back. It's similar to when we say "where 1=0" to force zero rows.

selenium c#

Hi all I am using this function to get name's of the input fields from browser. Problem is that in couple of my sites input fields have the same position, so i cant cycle thrue them correctly. Any ideas how to do this cycle in some different way as thrue position?
Thank you.
public void hladame_fieldy ()
{
//fieldy
string nazov_fieldu;
decimal celkovy_pocet_fieldov = selenium.GetXpathCount ("//input[#type='text']");
string field = "#type='text'";
int b = 1;
for (b = 1;b<=celkovy_pocet_fieldov;b++)
{
nazov_fieldu = selenium.GetAttribute("xpath=//input[position()="+b+" and "+field+"]#name");
Console.WriteLine(nazov_fieldu);
}
Console.WriteLine ("Celkovy pocet fieldov je = " + celkovy_pocet_fieldov);
}
Since you have the amount of elements you can just go through them as an array
public void hladame_fieldy ()
{
//fieldy
string nazov_fieldu;
decimal celkovy_pocet_fieldov = selenium.GetXpathCount ("//input[#type='text']");
string field = "#type='text'";
int b = 1;
for (b = 1;b<=celkovy_pocet_fieldov;b++)
{
nazov_fieldu = selenium.GetAttribute("xpath=//input[" + b + "]#name");
Console.WriteLine(nazov_fieldu);
}
Console.WriteLine ("Celkovy pocet fieldov je = " + celkovy_pocet_fieldov);
}
That way you just go through all the input elements in the DOM from top to bottom.
final solution:
public void hladame_fieldy ()
{
//fieldy
string nazov_fieldu;
decimal celkovy_pocet_fieldov = selenium.GetXpathCount ("//input[#type='text']");
int b = 1;
string pomoc = "";
for (b = 1;b<=celkovy_pocet_fieldov;b++)
{
nazov_fieldu = selenium.GetAttribute("xpath=//input[#type='text'" + pomoc +"]#name");
pomoc = pomoc + " and #name!= '" + nazov_fieldu + "'";
Console.WriteLine(nazov_fieldu);
}
Console.WriteLine ("Celkovy pocet fieldov je = " + celkovy_pocet_fieldov);
}

Categories

Resources