How to turn null to 0 - c#

I built a little program that calculates the average of 15 numbers or less. There are 15 text-boxes, each one's default value is '0'. The program knows to get the sum of all typed numbers and divide it by numbers of text boxes that don't return '0'. But if the user deletes in mistake one of the '0'os in one of the text boxs.. run-time error.
Originally I solved this problam by writing this "if statement" 15 times(one for each text-box):
if (t1.Text == "") { tr1 = 0; }
else
{
tr1 = Double.Parse(t1.Text);
}
this code checks if there isn't a thing in text box(for example, named t1), if true, the program is giving the double 'tr1'(don't confuse with 't1'), the value of '0', if false, the code gives the double 'tr1' the text of 't1'.
i had to write this 'if' 15 times. i wanted to know if i can write the same code with arrays and a for loop, and how?
here is the whole code (sorry for var names are not similar to var's use.):
private void goyouidiot_Click(object sender, EventArgs e)
{
double tr1;
double tr2;
double tr3;
double tr4;
double tr5;
double tr6;
double tr7;
double tr8;
double tr9;
double tr10;
double tr11;
double tr12;
double tr13;
double tr14;
double tr15;
if (t1.Text == "") { tr1 = 0; }
else
{
tr1 = Double.Parse(t1.Text);
}
if (t2.Text == "") { tr2 = 0; }
else
{
tr2 = Double.Parse(t2.Text);
}
if (t3.Text == "") { tr3 = 0; }
else
{
tr3 = Double.Parse(t3.Text);
}
if (t4.Text == "") { tr4 = 0; }
else
{
tr4 = Double.Parse(t4.Text);
}
if (t5.Text == "") { tr5 = 0; }
else
{
tr5 = Double.Parse(t5.Text);
}
if (t6.Text == "") { tr6 = 0; }
else
{
tr6 = Double.Parse(t6.Text);
}
if (t7.Text == "") { tr7 = 0; }
else
{
tr7 = Double.Parse(t7.Text);
}
if (t8.Text == "") { tr8 = 0; }
else
{
tr8 = Double.Parse(t8.Text);
}
if (t9.Text == "") { tr9 = 0; }
else
{
tr9 = Double.Parse(t9.Text);
}
if (t10.Text == "") { tr10 = 0; }
else
{
tr10 = Double.Parse(t10.Text);
}
if (t11.Text == "") { tr11 = 0; }
else
{
tr11 = Double.Parse(t11.Text);
}
if (t12.Text == "") { tr12 = 0; }
else
{
tr12 = Double.Parse(t12.Text);
}
if (t13.Text == "") { tr13 = 0; }
else
{
tr13 = Double.Parse(t13.Text);
}
if (t14.Text == "") { tr14 = 0; }
else
{
tr14 = Double.Parse(t14.Text);
}
if (t15.Text == "") { tr15 = 0; }
else
{
tr15 = Double.Parse(t15.Text);
}
double[] sch = { tr1, tr2, tr3, tr4, tr5, tr6, tr7, tr8, tr9, tr10, tr11, tr12, tr13, tr14, tr15 };
double total = 0;
double sorf = 0;
for (int i = 0; i != 14; i++)
{
sorf = sorf + sch[i];
if (sch[i] > 0)
{ total++; }
}
double totalic = sorf / total;
string glass = totalic.ToString();
result.Text = ("your score: " + glass);
}

Double.TryParse(t1.Text.Trim(), out tr1);
will set tr1 to the text box's numeric value, or 0.0 if it failed to convert it for some reason. It'll also return true if the conversion succeeded or false if it failed, but you don't care about the return value if the default is 0.0.
Added bonus: it won't throw an exception if someone decides to put "This is not a number." into a text box. It'll just see the value as 0.
To do this in an array...
TextBox t[] = { t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15 };
double tr[] = new double[t.Length];
for (int i = 0; i < t.Length; ++i)
{
Double.TryParse(t[i].Text.Trim(), out tr[i]);
}
UPDATE:
Note, it's perfectly reasonable to expect to be able to compute an average of numbers that includes 0. In order to do this:
TextBox t[] = { t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15 };
double tr[] = new double[t.Length];
int valid_count = 0;
for (int i = 0; i < t.Length; ++i)
{
if (Double.TryParse(t[i].Text.Trim(), out tr[i])) ++valid_count;
}
Set your TextBoxes' default values to blank (""), and then you'll know how many were legitimately 0's entered by the user and how many were blank. Divide the sum by valid_count to get an accurate average. (But be sure valid_count > 0, or you'll likely get a divide-by-zero exception.)

Sure, make a double tr[15] and a corresponding array of text fields.
Then just use:
for (int i = 0; i < 15; i++) {
if (t[i].Text == "") {
tr[i] = 0;
} else {
tr[i] = Double.Parse(t[i].Text);
}
}

If it's just the large amount of source code taken up with your if statements, you could opt for something like:
tr1 = ( t1.Text == "") ? 0 : Double.Parse( t1.Text);
tr2 = ( t2.Text == "") ? 0 : Double.Parse( t2.Text);
:
tr15 = (t15.Text == "") ? 0 : Double.Parse(t15.Text);
This is nice and neat, doesn't take up a lot of screen real-estate and it's fairly easy to see the intent.
Or, better yet, something like:
tr1 = 0; try { tr1 = Double.Parse( t1.Text); } catch (Exception e) {};
tr2 = 0; try { tr2 = Double.Parse( t2.Text); } catch (Exception e) {};
:
tr15 = 0; try { tr15 = Double.Parse(t15.Text); } catch (Exception e) {};
because the fields could be invalid and non-blank.
You can do the same thing with arrays and a for loop if you structure your data and controls differently but it may not be necessary for only fifteen items. Certainly if you were to add more, I'd give serious consideration to that option.
And you may want to load the values directly into an array so that you don't need sch:
double tr[15];
:
tr[ 0] = 0; try { tr[ 0] = Double.Parse( t1.Text); } catch (Exception e) {};
tr[ 1] = 0; try { tr[ 1] = Double.Parse( t2.Text); } catch (Exception e) {};
:
tr[14] = 0; try { tr[14] = Double.Parse(t15.Text); } catch (Exception e) {};
:
double total = 0;
double sorf = 0;
for (int i = 0; i < 15; i++) {
if (tr[i] > 0) {
sorf = sorf + tr[i];
total++;
}
}
:
For a minimal code solution, you can also create an array of the text boxes that you're pulling the information from. Something like (untested):
TextBox t[] = {t1, t2, t3, ..., t15};
double tr[t.length];
:
for (int i = 0; i < t.length; i++) {
tr[i] = 0; try { tr[i] = Double.Parse(t[i].Text); } catch (Exception e) {};
}
:
double total = 0;
double sorf = 0;
for (int i = 0; i < tr.length; i++) {
if (tr[i] > 0) {
sorf = sorf + tr[i];
total++;
}
}
:

Write a function that converts a textbox value to a double, something like:
private static double ConvertTextboxValueToDouble(string value)
{
double result;
Double.TryParse(value, out result);
return result;
}
Then create an array from your textboxes, converting their values to doubles:
double[] values =
{
ConvertTextboxValueToDouble(t1.text),
ConvertTextboxValueToDouble(t2.text),
ConvertTextboxValueToDouble(t3.text),
...
ConvertTextboxValueToDouble(t15.text)
}

Have you considered of using a NumericUpDown instead of an TextBox?
Also instead of writing something fifteen times you should really refactor your code and try one of the following ways:
Register for all your entry boxes an event, where all using the same code
public void ValueChanged(Object sender, EventArgs e)
{
var numericUpDown = sender as NumericUpDown;
if(numericUpDown == null)
return;
//ToDo: Put some check code here
}
Use some List<T> where you put all your boxes into and iterate over it to check all settings
var myList = new List<NumericUpDown>();
//ToDo: Put all your boxes into it
myList.Add(numericUpDown1);
myList.Add(numericUpDown2);
//or get the list from somewhere else
myList.AddRange(this.Controls.OfType<NumericUpDown>())
//OnButtonClick
foreach(var numericUpDown in myList)
{
//ToDo: Do some checking
}

Put a .Trim() when retrieving the values from the TextBox
tr3 = Double.Parse(t3.Text.Trim());

For this situations and thinking to accomplish the job in a little portion of code, i use a dirty little trick: put the controls into a panel.
If your panel is only containing desired controls (in this case, textboxes), this will be enough to store the values in a list of doubles:
private void button1_Click(object sender, EventArgs e)
{
List<double> doubleList = new List<double>();
foreach (TextBox t in panel1.Controls)
doubleList.Add(this.checkTextBox(t));
}
private double checkTextBox(TextBox t)
{
return (t.Text != string.Empty) ? Double.Parse(t.Text.Trim()) : 0;
}
If you can't have a panel only for textboxes and the design force you to mix controls into, you will have to do an extra check/conversion:
private void button1_Click(object sender, EventArgs e)
{
List<double> doubleList = new List<double>();
foreach (Control t in panel1.Controls)
if(t is TextBox)
doubleList.Add(this.checkTextBox((TextBox)t));
}
private double checkTextBox(TextBox t)
{
return (t.Text != string.Empty) ? Double.Parse(t.Text.Trim()) : 0;
}
Greetings!

Related

Can I use Asynchronous code to fix StackOverflow error?

I am trying to make a Sudoku solver in C# WPF, using backtracking algorithm, everything was going smoothly, but just as it seemed like it was going to work, I started getting stack overflow errors.
I tried to fix them with separating the loops and calls, but I still am getting the same error.
Another thing I tried was to make certain methods separate threads, but that seems too complicated and I am not sure it will work.
I want to know if separating them with threads could work or if I have to do something else so I don't get the error.
The main part of the code is below, though I don't know if it can be of any help
// h is the current Label's index in the list MTLabels (Empty labels)
// a is the current number I am displaying
private void Calculate()
{
Label label = MTLabels[h];
label.Content = a;
Check(label);
return;
}
private void Check(Label label)
{
CommonLabels.Clear();
var p1 = VisualTreeHelper.GetParent(label) as UIElement;
int labelID = Convert.ToInt32(label.Name.Substring(5));
int labelY = GetLabelY(labelID);
int labelX = labelID % 9;
string labelParent = ((Grid)p1).Name;
foreach (Label lbl in Labels)
{
if (lbl != label)
{
var p2 = VisualTreeHelper.GetParent(lbl) as UIElement;
int lblID = Convert.ToInt32(lbl.Name.Substring(5));
int lblY = GetLabelY(lblID);
int lblX = lblID % 9;
string lblParent = ((Grid)p2).Name;
if (lblY == labelY || lblX == labelX || lblParent == labelParent)
{
CommonLabels.Add(lbl);
}
}
}
CheckInCommon();
}
private void CheckInCommon()
{
Label label = MTLabels[h];
foreach (Label lbl in CommonLabels)
{
if (lbl.Content.ToString() == label.Content.ToString())
{
if (a >= 9)
{
label.Content = "";
h--;
label = MTLabels[h];
a = (int)label.Content;
a++;
label.Content = a;
Check(label);
}
else if (a < 9)
{
a++;
label.Content = a;
CheckInCommon();
}
}
}
if (h + 1 < MTLabels.Count)
{
a = 1;
h++;
label = MTLabels[h];
label.Content = a;
Check(label);
}
else if (h + 1 == MTLabels.Count)
{
Console.WriteLine("Done");
}
}

find the first element of an array that is not consecutive using web forms

E.g. If we have an array [1,2,3,4,6,7,8] then 1 then 2 then 3 then 4 are all consecutive but 6 is not, so that's the first non-consecutive number.
If the whole array is consecutive then return null .
The array will always have at least 2 elements 1 and all elements will be numbers. The numbers will also all be unique and in ascending order. The numbers could be positive or negative and the first non-consecutive could be either too. please help me finish this code i am new in programming. My code:
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace _2katas
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var input = this.txtInput.Text;
var numarray = input.Split(',');
int firstValue = Convert.ToInt32(numarray[0]);
for (var i = 0; i < numarray.Length; i++)
{
if (Convert.ToInt32(numarray[i]) - i != firstValue)
{
lblPrint.Text = "";
}
else
{
lblPrint.Text = "";
}
if (this.rdbConsecutive.Checked == true)
{
lblKataRunning.Text = "Consecutive";
}
else if (this.rdbStripCleaning.Checked == true)
{
lblKataRunning.Text = "Strip Cleaning";
}
}
}
}
}
Let's extract a method:
Find the first element of an array that is not consecutive ...
If the whole array is consecutive then return null
We can implement it like this:
private static string FirstInconsecutive(string data) {
var array = data.Split(',');
if (array.Length <= 0)
return null; //TODO: what shall we return on empty array?
if (!int.TryParse(array[0], out int delta))
return array[0];
for (int i = 1; i < array.Length; ++i)
if (!int.TryParse(array[i], out int value) || value - i != delta)
return array[i];
return null;
}
Usage:
string result = FirstInconsecutive(txtInput.Text);
Please note int.TryParse which helps to return the right answer "ABC" on an input like "1, 2, 3, ABC, 4, 6, 7, 8" (user input txtInput.Text can contain any string)
A linq solution just for the fun of it:
static int? FindFirstNonConsecutive(IEnumerable<int> arr)
{
var nonConsecutiveInfo =
arr.Select((i, index) => new {Index = index, Delta = i - index})
.FirstOrDefault(t => t.Delta != arr.First());
return nonConsecutiveInfo?.Delta + nonConsecutiveInfo?.Index;
}
Note that this will only work finding non consecutive numbers in ascending order as per requirements.
Two numbers are not consecutive if the left ones + 1 <> the right one.
Check with something like this, note that you have to change your boundary checks:
for (var i = 0; i < numarray.Length - 1; i++)
{
if (Convert.ToInt32(numarray[i]) + 1 != Convert.ToInt32(numarray[i+1]))
Update your condition as below for loop and it will work. I would suggest you to have separate function so that it could be reusable if needed elsewhere in code.
Here start your loop from i = 1 and compare numarray[i-1] + 1 != numarray[i] values.
You can convert your sting[] to int[] with var numarray = input.Split(',').Select(x => Convert.ToInt32(x)).ToArray(); and use it with IsConsecutive(numarray) as per button1_Click code.
You can get first non-consecutive value with minor modification in return type and return statement as shown in GetFirstNonConsecutiveValue().
public bool IsConsecutive(int[] numarray)
{
for (int i = 1; i < numarray.Length; i++)
{
if (numarray[i-1] + 1 != numarray[i])
{
return false;
}
}
return true;
}
public int? GetFirstNonConsecutiveValue(int[] numarray)
{
for (int i = 1; i < numarray.Length; i++)
{
if (numarray[i-1] + 1 != numarray[i])
{
return numarray[i];
}
}
return null;
}
private void button1_Click(object sender, EventArgs e)
{
var input = this.txtInput.Text;
var numarray = input.Split(',').Select(x => Convert.ToInt32(x)).ToArray();
var nonConsecutiveValue = GetFirstNonConsecutiveValue(numarray);
if (nonConsecutiveValue != null)
{
// nonConsecutiveValue is first non consecutive value.
}
else
{
// sequence is consecutive.
}
}
One way to go.
string rawData = "1,2,3,4,6,7,8,9";
IEnumerable<int> data = rawData.Split(',').Select(v => Convert.ToInt32(v));
IEnumerable<int> all = Enumerable.Range(data.Min(), data.Max() - data.Min() + 1);
IEnumerable<int> diff = all.Except(data);
if (diff.Count() == 0)
{
return null;
}
return data.ElementAt(all.ToList().IndexOf(diff.First()))
NB Not thoroughly tested.
Just test diff for being empty to get the numbers are consecutive

How to add array values to equal a number, or fail if values in array wont work

I am trying to build a calculator that will tell me what "steps" are needed to stack up to a given value. Using only that "steps" available in the array.
Example:
decimal[] blocks {.05, .100, .150, .200, .250}
goal = .550m
result = .100, .200, .250
I have tried using nested if statements and array find/last with not much luck.
I can get a match if the goal is an exact match, or will match with two of them stacked. I can't get it to work for the max(.750).
This is what I have so far:
code:
string result = "nope";
decimal goal = 3.264m;
decimal[] DAStep = new decimal[10];
decimal temp = Array.Find(GaugeBlockArray, element => element.Equals(goal));
if (temp != 0m)
{
DAStep[0] = Array.Find(GaugeBlockArray, element => element.Equals(temp));
result = DAStep[0].ToString();
}
else
{
DAStep[0] = GaugeBlockArray.Last(element => element <= goal); ;
decimal remaining;
remaining = goal - DAStep[0];
while (remaining != 0m)
{
DAStep[1] = GaugeBlockArray.Last(element => element <= remaining);
if (DAStep[1] != remaining)
{
DAStep[2] = GaugeBlockArray.Last(element => element <= (DAStep[1] - .0001m));
if (DAStep[2] == 0) { DAStep[1] = DAStep[2]; }
}
}
}
GaugeBlockArray contains an array of 72 different elements from .05 to 4.0. And, I can only use each block once.
edit:
I guess more detail on the array contents may help getting to a solution.
GaugeBlockArray:
.05
.100
.1001
.1002
.1003
.1004
.1005
.1006
.1007
.1008
.1009
.110
.111
.112
.113
.114
.115
.116
.117
.118
.119
.120
.121
.122
.123
.124
.125
.126
.127
.128
.129
.130
.131
.132
.133
.134
.135
.136
.137
.138
.139
.140
.141
.142
.143
.144
.145
.146
.147
.148
.149
.150
.200
.250
.300
.350
.400
.450
.500
.550
.600
.650
.700
.750
.800
.850
.900
.950
1.000
2.000
3.000
4.000
Many thanks to #GeorgPatscheider for getting me pointed in the right direction!
This is my final working result:
public static void CountSum(decimal[] DNumbers, decimal Dsum)
{
foreach (Window window in Application.Current.Windows)
{
if (window.GetType() == typeof(MetTracker.GaugeCalc))
{
(window as MetTracker.GaugeCalc).CalculateBtn.Content = "working...";
}
}
DNumbers = Array.ConvertAll(DNumbers, element => 10000m * element);
string TempString = GetSettingsStrings("GBCMaxStep"); // only used to initialize max step value
Dsum = Dsum * 10000m;
Int32 Isum = Convert.ToInt32(Dsum);
Int32[] INumbers = Array.ConvertAll(DNumbers, element => (Int32)element);
// int result = 0;
GetmNumberOfSubsets(INumbers, Isum);
success = false;
return;
}
private static void GetmNumberOfSubsets(Int32[] numbers, Int32 Isum)
{
set = numbers;
sum = Isum;
FindSubsetSum();
}
//-------------------------------------------------------------
static Int32[] set;
static Int32[] subSetIndexes;
static Int32 sum;
static Int32 numberOfSubsetSums;
static bool success = false;
static List<Int32> ResultSet = new List<Int32>();
static List<string> results = new List<string>();//------------------------------------------------------------
/*
Method: FindSubsetSum()
*/
private static void FindSubsetSum()
{
numberOfSubsetSums = 0;
Int32 numberOfElements = set.Length;
FindPowerSet(numberOfElements);
}
//-------------------------------------------------------------
/*
Method: FindPowerSet(int n, int k)
*/
private static void FindPowerSet(Int32 n)
{
// Super set - all sets with size: 0, 1, ..., n - 1
for (Int32 k = 0; k <= n - 1; k++)
{
subSetIndexes = new Int32[k];
CombinationsNoRepetition(k, 0, n - 1);
if(subSetIndexes.Length >= GBC_MaxStepSetting) {
break; }
}
if (numberOfSubsetSums == 0)
{
MessageBox.Show("No subsets with wanted sum exist.");
}
}
//-------------------------------------------------------------
/*
Method: CombinationsNoRepetition(int k, int iBegin, int iEnd);
*/
private static void CombinationsNoRepetition(Int32 k, Int32 iBegin, Int32 iEnd)
{
if (k == 0)
{
PrintSubSet();
return;
}
if (success == false)
{
for (Int32 i = iBegin; i <= iEnd; i++)
{
subSetIndexes[k - 1] = i;
++iBegin;
CombinationsNoRepetition(k - 1, iBegin, iEnd);
if (success == true)
break;
}
}
return;
}
private static void PrintSubSet()
{
Int32 currentSubsetSum = 0;
// accumulate sum of current subset
for (Int32 i = 0; i < subSetIndexes.Length; i++)
{
currentSubsetSum += set[subSetIndexes[i]];
if(currentSubsetSum > sum) { break; }
}
if(currentSubsetSum > sum) { return; }
// if wanted sum: print current subset elements
if (currentSubsetSum == sum)
{
++numberOfSubsetSums;
// results.Add("(");
for (Int32 i = 0; i < subSetIndexes.Length; i++)
{
results.Add((set[subSetIndexes[i]]).ToString());
ResultSet.Add(set[subSetIndexes[i]]);
if (i < subSetIndexes.Length - 1)
{
// results.Add(" ,");
}
}
// results.Add(")");
Int32[] ResultSetArr = ResultSet.ToArray();
decimal[] ResultSetArrD = Array.ConvertAll(ResultSetArr, element => (decimal)element);
ResultSetArrD = Array.ConvertAll(ResultSetArrD, element => element / 10000m);
// var message = string.Join(Environment.NewLine, ResultSetArrD);
// message = string.Format("{0:0.0000}", message);
int l = ResultSetArrD.Length;
string[] ResultString = new string[l];
foreach(int i in ResultSetArrD)
{ResultString = Array.ConvertAll(ResultSetArrD, element => element.ToString("0.0000"));}
var message = string.Join(Environment.NewLine, ResultString);
decimal ResultSum = ResultSetArrD.Sum();
MessageBox.Show(message + "\n= " + ResultSum.ToString("0.0000"), "Result");
Array.Clear(ResultSetArrD, 0, ResultSetArrD.Length);
Array.Clear(ResultSetArr, 0, ResultSetArr.Length);
ResultSet.Clear();
message = null;
success = true;
foreach (Window window in Application.Current.Windows)
{
if (window.GetType() == typeof(MetTracker.GaugeCalc))
{
(window as MetTracker.GaugeCalc).CalculateBtn.Content = "Calculate";
}
}
return;
}
if (success == true)
return;
}
I added some limiting to reduce the amount of time before it reports a failure to find a combo. I also convert the array to a double to get around the headache the decimals were causing me. Works great!

Application running in ASP.NET is not giving the desired output

I have an application not calculating the percentage correctly. It is suppose to calculate the input in percent. But there is bug somewhere which is preventing it from doing so.
For example, if I input any number starting with decimals like 0.01 or 0.001 or 0.02 etc it will give me the output 1, 0.1 and 2 respectively. If I punch in any whole numbers like 1, 2, 3, 10, etc, it will always give the same output i.e 0.01.
This application was done by some contractors 5 years ago. The main in-charge of this application has left. Which leaves me and my little experience in c# and asp.net in figuring out the issue. Before I seek any further help, I thought I should ask geniuses out there and see what they have to say, may be I will end up figuring out the issue with your help. I did talk to other IT people in my department, they guess it might be because of the code below.
if (int.TryParse(string.IsNullOrEmpty(txtminup.Text) ? "0" : txtminup.Text, out n))
I am not 100% sure how to debug or find the issue. If anyone can point me out anything that might help or provide me some resources that I can look it up, it will be really helpful. I have copied few of the lines of code. I can provide more information but don't know which one will be more relevant.
protected string MinUp
{
get
{
return (string)ViewState["minup"];
}
set
{
ViewState["minup"] = value;
}
}
==============
MinUp = rows["process_minimum_up"].ToString();
PIMSSource = rows["pims_source"].ToString();
//MinUp = Convert.ToDouble()
if (MinUp != string.Empty || MinUp.Length > 0)
{
MinUp = Convert.ToString(Convert.ToDouble(MinUp) * 100);
}
=====================
if (DCFoption != "P")
{
MinUp = "";
}
if (DcfmSeq != "0")
{
int caret;
caret = ddlvbcfmseq.SelectedValue.IndexOf("^");
DcfmSeq = DcfmSeq.Substring(0, caret);
}
if (DCFoption != "P" && ddlpdwnlst.SelectedItem.Value == "0")
{
MinUp = "";
}
if (PIMSTagId == "Not specified")
{
PIMSTagId = "";
}
if (MinUp != string.Empty || MinUp.Length > 0)
{
int n;
if (int.TryParse(string.IsNullOrEmpty(txtminup.Text) ? "0" : txtminup.Text, out n))
{
MinUp = Convert.ToString(Convert.ToInt32(MinUp) / 100);
if (Convert.ToInt32(MinUp) < 0)
{
MinUp = "0";
}
else if (Convert.ToInt32(MinUp) > 1)
{
MinUp = "1";
}
}
}
if ((DCFoption == string.Empty || DCFoption.Length < 1) || DCFoption == "D")
{
MinUp = "";
}
if (MinUp != string.Empty || MinUp.Length > 0)
{
int n;
if (int.TryParse(string.IsNullOrEmpty(txtminup.Text) ? "0" : txtminup.Text, out n))
{
if (Convert.ToDouble(MinUp) <= 0)
{
MinUp = ".0001";
}
}
}
=======================
if (rdbProcess.Checked == true && (txtminup.Text == string.Empty || txtminup.Text.Length < 1) && ddlpdwnlst.SelectedItem.Value == "0")
{
Utilities.ShowAlert(this.Page, Resources.Resource.RIPimsUpload_MinUptime.ToString());
txtminup.Focus();
======================
int n;
if (!int.TryParse(string.IsNullOrEmpty(txtRound.Text) ? "0" : txtRound.Text, out n))
{
Utilities.ShowAlert(this.Page, Resources.Resource.RIPimsUpload_RoundingNum.ToString());
}
else if (!IsDouble(txtminup.Text))
======================
try
{
DBResults objDBResult = new DBResults();
WEIS.RIPimsUpload objRI = new WEIS.RIPimsUpload();
objDBResult = objRI.SaveItemInsert(reciseq, shortname, name, eiscprocess2, period, media, euseq, eqmtseq, eiscuom, pollseq, dcfmseq, rounding, formula, physmin, physmax, warn1min, warn1max, warn2min, warn2max, pimsStatus, pimsTagidp, datapoint, freq, periodoffset, initpimstTagId, initDataPoint, initLoadFrequency, initperiodoffset, day0result, retention, audituser, dcfoption, minup, pimssource);
if (objDBResult.oraErrMsg.Trim().ToString().Length > 1)
{
Exception ex = new Exception(objDBResult.oraErrMsg.ToString());
throw ex;
}
return objDBResult.oraIntReturn;
}
===============================
protected int SaveItemUpdate(int reciseq, string shortname, string name, int eiscprocess2, int period, int media, int euseq, int eqmtseq, int eiscuom, int pollseq, int dcfmseq, string rounding, string formula, string physmin, string physmax, string warn1min, string warn1max, string warn2min, string warn2max, string pimsStatus, string pimsTagidp, string datapoint, string freq, char periodoffset, string initpimstTagId, char initDataPoint, char initLoadFrequency, char initperiodoffset, string day0result, string retention, string audituser, string dcfoption, string minup, string pimssource)
{
try
{
DBResults objDBResult = new DBResults();
WEIS.RIPimsUpload objRI = new WEIS.RIPimsUpload();
objDBResult = objRI.SaveItemUpdate(reciseq, shortname, name, eiscprocess2, period, media, euseq, eqmtseq, eiscuom, pollseq, dcfmseq, rounding, formula, physmin, physmax, warn1min, warn1max, warn2min, warn2max, pimsStatus, pimsTagidp, datapoint, freq, periodoffset, initpimstTagId, initDataPoint, initLoadFrequency, initperiodoffset, day0result, retention, audituser, dcfoption, minup, pimssource);
if (objDBResult.oraErrMsg.Trim().ToString().Length > 1)
{
Exception ex = new Exception(objDBResult.oraErrMsg.ToString());
throw ex;
}
=============================
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
lblUserMsgText.Text = "";
bool dcfm = ddlvbcfmseq.Enabled;
string minup, dcfoption="";
minup = txtminup.Text;
if (rdbNone.Checked == true)
{
dcfoption = "NONE";
}
else if (rdbProcess.Checked == true)
{
dcfoption = "P";
}
else if (rdbData.Checked == true)
{
dcfoption = "D";
}
Index = Convert.ToInt32(rdbListradios.SelectedIndex);
SaveItem();
RetainClientControlValues(dcfm, dcfoption, minup);
}
==============================
protected void btnExcMod_Click(object sender, EventArgs e)
{
try
{
lblUserMsgText.Text = "";
bool dcfm = ddlvbcfmseq.Enabled;
string minup, dcfoption = "";
Index = Convert.ToInt32(rdbListradios.SelectedIndex);
minup = txtminup.Text;
if (rdbNone.Checked == true)
{
dcfoption = "NONE";
}
else if (rdbProcess.Checked == true)
{
dcfoption = "P";
}
else if (rdbData.Checked == true)
{
dcfoption = "D";
}
Button btn = (Button)sender;
int evntseq = Convert.ToInt32(btn.CommandArgument.ToString());
RetainClientControlValues(dcfm, dcfoption, minup);
//Response.Write("you clicked on button");
}
#Umamaheswaran thanks for the hint.
int n;
if (int.TryParse(string.IsNullOrEmpty(txtminup.Text) ? "0" : txtminup.Text, out n))
Above was the initial code and i changed it to
double n;
if (double.TryParse(string.IsNullOrEmpty(txtminup.Text) ? "0" : txtminup.Text, out n))
and also whereever it was converting to
Convert.ToInt32
I changed it to
Convert.ToDouble
I don't know whatever was the issue as I am not very much familiar with asp.net and c# but changing above code solved the issue. Now whenever I input a number it will change to percentage and save it to correct format.
Thank you all for your help and concern. I have few more different issues. I will try to solve it if not I will post it here and try to be concise and to the point.

Count Number of Functions in c programme using C#

How can i count number of functions in C program File using C# program? I have create a simple C# class to count the LOC in C file.
private bool IsInMultipleComment = false;
private int getNumberOFFuncions(FileInfo fs)
{
StreamReader rdr;
int count = 0;
string tempStr;
// initialize
rdr = fs.OpenText();
tempStr = rdr.ReadLine();
while (true)
{
if (tempStr == null)
break;
if (IsFunction(tempStr))
count++;
tempStr = rdr.ReadLine();
}
return count;
}
Supportive method:
private bool IsFunction(string line)
{
if (line.Contains("//"))
return false;
if (line.Contains("/*"))
IsInMultipleComment = true;
if (line.Contains("*/"))
IsInMultipleComment = false;
if (!IsInMultipleComment)
{
if (line.Contains("void") || line.Contains("int") || line.Contains("short") || line.Contains("long") || line.Contains("float") || line.Contains("char") || line.Contains("double"))
{
if (!line.Contains(";"))
{
return true;
}
}
}
return false;
}
This is how I count variables:
private int getNumberOfVariables(FileInfo fs)
{
StreamReader rdr;
int count = 0;
string tempStr;
// initialize
rdr = fs.OpenText();
tempStr = rdr.ReadLine();
while (true)
{
if (tempStr == null)
break;
count += getVariblesOfLine(tempStr);
tempStr = rdr.ReadLine();
}
return count;
}
Supportive method:
private int getVariblesOfLine(string line)
{
line = line.Trim(); // trim the lines
if (line.Contains("#")) // remove preprocessive declarations
return 0;
if (line.Contains("//"))
return 0;
if (line.Contains("/*"))
IsInMultipleComment = true;
if (line.Contains("*/"))
IsInMultipleComment = false;
if (!IsInMultipleComment)
{
if (line.Contains("unsigned") || line.Contains("signed") || line.Contains("int") || line.Contains("short") || line.Contains("long") || line.Contains("float") || line.Contains("char") || line.Contains("double"))
{
if (!line.Contains("(")) // remove if this is function
{
Console.WriteLine(line);
if (line.Contains(",")) // count at multiple declarations
{
int y = line.Count(f => f == ',');
return y + 1;
}
return 1;
}
}
}
return 0;
}
Learn about Regex(s). There is a string pattern what a function declaration looks like. You won't catch every possible contortion of a function, you can get most of them, if you use declare functions in the general accepted .net way. Expresso is learning good learning tool for helping you to get the pattern of the Regex.
Here is a pattern to identify a function. It looks crazy but it's not. Expresso will decode it for you. It's not fully developed in that it won't catch private functions where you don't put the word private in front of it and it doesn't do protected internal. There is probably many more that it won't catch.
Regex regex = new Regex("\s*(private|public|internal|protected)\s*\w+\s+([a-zA-Z_0-9.]+)\s*\(.*\)",RegexOptions.Compiled)
if (regex.IsMatch(lineOfCode)
{
//then it's a function
}
On another note, don't keep opening and re-reading the file. Open it once, make a pass, that's it.
I've got some code (in javascript) to do line counts and such on Csharp files you might be able to pull out some of the regex patterns. Note how the regexes are kept in an object (dictionary in .net) In javascript, /pattern/ is the same as .net "pattern"
module.exports = ( function() {
var classifiers = [] ;
classifiers.push(
{
ctype: "using",
regex: /^(\s*using\s*)([a-zA-Z_0-9.]+)/,
extractMethod: function(lineInfo) {
lineInfo.extractValue = lineInfo.line.split(this.regex)[2] ;
}
},
{
ctype: "namespace",
regex: /^(\s*namespace\s*)([a-zA-Z_0-9.]+)/,
extractMethod: function(lineInfo) {
lineInfo.extractValue = lineInfo.line.split(this.regex)[2] ;
}
},
{
ctype: "comment",
regex: /^\s*\/\/[/ A-Za-z,*]*/,
extractMethod: function(lineInfo) {
lineInfo.extractValue = null ;
}
},
{
ctype: "n/a",
regex: /^\s*$|^\s*[;{}]+?\s*$/,
extractMethod: function(lineInfo) {
lineInfo.extractValue = null ;
}
}
);
function classifyLine(line, lineNo) {
var lineInfo = {} ;
lineInfo.line = line ;
lineInfo.lineNo = lineNo;
for (var index = 0; index < classifiers.length; index++) {
var classifier = classifiers[index];
if (classifier.regex.test(line)) {
lineInfo.ctype = classifier.ctype;
lineInfo.line = line ;
classifier.extractMethod(lineInfo) ;
break ;
}
}
if (lineInfo.ctype == undefined){
lineInfo.ctype = "code" ;
}
return lineInfo ;
}
return {
classifyLine : classifyLine
};
} )();

Categories