Hello i would like to ask you about a small problem i have with a certain program. So basically the program(console app) reads packets from other Procees(Program) and delivers the packets so they can be analyzed. The problem i stumbeled upon is that One of my nested functions wont trigger (completely). Example:
This line is lying in the Main() function. Along with the rest , this is just a clip
captureDevice.OnPacketArrival += new PacketArrivalEventHandler(Program.device_OnPacketArrival);
After which i have some console.writeline etc. Nothing special.
device_OnPacketArrival() is Function with some other Nested Functions Inside.
private static void device_OnPacketArrival(object sender, CaptureEventArgs packet)
{
DateTime date = packet.Packet.Timeval.Date;
int length = packet.Packet.Data.Length;
..........
Program.ValidateItem(first_db_id, first_bin_id, out char_id, out user_id, out type, out valid);
............
The Function that causes problem is:ValidateItem()
public static void ValidateItem(int item_Id, int item_type, out int char_id, out int user_id, out int type, out int valid)
{
valid = type = user_id = char_id = 0;
string oString = "SELECT type,char_id,user_id FROM [DB].[dbo].[Table] WHERE id = #item_id";
SqlCommand oCmd = new SqlCommand(oString, Program.s_DB);
oCmd.Parameters.AddWithValue("#item_id", item_Id);
try
{
using (SqlDataReader oReader = oCmd.ExecuteReader())
{
if (oReader.Read())
{
type = Convert.ToInt32(oReader["type"]);
char_id = Convert.ToInt32(oReader["char_id"]);
user_id = Convert.ToInt32(oReader["user_id"]);
if (type == item_type)
{
valid = 1;
}
else
{
valid = 0;
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
The Problem is that only the first line of the function is initialized - valid = type = user_id = char_id = 0; But if i run the function directly in Main() its working fine.
Not sure if answering your question
but in c# there is no "nested" functions , if you need to create that "illusion" try using annonymus
functions
Related
I am creating a simple inventory system using c#.
When I am generating the invoice number, the form is loaded but it doesn't show anything.
It is an auto-incremented invoice number; order is completed incrementally by 1.
For example, starting at E-0000001, after order we expect E-0000002. I don't understand why it is blank.
No error displayed. I tried to debug the code but I couldn't find what's wrong.
public void invoiceno()
{
try
{
string c;
sql = "SELECT MAX(invoid) FROM sales";
cmd = new SqlCommand(sql, con);
var maxInvId = cmd.ExecuteScalar() as string;
if (maxInvId == null)
{
label4.Text = "E-000001";
}
else
{
int intVal = int.Parse(maxInvId.Substring(2, 6));
intVal++;
label4.Text = String.Format("E-{0:000000}", intVal);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.Write(ex.StackTrace);
}
}
Let's extract a method - NextInvoiceId - we
Open connection
Execute query
Obtain next invoice number
Code:
private int NextInvoiceNumber() {
//TODO: put the right connection string here
using(var conn = new SqlConnection(ConnectionStringHere)) {
conn.Open();
string sql =
#"SELECT MAX(invoid)
FROM sales";
using (var cmd = new SqlCommand(sql, conn)) {
var raw = cmd.ExecuteScalar() as string;
return raw == null
? 1 // no invoces, we start from 1
: int.Parse(raw.Trim('e', 'E', '-')) + 1;
}
}
}
Then we can easily call it:
public void invoiceno() {
label4.Text = $"E-{NextInvoiceNumber():d6}";
}
Edit: You should not swallow exceptions:
try
{
...
}
// Don't do this!
catch (Exception ex) // All the exceptions will be caught and...
{
// printed on the Console...
// Which is invisible to you, since you develop Win Forms (WPF) application
Console.WriteLine(ex.ToString());
Console.Write(ex.StackTrace);
}
let system die and inform you that something got wrong
Please find the source code below. I am not getting any error but
_oracleCommand.ExecuteNonQuery() is going infinite - debugger is not moving to next line. I am able to update the data using Toad. I am stuck with this.
public void UpdateNewResignationRequestInSynergy(string _employeeno, string _comment, string _changeby, string _changeddt, string _reason)
{
int rowsaffected = 0;
string returnStatus;
string _synquery = "";
DateTime dtDate;
_employeeno = "774647";
_comment = "contract eand";
dtDate = DateTime.Parse(_changeddt, System.Globalization.CultureInfo.CreateSpecificCulture("en-CA"));
_oracleCommand = new OracleCommand(_synquery, _synergyDb);
_synergyDb.Open();
_oracleCommand.CommandText = string.Format(#"update wipinfo.fms_resignation set str_comments = 'contract end' where STR_CONTRACTOR_ID = 774647");
_oracleCommand.CommandType = CommandType.Text;
try
{
_oracleCommand.ExecuteNonQuery();
}
catch(Exception ex)
{
}
_synergyDb.Close();
}
You have to stop the oracle server and start again( do not restart it will not help you). I solved this problem by doing this process.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm getting errors when I try to "login" to this. Its a school project and I know its simple, I just need it to function properly, any help is appreciated. Try to ignore obviously inefficient code.
class UserVariables
{
public static int avatarC;
public static int colourC;
public static string userNameC;
public static string passWordC;
public static int highScoreC;
}
private void button1_Click(object sender, EventArgs e)
{
try
{
bool success = false;
string UsernameTXT = "userName.txt";
string PasswordTXT = "userPass.txt";
string ColourTXT = "userColour.txt";
string AvatarTXT = "userAvatar.txt";
string ScoreTXT = "userScore.txt";
using (StreamReader user_Login = new StreamReader(UsernameTXT))
{
using (StreamReader pass_Login = new StreamReader(PasswordTXT))
{
using (StreamReader colour_Login = new StreamReader(ColourTXT))
{
using (StreamReader avatar_Login = new StreamReader(AvatarTXT))
{
using (StreamReader score_login = new StreamReader(ScoreTXT))
{
var lineCount = File.ReadLines(UsernameTXT).Count();
string userRead;
string passRead;
string colourRead;
string avatarRead;
string scoreRead;
for (int a = 0; a < lineCount; a++)
{
userRead = user_Login.ReadLine();
passRead = pass_Login.ReadLine();
colourRead = user_Login.ReadLine();
avatarRead = pass_Login.ReadLine();
scoreRead = user_Login.ReadLine();
if ((textBox1.Text == userRead) && (textBox2.Text == passRead))
{
UserVariables.userNameC = textBox1.Text;
UserVariables.passWordC = textBox2.Text;
UserVariables.colourC = int.Parse(colourRead);
// Theres a problem with this line.
UserVariables.avatarC = int.Parse(avatarRead);
UserVariables.highScoreC = int.Parse(scoreRead);
MessageBox.Show("Login successful!",
"Success");
success = true;
new Menus().Show();
this.Hide();
MessageBox.Show("Hi, " + UserVariables.userNameC + "!");
break;
}
}
if (success == false)
{
label1.Show();
MessageBox.Show("Login was unsuccessful.",
"Error");
}
}
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
The error is "Input string was not in a correct format", which tells me that at least one value of colourRead is not an integer value. int.Parse ignores whitespace, so it isn't a matter of formatting. It cannot be a simple integer value and has to contain another character like "2a", "2.0", "1,000", etc.
To figure out exactly which value, you can create a breakpoint or watch and start debugging, or you can use int.TryParse
Try this instead
if(!int.TryParse(colourRead, out UserVariables.colourC))
{
MessageBox.Show(colourRead);
}
// Theres a problem with this line.
It will likely pop up a window telling you exactly what value it is trying to turn into an int.
Also, I forsee problems with the way you are reading the files. You get the number of lines in userTXT by doing this:
var lineCount = File.ReadLines(UsernameTXT).Count();
Which will read the entire file contents, and count up how many lines exist. That's not a great way of doing this, but it should be functional as long as the files aren't too long.
You are then stepping through every line in this file, but reading 3 lines for every iteration of the for loop
userRead = user_Login.ReadLine();
...
colourRead = user_Login.ReadLine();
...
scoreRead = user_Login.ReadLine();
You will run out of lines to read from your file before the for loop completes.
So i have a google spreedsheet from where I'm reading some data. So e.g my first column looks something like this:
When I change any of the rows into some random string like "abc" my application crashes:
I have also recorded a short video where I demonstrate this in action, and put my method in TRY-CATCH so the app doesn't crash. This is very strange... Is it maybe because of the variable var where if half of the data array is an integer value, then it becomes int or what else could it be?
http://screencast.com/t/7OlDOzDZX70R
If I, for example put all rows in some strings "a","b" and insert a number in between, the app crashes again...
I just don't know what might be the problem. It also happens in other rows...
crash report
Here is my code that deserilazes the json when I get it from the web:
private async Task GetDataAsync()
{
//if (this._table.Count != 0) return;
this.Table.Clear();
var jsonObject = await DownloadSpreadsheet.GetJson();
for (int row = 0; row < jsonObject["rows"].Count(); row++)
{
Table table = new Table();
table.Day = jsonObject["rows"][row]["c"][0]["v"].ToString();
table.Month = jsonObject["rows"][row]["c"][5]["v"].ToString();
table.Year = jsonObject["rows"][row]["c"][6]["v"].ToString();
table.People = jsonObject["rows"][row]["c"][7]["v"].ToString();
this.Table.Add(table);
}
And here is the model where all fields are clearly declared as STRING...
public class Table
{
[DataMember(Name="id")]
public string Id { get; set; }
[DataMember(Name="day")]
public string Day { get; set; }
[DataMember(Name="month")]
public string Month { get; set; }
[DataMember(Name="year")]
public string Year { get; set; }
}
Here is also the method for getting the json:
public class DownloadSpreadsheet
{
// 1tJ64Y8hje0ui4ap9U33h3KWwpxT_-JuVMSZzxD2Er8k
private static readonly string spreadsheetKey = "1Ka-8bTSo4E7sNmsP41prSQqpjawooAvajnFnLi-jtCI";
private static string jsonUrlTemplate = "http://spreadsheets.google.com/a/google.com/tq?key={0}";
async public static Task<JObject> GetJson()
{
var url = string.Format(jsonUrlTemplate, spreadsheetKey);
var client = new HttpClient();
var response = await client.GetAsync(new Uri(url));
var rawResult = await response.Content.ReadAsStringAsync();
int start = rawResult.IndexOf("{", rawResult.IndexOf("{") + 1);
int end = rawResult.LastIndexOf("}");
String jsonResponse = rawResult.Substring(start, end - start);
return JObject.Parse(jsonResponse);
}
}
There is no error catching or checking for null values anywhere in the code and an unknown error is occuring.
I moved out your code into linqpad and I get an exception on this line:
var result = jsonObject.Result;
for (int row = 0; row < result["rows"].Count(); row++)
{
table.Day = result["rows"][row]["c"][0]["v"].ToString(); // Exception here
the exception is this
InvalidOperationException: Cannot access child value on
Newtonsoft.Json.Linq.JValue.
I recommend that you put error checking into your code and a way to see the message such as:
private async Task GetDataAsync()
{
//if (this._table.Count != 0) return;
try
{
this.Table.Clear();
var jsonObject = await DownloadSpreadsheet.GetJson();
for (int row = 0; row < jsonObject["rows"].Count(); row++)
{
Table table = new Table();
table.Day = jsonObject["rows"][row]["c"][0]["v"].ToString();
table.Month = jsonObject["rows"][row]["c"][5]["v"].ToString();
table.Year = jsonObject["rows"][row]["c"][6]["v"].ToString();
table.People = jsonObject["rows"][row]["c"][7]["v"].ToString();
this.Table.Add(table);
}
}
catch(Exception ex)
{ this.Error = ex; }
}
One other thing, in my version of the code I had to work off of the result of the task jsonObject.Result before extracting data.
I am using MongoVue application to show the data preview stored in "MongoDb".
In the attached image, the database name "Energy" has collection name "DataLog". In "DataLog", there are several rows. I am adding these row to the collection by reading it from a .CSV file.
Now sometimes the column name Pings has huge data [say array of 2000 items] for a single row due to which the exception occurs i.e if "MaxDocumentSize exceeds in 16MB"
Since the Pings array was huge which threw an exception and to avoid this, I removed the collection of Pings [i.e. entered blank collection] from row and tried to Insert, it went successful.
Now I want to update the Pings for the same entry, but in case the array is something like 2000 elements or above, then I wish to update it in group of 500 items [500 x 4 = 2000] in a loop.
Can anyone help me out.
** SAMPLE CODE **
private void InsertData(Datalog xiDatalog)
{
List<Ping> tempPings = new List<Ping>();
tempPings.AddRange(xiDatalog.Pings);
xiDatalog.Pings.RemoveAll(x => x.RowId != 0);
WriteConcernResult wc = mongoCollection.Insert(xiDatalog);
counter++;
var query = new QueryDocument("_id", xiDatalog.Id);
MongoCursor<Datalog> cursor = mongoCollection.FindAs<Datalog>(query);
foreach (Datalog data in cursor)
{
AddPings(data, tempPings, mongoCollection);
break;
}
}
private void AddPings(Datalog xiDatalog, List<Ping> xiPings, MongoCollection<Datalog> mongoCollection)
{
int groupCnt = 0;
int insertCnt = 0;
foreach (Ping px in xiPings)
{
xiDatalog.Pings.Add(px);
groupCnt++;
if (((int)(groupCnt / 500)) > insertCnt)
{
UpdateDataLog(xiDatalog.Id, xiDatalog.Pings, mongoCollection);
insertCnt++;
}
}
}
private bool UpdateDataLog(BsonValue Id, List<Ping> tempPings, MongoCollection<Datalog> mongoCollection)
{
bool success = false;
try
{
var query = new QueryDocument("_id", Id);
var update = Update<Datalog>.Set(e => e.Pings, tempPings);
mongoCollection.Update(query, update);
success = true;
}
catch (Exception ex)
{
string error = ex.Message;
}
return success;
}
Answer : Just modified the code to use Update.PushAll() instead of Update.Set()
Please refer below code
private bool UpdateDataLog(BsonValue Id, List<Ping> tempPings, MongoCollection<Datalog> mongoCollection)
{
bool success = false;
try
{
var query = new QueryDocument("_id", Id);
var update = Update<Datalog>.PushAll(e => e.Pings, tempPings);
mongoCollection.Update(query, update);
success = true;
}
catch (Exception ex)
{
string error = ex.Message;
}
return success;
}