My purpose on this is to insert a autonumber for this format AN-00000000 to the db, with the type in db varchar.
my code in windows form is saving a integer number already "10000000".
But I turn on my mind and think if possible that the auto number will be like this AN-00000000 and to save to the db with a character string.
I tried my best to change and apply but suddenly I can not implement because is on the integer part.
I am creating the basic system in our company to create a automate membership for the members, in our company we have 4 parts of membership which is Dep, sep, mep and cef, so I turn on my mind that i need to implement the 4 Id with the following to identify what the department they included. like DEP-00000001, SEP-00000001, MEP-0000001 and CEF-00000001.
Can anyone suggest or give their opinion on my code below? Thanks!
DBconnect.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Windows.Forms;
using System.Data;
namespace PAIRDevelopment.Classes
{
public class DBConnect
{
public static string csConnect = "uid=root; database=membership; pooling = false; convert zero datetime=True";
public static MySqlConnection csCon= new MySqlConnection(Classes.DBConnect.csConnect);
public MySqlCommand cmdCon = new MySqlCommand();
public MySqlDataReader reader;
public void nonQuery(string cmdText)
{
cmdCon.Connection = csCon;
csCon.Open();
cmdCon.CommandText = cmdText;
cmdCon.ExecuteNonQuery();
cmdCon.Dispose();
csCon.Close();
}
public void OPEN(string cmdtext)
{
cmdCon.Connection = Classes.DBConnect.csCon;
Classes.DBConnect.csCon.Open();
cmdCon.CommandText = cmdtext;
reader = cmdCon.ExecuteReader();
}
public void CLOSE()
{
reader.Close();
cmdCon.Dispose();
Classes.DBConnect.csCon.Close();
}
}
}
Windows Form:
using System;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace PAIRDevelopment
{
public partial class Pair_Individual : Form
{
Classes.DBConnect OpenConCls = new Classes.DBConnect();
public Pair_Individual()
{
InitializeComponent();
textBox6.MaxLength = 13;
}
private void benabled_Click(object sender, EventArgs e)
{
OpenConCls.OPEN("SELECT MAX(piId) FROM tblpair_individual_membership");
while (OpenConCls.reader.Read())
{
string pcount = OpenConCls.reader[0].ToString();
if (pcount.Length == 0)
{
textBox1.Text = "10000000";
}
else
{
//int pcount1 = Convert.ToInt32(pcount);
//int pcountAdd = pcount1 + 1;
int pcount1 = Convert.ToInt32(pcount);
int pcountAdd = pcount1 + 1;
textBox1.Text = pcountAdd.ToString();
}
}
OpenConCls.CLOSE();
}
int pcount1 = Convert.ToInt32(pcount);
You are probably throwing a FormatException on the above line now if the string contains more than 0-9.
FormatException - value does not consist of an optional sign followed by
a sequence of digits (0 through 9).
If you know the first 4 chars will always be "XXX-" (e.g. "MEP-") then why don't you:
int pcount1 = Convert.ToInt32(pcount.Substring(4)); // ######## part
int pcountAdd = pcount1 + 1; // ######## + 1
textBox1.Text = String.Format("{0}-{1:D8}", pcount.Substring(0, 4), pcountAdd);
Which will convert only the numeric part, increment it, and then concatenate it with the first part.
Also you can look into the TryParse method. Which will indicate if your parse succeeded.
TryParse - Converts the string representation of a number to its 32-bit signed
integer equivalent. A return value indicates whether the operation succeeded.
Related
I'm new to C#, and I am supposed to be demonstrating creating arrays and processing the contents of the arrays. Whenever I press calculate I get the same numbers every time. I am not sure what I am missing? I changed double to decimals thinking that might help change things, but no matter what I try to fix it still comes up the same. Any help in this is appreciated. I also had to save a .txt file into the same folder as the bin/debug for this project. Im instructed that this is supposed to read the files content into the array of double or decimal. the folder just has a few numbers with decimals (1260.07, etc)
heres the code I have so far.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsAppAssignment6
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void analyzeBtn_Click(object sender,System.EventArgs e)
{
string file = "Sales.txt";
string salesValue;
Decimal[] sales = new decimal[7];
int count = 0;
decimal maxSales = Decimal.MinValue;
decimal minSales = Decimal.MaxValue;
decimal totalSales = 0;
try
{
StreamReader dataStream = new StreamReader(file);
salesValue = dataStream.ReadLine();
var total = sales.Sum();
var average = sales.Average();
var high = sales.Max();
var low = sales.Min();
while (salesValue != null)
{
sales[count] = Convert.ToDecimal(salesValue);
totalSales += sales[count];
if (sales[count] > maxSales)
maxSales = sales[count];
if (sales[count] < minSales)
minSales = sales[count];
count++;
salesValue = dataStream.ReadLine();
}
dataStream.Close();
for (int item = 0; item < 7; item++)
salesListBox.Items.Add(sales[item]);
totalLbl.Text = totalSales + "";
avgLabel.Text = totalSales + "";
highSalesLabel.Text = maxSales + "";
smallSalesLabel.Text = minSales + "";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void label3_Click(object sender, EventArgs e)
{
}
private void exitBtn_Click(object sender, EventArgs e)
{
this.Close();
}
}
}'''
Heres what populates every time.
The problem I think is with your error handling or the format of your document. Convert will actually throw an exception which will kill your entire loop if it cannot parse the current line. Say you had a simple line break in your file that created an empty line, you would try to parse it, an error is thrown, your code does nothing after it. Since I didnt have your file and I really do not feel like using visual studio instead of vscode, I replaced your streamreader with a stringreader (reads a string instead of a file but almost exactly the same) and i replaced the form with simple console writes. Outside of those changes, I gave myself some extra room in the array size since it was throwing exceptions and i wrapped the inside of the while loop in a try catch for format exceptions which is what Convert throws. After I made those changes, the outputs all worked properly. If you still dont see the values, then it is a problem with how you are using windows forms not your codes logic itself.
public static void Main()
{
Console.WriteLine("Hello World");
analyzeBtn_Click();
}
public static string SalesTxt = #"
1260.07
4002.52
267.21
15773.223
66655.2
555.0
7322
";
private static void analyzeBtn_Click()
{
string salesValue;
Decimal[] sales = new decimal[8];
int count = 0;
decimal maxSales = Decimal.MinValue;
decimal minSales = Decimal.MaxValue;
decimal totalSales = 0;
try
{
StringReader dataStream = new StringReader(SalesTxt);
salesValue = dataStream.ReadLine();
var total = sales.Sum();
var average = sales.Average();
var high = sales.Max();
var low = sales.Min();
while (salesValue != null)
{
try {
sales[count] = Convert.ToDecimal(salesValue);
totalSales += sales[count];
if (sales[count] > maxSales)
maxSales = sales[count];
if (sales[count] < minSales)
minSales = sales[count];
count++;
} catch (FormatException) {Console.WriteLine("\tException: '"+ salesValue + "'"); }
salesValue = dataStream.ReadLine();
}
dataStream.Close();
string listItems = string.Join(",\n", sales);
Console.WriteLine(listItems);
Console.WriteLine(totalSales);
Console.WriteLine(maxSales);
Console.WriteLine(minSales);
} catch (Exception ex) {
Console.WriteLine(ex);
}
}
Output:
Hello World
Exception: ''
Exception: ' '
1260.07,
4002.52,
267.21,
15773.223,
66655.2,
555.0,
7322,
0
95835.223
66655.2
267.21
EDIT:
In light of discussion, I have moved the string into a file with the appropriate name and used StreamReader just as you originally did. Using the same code as above just slightly modified, I was still able to get the correct output.
This question already has answers here:
What does the static keyword mean?
(4 answers)
Closed 7 years ago.
The code I am looking at is as follows
string data;
string[] tokens;
while (sr.EndOfStream != true)
{
data = sr.ReadLine();
char delim = ',';
tokens = data.Split(delim);
Team t = new Team(tokens[0], int.Parse(tokens[1]), int.Parse(tokens[2]));
TeamList.Add(t);
}
//Test to make sure the teams were stored properly
foreach(Team t in TeamList)
{
Console.WriteLine(t.Name);
}
sr.Close();
When I use the foreach loop to write the team names out it displays 9 copies of Team9 (The teams are listed 1-9 in the text file line by line, with two numbers separated by commas to hold the wins and losses for each team, which is the reason there are delims with commas). This goes for any number of teams I add, if i add a 10th team it does 10 copies of team10, and if I use 8 teams it shows 8 copies of Team8. I added the foreach loop into the while loop to have it show the teams at each stage and it keeps overwriting all previous objects when it creates a new one, so for example the first time it runs the loop it shows Team1, then the next time it runs the loop it shows two lines of Team2, and so on. From my research I saw that this is usually caused by not declaring a new object inside of the loop, but in this case a new object is declared inside the loop.
Edit: the Team class is as follows
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApplication2
{
class Team
{
private static string tn;
private static int Wins, Losses;
public Team()
{
}
public Team(string name, int wins, int losses)
{
tn = name;
Wins = wins;
Losses = losses;
}
public override string ToString()
{
return tn + ", wins: " + Wins + ", losses: " + Losses;
}
public string Name
{
get { return tn; }
}
}
}
The TeamList variable and main class are as follows
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApplication2
{
class Program
{
private static Random pick = new Random();
private static List<Team> TeamList = new List<Team>();
static void Main(string[] args)
{
//Reading file io
Schedule(TeamList);
Console.ReadLine();
}
static void Schedule(List<Team> TeamList)
{
StreamReader sr = new StreamReader("C:/Users/andre/Desktop/VisualStudioProjects/ConsoleApplication1/ConsoleApplication1/TeamList.txt");
string data;
string[] tokens;
while (sr.EndOfStream != true)
{
data = sr.ReadLine();
char delim = ',';
tokens = data.Split(delim);
Team t = new Team(tokens[0], int.Parse(tokens[1]), int.Parse(tokens[2]));
TeamList.Add(t);
foreach(Team x in TeamList)
{
Console.WriteLine(x.Name);
}
}
//Test to make sure the teams were stored properly
foreach(Team t in TeamList)
{
Console.WriteLine(t.Name);
}
sr.Close();
}
The text file is simply a file that contains the following
Team1,0,0
Team2,0,0
Team3,0,0
Team4,0,0
Team5,0,0
Team6,0,0
Team7,0,0
Team8,0,0
Team9,0,0
You have
class Team
{
private static string tn; //STATIC??
private static int Wins, Losses; //STATIC??
}
static means the variable is shared between all instances of Team in your application. Remove it please. That is the problem.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Hi fellow programmers,
I am creating a calculator in C#
and I have a string variable math which contains 100 * 5 - 2
How can I display its output which is 498 in my console?
My code is this:
String math = "100 * 5 - 2";
Console.WriteLine(math);
Console.ReadLine(); // For Pause
So basically, what my code will give me is the string itself which 100 * 5 - 2
but I want it to give me 498 as a result.
Idea about this is pretty much appreciated.
Thanks
Regular Expression evaluation can be done using DataTable.Compute method (from MSDN) :
Computes the given expression on the current rows that pass the filter
criteria.
Try this:
using System.Data;//import this namespace
string math = "100 * 5 - 2";
string value = new DataTable().Compute(math, null).ToString();
Simply try this
String math = (100 * 5 - 2).ToString();
I don't know, Why you want more complex? It's very easy ..
And if you want surely that,You can do that by using EvaluateExpression
public int EvaluateExpression(string math )
{
return Convert.ToInt32(math);
}
........................
String math = "100 * 5 - 2";
int result = EvaluateExpression(math );
Console.WriteLine(result );
See this discussions
Evaluating string "3*(4+2)" yield int 18
Update:
If those values came from input textbox, then write this way
String math = txtCalculator.Text.Trim();
int result = EvaluateExpression(math );
Console.WriteLine(result );
And also you can find out some pretty answer from this discussion
Is it possible to compile and execute new code at runtime in .NET?
Update 2:
Finally I have tried this sample for you :
My full code for class library
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.XPath;
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
String math = "100 * 5 - 2";
Console.WriteLine(Evaluate(math));
}
public static double Evaluate(string expression)
{
var xsltExpression =
string.Format("number({0})",
new Regex(#"([\+\-\*])").Replace(expression, " ${1} ")
.Replace("/", " div ")
.Replace("%", " mod "));
// ReSharper disable PossibleNullReferenceException
return (double)new XPathDocument
(new StringReader("<r/>"))
.CreateNavigator()
.Evaluate(xsltExpression);
// ReSharper restore PossibleNullReferenceException
}
}
You can compile code from string at runtime and execute it:
using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace DynamicCalcTest
{
class Program
{
static void Main(string[] args)
{
var result = new DynamicCalculator<double>("2 + 2 * 2").Execute();
}
}
public class DynamicCalculator<T>
{
private MethodInfo _Method = null;
public DynamicCalculator(string code)
{
_Method = GetMethodInfo(code);
}
public T Execute()
{
return (T)_Method.Invoke(null, null);
}
private MethodInfo GetMethodInfo(string code)
{
var tpl = #"
public static class Calculator
{{
public static double Calc()
{{
return {0};
}}
}}";
var finalCode = string.Format(tpl, code);
var parameters = new CompilerParameters();
parameters.ReferencedAssemblies.Add("mscorlib.dll");
parameters.GenerateInMemory = true;
parameters.CompilerOptions = "/platform:anycpu";
var options = new Dictionary<string, string> { { "CompilerVersion", "v4.0" } };
var c = new CSharpCodeProvider(options);
var results = c.CompileAssemblyFromSource(parameters, finalCode);
var type = results.CompiledAssembly.GetExportedTypes()[0];
var mi = type.GetMethod("Calc");
return mi;
}
}
}
Hi I trying to get the max timedate from a table using LinqToSQL. I already asked a similar question, but was trying to do something a bit more specific, and no one was able to help. This time, i would not mind using any solution, short of an Execute SQL task in another part of the SSIS package. This is my whole code. I was trying just to get the Identity column and it wasnt even working, so ignore the ToString please if it seems out of place. I just want to get the latest CREATED_TIMESTAMP please
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.IO;
using System.Linq;
using System.Data.SqlClient;
using System.Linq.Expressions;
using System.Collections;
using System.Collections.Generic;
using System.Data.Linq.Mapping;
using System.Data.Linq;
namespace ST_663004ffff194a14b84e2291578ada33.csproj
{
[System.AddIn.AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
#region VSTA generated code
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
//Strings for connections
string iFileName;
string oFileName;
string RW;
public void Main()
{
Dts.Variables["latestTableRow"].Value = getLatest();
MessageBox.Show(getLatest());
Dts.TaskResult = (int)ScriptResults.Success;
}// End Main
public string getLatest()
{
string result = "";
////temp dummy/defaul date is two days ago
//DateTime result = new DateTime();
//result = DateTime.Now.AddDays(-2);
try
{
//get the data connection string from the connection manager
RW = (string)Dts.Connections["ReportingWarehouse"].ConnectionString;
//Remove the Provider, Auto Translate, and Application
//as it is not a parameter for the DataContext constructor
RW = RW.Remove(RW.IndexOf("Provider=SQLNCLI10.1;"), "Provider=SQLNCLI10.1;".Length);
RW = RW.Remove(RW.IndexOf("Auto Translate=False;"), "Provider=SQLNCLI10.1;".Length);
RW = RW.Remove(RW.IndexOf("Application"),RW.Length - RW.IndexOf("Application"));
MessageBox.Show(RW);
//get the last insertion date from the SSASLoging table
using (DataContext RWData = new DataContext(RW))
{
Table<SSASLogging> records = RWData.GetTable<SSASLogging>();
var rs = (from r in records
orderby r.TimeStamp descending
select r).Max();
result = rs.Errorval.ToString();
}
MessageBox.Show(result);
}
catch (Exception e)
{
MessageBox.Show("Exception in retreiving latest time: " + e.Message + "/n"
+ e.StackTrace);
}
return result;
}
}//end partial class
[Table(Name = "SSASLogging")]
public class SSASLogging
{
private DateTime timeStamp;
[Column(Name = "CREATED_TIMESTAMP")]
public DateTime TimeStamp
{
get { return this.timeStamp; }
private set { ;}
}
}//End SSASLogging
}
Ok this works
using (DataContext RWData = new DataContext(RW))
{
Table<SSASLogging> records = RWData.GetTable<SSASLogging>();
var rs = (from r in records
select r).Max(r => r.TimeStamp);
result = rs;
}
I have a system that outputs dates in the format "1{yy}{MM}{dd}" and I am trying to find a good way to parse it back into a real date.
At the moment I am using this:
var value = "1110825";
var z = Enumerable.Range(1,3).Select(i => int.Parse(value.Substring(i, 2))).ToList();
var d = new DateTime(2000 + z[0], z[1], z[2]);
but I'm sure there's a cleaner/more efficient way to do it?
I've tried DT.ParseExact, but can't find a suitable format string to use.
This works for me:
using System;
using System.Globalization;
public class Test
{
static void Main()
{
var value = "1110825";
DateTime dt = DateTime.ParseExact(value, "1yyMMdd",
CultureInfo.InvariantCulture);
Console.WriteLine(dt);
}
}
(You may want to use TryParseExact of course, if you need to cope with invalid data in any way other than with an exception.)
A slight variation of this is the format pattern of "'1'yyMMdd" - note the apostrophes round the 1. That quotes the 1 to force it to be treated as a "literal" in the pattern. It's not important in this case, but if you actually had values such as "y110825" then you'd want to quote the y to make sure it wasn't treated as part of a year specifier.
you can use DateTime.ParseExact:
here is a example for 12/26/1979:
var parseback = DateTime.ParseExact("1791226", "1yyMMdd",
System.Globalization.CultureInfo.CurrentCulture);
Use DateTime.ParseExact(string s, string format, IFormatProvider provider)
an example
DateTime.ParseExact("1110825", "1yyMMdd", CultureInfo.InvariantCulture);
Just use this code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace DateTimeConvert
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
label1.Text= ConvDate_as_str(textBox1.Text);
}
public string ConvDate_as_str(string dateFormat)
{
try
{
char[] ch = dateFormat.ToCharArray();
string[] sps = dateFormat.Split(' ');
string[] spd = sps[0].Split('.');
dateFormat = spd[0] + ":" + spd[1]+" "+sps[1];
DateTime dt = new DateTime();
dt = Convert.ToDateTime(dateFormat);
return dt.Hour.ToString("00") + dt.Minute.ToString("00");
}
catch (Exception ex)
{
return "Enter Correct Format like <5.12 pm>";
}
}
private void button2_Click(object sender, EventArgs e)
{
label2.Text = ConvDate_as_date(textBox2.Text);
}
public string ConvDate_as_date(string stringFormat)
{
try
{
string hour = stringFormat.Substring(0, 2);
string min = stringFormat.Substring(2, 2);
DateTime dt = new DateTime();
dt = Convert.ToDateTime(hour+":"+min);
return String.Format("{0:t}", dt); ;
}
catch (Exception ex)
{
return "Please Enter Correct format like <0559>";
}
}
}
}