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.
Related
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);
}
how can i get string between two dots for example ?
[Person.Position.Name]
for this case I want to get the string "Position"
I can also have three dots ….
[Person.Location.City.Name]
I want to take all strings between dots
I know it's a year old question, but the other answers are not sufficient, like they are even pretending that you want "Location.City" because they don't know how to seperate them.. The solution is simple though, don't use indexof.
say you want to seperate the Four (not 3) parts:
String input = "Person.Location.City.Name"
string person = input.Split('.')[0];
string location = input.Split('.')[1];
string city = input.Split('.')[2];
string name = input.Split('.')[3];
Console.WriteLine("Person: " + person + "\nLocation: " + location + "\nCity: " + city + "\nName: " + name);
This might help you:
string s = "Person.Position.Name";
int start = s.IndexOf(".") + 1;
int end = s.LastIndexOf(".");
string result = s.Substring(start, end - start);
It will return all the values between the first and the last dot.
If you don't want the result with dot between the strings, you can try this:
string s = "Person.Location.Name";
int start = s.IndexOf(".") + 1;
int end = s.LastIndexOf(".");
var result = s.Substring(start, end - start).Split('.');
foreach (var item in result)
{
//item is some string between the first and the last dot.
//in this case "Location"
}
Try this
string str = "[Person.Location.City.Name]";
int dotFirstIndex = str.IndexOf('.');
int dotLastIndex = str.LastIndexOf('.');
string result = str.Substring((dotFirstIndex + 1), (dotLastIndex - dotFirstIndex) - 1); // output Location.City
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.
I have a program that uses a formula to calculate the refurb on a unit (parts replaced on cableboxes that were damaged) divided by total units (cableboxes that went through refurb, but did not have any parts replaced). I looked up casting online, and the format for it is:
int valuetoconvert = Convert.ToInt32;
I'm doing that, but I still get the following error:
Cannot implicitly convert type 'double to int. An explicit conversion exists(are you missing a cast?)
What am I doing wrong? Can someone please help? Thank you.
Here's some of my code:
private int GetRefurbRate()
{
string sql = "";
double Refurb_Rate;
int totalRefurb = 0;
int totalUnits = 0;
string error_msg = "";
sql = "SELECT COUNT(rp.repair_ord) " +
"FROM " + schema + ".repair_part rp " +
"WHERE rp.repair_ord = '" + repair_ord + "' ";
while (true)
{
if (!myDb.RunSql(sql, true))
{
error_msg = "DBError for getting Refurb Rate";
break;
}
if (myDb.dbRdr.HasRows)
{
if (myDb.dbRdr.Read())
{
try //Try and Catch are here b/c I originally had everything ints, and and they just caught the 0 exception.
{
Refurb_Rate = Convert.ToInt32( totalRefurb / totalUnits * 100); //This is where I try to perform the cast.
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
//int Refurb_Rate = Convert.ToInt32(Refurb_Rate);
}
break;
}
myDb.dbRdr.Close();
if (error_msg != String.Empty)
{
MessageBox.Show(error_msg, "Get Refurb Rate",
MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
You say you want an int cast, but you actually need to cast to a double. You can do that like so (Example Code):
Refurb_Rate = (double)totalRefurb / (double)totalUnits * 100d;
Otherwise, you need to change Refurb_Rate from a double to an int.
You need to say that you want an int cast:
double a;
int b = (int) a;
I don't understand your error, because Refurb_Rate is a double and everything else is an int. However, I think what you really want is this:
if (totalUnits != 0)
Refurb_Rate = totalRefurb * 100.0 / totalUnits;
Or possibly you want something like this:
int Refurb_Rate = 0;
...
if (totalUnits != 0)
Refurb_Rate = totalRefurb * 100 / totalUnits;
Try this:
Refurb_Rate = (int)((double)totalRefurb / totalUnits * 100);
Make sure you case the int to double otherwise 1 / 2 will equal zero instead of .5
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);
}