C# Update Table Button Not Working Automatically - c#

I have some c# code and recently I added a button to the form designer which runs a simple update table query (update a SQL table). The table is updated as I would expect when I manually click the button in Debug mode, however when I run the entire program, it appears the method/button to update the SQL table is either ignored or simply not being picked up. As I mentioned, this works fine when I go into Debug and click on the button manually, however what I need it to do is run the method and click the button automatically as it is doing for the other methods. I have gone through this hundreds of times and am at the end of the road. Below is my code;
private void updateClosedModuleState()
{
System.Data.SqlClient.SqlConnection saConn = new System.Data.SqlClient.SqlConnection();
saConn.ConnectionString = GlobalDef.strSQLConnection;
//MessageBox.Show(saConn.ConnectionString);
try
{
saConn.Open();
SqlCommand command = saConn.CreateCommand();
command.CommandTimeout = saConn.ConnectionTimeout;
command.CommandType = System.Data.CommandType.Text;
command.CommandText = " UPDATE SATA_AllocationObject "
+ " SET State = REPLACE(State, 'A', 'I') "
+ " where AllocationObjectType = 4 "
+ " and Hostkey in (select hostkey from TRAN_UnitEClosedModules)";
command.ExecuteNonQuery();
}
catch (Exception act)
{
MessageBox.Show("Ooops! Error " + act.Message.ToString() + " when updating Module State");
}
finally
{
saConn.Close();
}
pictureBox19.Visible = true;
}
This is the code for the button click;
private void cmdUpdateClosedModuleState_Click(object sender, EventArgs e)
{
updateClosedModuleState();
}
Lastly, these are the method details in the form designer;
this.cmdUpdateClosedModuleState.Location = new System.Drawing.Point(517, 114);
this.cmdUpdateClosedModuleState.Name = "cmdUpdateClosedModuleState";
this.cmdUpdateClosedModuleState.Size = new System.Drawing.Size(107, 23);
this.cmdUpdateClosedModuleState.TabIndex = 41;
this.cmdUpdateClosedModuleState.Text = "UpdateModState";
this.cmdUpdateClosedModuleState.UseVisualStyleBackColor = true;
this.cmdUpdateClosedModuleState.Click += new System.EventHandler(this.cmdUpdateClosedModuleState_Click);
I have also tried to use a TableAdapter and use a Fill to update the SQL Table via the button, and that works...only when I click the button in Debug mode;
private void newupdate()
{
//throw new NotImplementedException();
this.sATA_AllocationObject1TableAdapter.Fill(this.moduleSignupTestDataSet.SATA_AllocationObject1);
}
I assigned a buttton to run the Fill on the TableAdapter;
private void newupdate_Click(object sender, EventArgs e)
{
//this.sATA_AllocationObject1TableAdapter.Fill(this.moduleSignupTestDataSet.SATA_AllocationObject1);
newupdate();
}
So in a nutshell, I need the program to run this method like it does with all the other ones without my intervention.
I have attached a photo of the form - when I click 'Run All' everything runs except for the UpdateClosedModState; [1]: https://i.stack.imgur.com/dJryA.png
The code behind the Run All command is;
private void cmdRunAll_Click(object sender, EventArgs e)
{
begin();
}
In the form designer we have;
this.cmdRunAll.Location = new System.Drawing.Point(381, 375);
this.cmdRunAll.Name = "cmdRunAll";
this.cmdRunAll.Size = new System.Drawing.Size(107, 21);
this.cmdRunAll.TabIndex = 10;
this.cmdRunAll.Text = "Run All";
this.cmdRunAll.UseVisualStyleBackColor = true;
this.cmdRunAll.Click += new System.EventHandler(this.cmdRunAll_Click);
And at the start of the form, we have this to begin running the app;
if (args.Length > 0)
{
lArgsExists = true;
// strDetails = strDetails + ": About to run app.";
// runApp(args[0], lArgsExists);
begin();
}
}
public void runApp(string cnfgPath, bool gui)
{
if (gui == true)
{
strDetails = strDetails + " Running app.";
begin();
}
else
{
textBox2.Text = GlobalDef.appStatus.ToString();
begin();
//MessageBox.Show("Opening form!");
}
}
public void begin()
{
String sqlServerLogin = GlobalDef.sqlServerlogin;
String password = GlobalDef.password;
String instanceName = GlobalDef.instanceName;
String remoteSvrName = GlobalDef.remoteSvrName;
string strNow = DateTime.Now.Day + "/" + DateTime.Now.Month + "/" + DateTime.Now.Year;
string strSQLConnection = GlobalDef.strSQLConnection;
textBox2.Text = GlobalDef.appStatus.ToString();
//string path = #"E:\Allocator\StudentAllocatorTest\logs\Error.log";
string path = GlobalDef.path;
// This text is added only once to the file.
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Error details");
}
}
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine();
sw.WriteLine("******************************************");
sw.WriteLine();
sw.WriteLine(strDetails.ToString());
sw.WriteLine("******************************************");
sw.WriteLine();
sw.WriteLine(DateTime.Now.ToString() + ": Starting load for " + GlobalDef.instanceName);
}
try
{
string connString = GlobalDef.connString;
OracleConnection oraCon = new OracleConnection(connString);
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection();
conn.ConnectionString =
"data source=" + remoteSvrName + ";" +
"persist security info=true;initial catalog=" + instanceName + ";User Id=" + sqlServerLogin + "; Password=" + password + ";";
// Clear transfer tables before running any subroutine
clearTransTables();
// Loads Department details into SA TransTables
updateDepartment(oraCon, strSQLConnection);
// Loads new POSA modules into SA TransTables
updatePOSA(oraCon, strSQLConnection, path);
// Loads new POSY modules into SA TransTables
updatePOSY(oraCon, strSQLConnection, path);
// Remove open option links for modules which do not have the timetable flag checked
RemoveUnneededOOCourses(oraCon, strSQLConnection, path);
// Loads top-level OO structure into SA TransTables
OpenOption(oraCon, strSQLConnection, path);
// Loads Dept level OO structure into SA TransTables
OptionByDept(oraCon, strSQLConnection, path);
// Links OOByDept Allocation Objects to OO Objects via TransTables
linkOOAndOOByDept(path);
// Loads new Course modules into SA TransTables
updateCourse(oraCon, strSQLConnection, path);
// Links OO courses to OOByDept AllocationObjects via TransTables
OpenOptionCourses(oraCon, strSQLConnection, path);
//Adds All Courses to various hidden groups via TransTables
updateAllHidden(oraCon, strSQLConnection, path);
// Loads new students into SA TransTables
//TransferStudent(oraCon, strSQLConnection);
// Loads prerequisite allocations into SA TransTables
UploadPrerequisites(oraCon, strSQLConnection);
//button1_Click();
// Loads Closed Modules from UnitE to TRAN_UnitEClosedModules
uploadUnitEClosedModules(oraCon, strSQLConnection);
//Runs the transfer service which loads the data in the TransTables into the database
runTransferservice(path);
///
newupdate();
// update Closed Modules to 'I' State
updateClosedModuleState();
// Used to create a structure for programmes which had yet to be set up by faculties
// DefaultCourseStructure(oraCon, strSQLConnection);
// Creates UNITe course enrolments and cancels changed course selections
uploadAllocationsToUNITe(oraCon, strSQLConnection, path);
// pictureBox11.Visible = true;
}
catch (Exception e)
{
MessageBox.Show(e.Message.ToString());
}
finally
{
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine(DateTime.Now.ToString() + ": Completed load for " + GlobalDef.instanceName);
}
Application.Exit();
}
}
private void updateDepartment(OracleConnection oraCon, string strSQLConnection)
{
try
{
....and it goes on with the subroutines listed above.
Any help would be greatly appreciated.
Thank you in advance.

Related

How to fix issue of zkemkeeper.dll realtime events inside windows service?

i'm setting up windows service and want it to sync the device attendance to SQL Server database using zkemkeeper real time event. i have successfully created service as well as tested the service on my local system which run windows 10 and another one window 8 service work fine and sync the attendance record to DB server at real time. Now after successful testing on local system i deployed service over production server where service successfully established the connection with device but it didn't respond to Real time event for testing purpose i have created winform app and run it over the server and find out it is working and listening to real time event but i need service to work properly not win form application any help will be appreciated thanks below is my code !
public partial class AttendanceSyncService_405 : ServiceBase
{
public AttendanceSyncService_405()
{
InitializeComponent();
}
System.Timers.Timer timer = new System.Timers.Timer();
public zkemkeeper.CZKEMClass axCZKEM1 = new zkemkeeper.CZKEMClass();
private bool bIsConnected = false;//the boolean value identifies whether the device is connected
private int iMachineNumber = 1;//the serial number of the device.After connecting the device ,this value will be changed.
protected override void OnStart(string[] args)
{
//var thread = new Thread();
//thread.SetApartmentState(ApartmentState.STA);
//thread.Start();
WriteToFile("Service is started at " + DateTime.Now);
Connect();
// LoadCurrentMonthAtt();
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
timer.Interval = 900000; //number in milisecinds
timer.Enabled = true;
}
protected override void OnStop()
{
WriteToFile("Service is stopped at " + DateTime.Now);
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
if (bIsConnected == true)
{
WriteToFile("Service recall at " + DateTime.Now);
WriteToFile("Device Status Connected at " + DateTime.Now);
}
else
{
WriteToFile("Device Status DisConnected at " + DateTime.Now);
WriteToFile("Service recall at " + DateTime.Now);
Connect();
}
}
public void WriteToFile(string Message)
{
string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\ServiceLog_" + DateTime.Now.Date.ToShortDateString().Replace('/', '_') + ".txt";
if (!File.Exists(filepath))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(filepath))
{
sw.WriteLine(Message);
}
}
else
{
using (StreamWriter sw = File.AppendText(filepath))
{
sw.WriteLine(Message);
}
}
}
private void Connect()
{
try
{
int idwErrorCode = 0;
bIsConnected = axCZKEM1.Connect_Net("192.168.0.177", 4370);
if (bIsConnected == true)
{
this.axCZKEM1.OnAttTransactionEx += new zkemkeeper._IZKEMEvents_OnAttTransactionExEventHandler(axCZKEM1_OnAttTransactionEx);
iMachineNumber = 1;
if (axCZKEM1.RegEvent(iMachineNumber, 65535))//Here you can register the realtime events that you want to be triggered(the parameters 65535 means registering all)
{
this.axCZKEM1.OnAttTransactionEx += new zkemkeeper._IZKEMEvents_OnAttTransactionExEventHandler(axCZKEM1_OnAttTransactionEx);
}
else
{
WriteToFile("RT Events didn't registered at " + DateTime.Now);
}
axCZKEM1.RegEvent(iMachineNumber, 65535);//Here you can register the realtime events that you want to be triggered(the parameters 65535 means registering all)
WriteToFile("Device Connection Established Successfully at " + DateTime.Now);
}
else
{
axCZKEM1.GetLastError(ref idwErrorCode);
WriteToFile("Unable to connect the device,ErrorCode=" + idwErrorCode.ToString() + " at " + DateTime.Now);
}
}
catch(Exception ex)
{
WriteToFile("Exception :" + ex.Message + " at " + DateTime.Now);
}
}
private void axCZKEM1_OnAttTransactionEx(string sEnrollNumber, int iIsInValid, int iAttState, int iVerifyMethod, int iYear, int iMonth, int iDay, int iHour, int iMinute, int iSecond, int iWorkCode)
{
DateTime Attendancedate = new DateTime(iYear, iMonth, iDay, iHour, iMinute, iSecond);
string row = sEnrollNumber + "," + Attendancedate.ToString();
WriteToFile("Attendane :" + row + " Marked At: " + DateTime.Now);
if (bIsConnected == false)
{
Connect();
return;
}
decimal empserial = decimal.Parse(sEnrollNumber);
attInsert(empserial, Attendancedate);
}
private void attInsert(decimal empserial, DateTime Attendancedate)
{
try
{
WriteToFile("Attendance Entry Arrived for EMP-Serial :" + empserial + " At: " + DateTime.Now + " for Insertion");
DBAccess db = new DBAccess();
DataSet attCount = db.GetDataSetFromQuery("select Count(att.[todayCount]) as attCount from tblAttendance att where (att.attDate = Convert(date,GETDATE()) AND att.fkSerial ='" + empserial.ToString() + "')");
int count = int.Parse(attCount.Tables[0].Rows[0]["attCount"].ToString());
Boolean INOUT = (count % 2 == 0) ? true : false;
WriteToFile("Attendane Count :" + count + " & In/Out : " + INOUT + " Marked At: " + DateTime.Now);
db.Parameters.AddWithValue("fkSerial", empserial);
db.Parameters.AddWithValue("attTerminalId", "Time1");
db.Parameters.AddWithValue("attDateTime", Attendancedate);
db.Parameters.AddWithValue("attTgId", 3);
db.Parameters.AddWithValue("attINOUT", INOUT);
db.Parameters.AddWithValue("attEmpCode", "no need");
db.ExecuteNonQuery("spInsertAttendance");
WriteToFile("Attendance Inserted of EMP-Serial :" + empserial + " At: " + DateTime.Now);
}
catch (Exception ex)
{
WriteToFile("Exception in insert method :" + ex.Message + " At: " + DateTime.Now);
}
}
}
Type This Code in Your IntializeComponent and it will respond to realtime events
private void InitializeComponent()
{
Thread createComAndMessagePumpThread = new Thread(() =>
{
axCZKEM1 = new zkemkeeper.CZKEMClass();
bool connSatus = axCZKEM1.Connect_Net(192.168.0.177, 4370);
if (connSatus == true)
{
this.axCZKEM1.OnAttTransactionEx -= new zkemkeeper._IZKEMEvents_OnAttTransactionExEventHandler(axCZKEM1_OnAttTransactionEx);
if (axCZKEM1.RegEvent(1, 65535))//Here you can register the realtime events that you want to be triggered(the parameters 65535 means registering all)
{
this.axCZKEM1.OnAttTransactionEx += new zkemkeeper._IZKEMEvents_OnAttTransactionExEventHandler(axCZKEM1_OnAttTransactionEx);
}
}
Application.Run();
});
createComAndMessagePumpThread.SetApartmentState(ApartmentState.STA);
createComAndMessagePumpThread.Start();
components = new System.ComponentModel.Container();
this.ServiceName = "Service1";
}

Unable to cast object of type 'System.Threading.Timer' to type 'jabber.client.JabberClient' [closed]

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 5 years ago.
Improve this question
I am making a birthday notification in windows service that uses jabber-net library which is a XMPP and System.Threading that must send automatic messages to user every day, but i'm getting an error in logs which says
Unable to cast object of type 'System.Threading.Timer' to type 'jabber.client.JabberClient'. at SparkSalesCrdBirthdays.SparkBirthDayGreeting.j_OnAuthenticate(Object sender)
Here's my code
protected override void OnStart(string[] args)
{
this.WriteToFile("Simple Service started {0}");
JabberClient j = new JabberClient();
// what user/pass to log in as
j.User = "user";
j.Server = "server"; // use gmail.com for GoogleTalk
j.Password = "pass";
//j.Resource = "admin";
// don't do extra stuff, please.
j.AutoPresence = false;
j.AutoRoster = false;
j.AutoReconnect = -1;
j.KeepAlive = 10;
j.AutoLogin = true;
j.AutoStartTLS = false;
j.PlaintextAuth = true;
j.OnError += new bedrock.ExceptionHandler(j_OnError);
// what to do when login completes
j.OnAuthenticate += new bedrock.ObjectHandler(j_OnAuthenticate);
// listen for XMPP wire protocol
if (VERBOSE)
{
j.OnReadText += new bedrock.TextHandler(j_OnReadText);
j.OnWriteText += new bedrock.TextHandler(j_OnWriteText);
}
// Set everything in motion
j.Connect();
// wait until sending a message is complete
done.WaitOne();
// logout cleanly
j.Close();
this.ScheduleService();
}
protected override void OnStop()
{
this.WriteToFile("Simple Service stopped {0}");
this.Schedular.Dispose();
}
private Timer Schedular;
static void j_OnWriteText(object sender, string txt)
{
if (txt == " ") return; // ignore keep-alive spaces
Console.WriteLine("SEND: " + txt);
}
static void j_OnReadText(object sender, string txt)
{
if (txt == " ") return; // ignore keep-alive spaces
Console.WriteLine("RECV: " + txt);
}
private void j_OnAuthenticate(object sender)
{
try
{
JabberClient j = (JabberClient)sender;
DataTable dt = new DataTable();
string birthdaymsg = "";
string fullname;
string department;
string query = "SELECT CONCAT(FirstName, ' ', MiddleName, ' ', LastName) as Fullname, DepartmentDescription FROM vw_EmployeeOrganization WHERE DATEPART(d, BirthDate) = DATEPART(d,GETDATE()) AND DATEPART(m, BirthDate) = DATEPART(m, GETDATE()) AND DepartmentDescription IN('Client Relations--CDO', 'E-Learning', 'Sales ', 'Client Relations', 'Sales-Davao', 'Sales-CDO', 'Client Relations--Cebu', 'Sales-Cebu')";
string constr = ConfigurationManager.ConnectionStrings["HRIS"].ConnectionString;
lstUsers.Clear();
using (SqlConnection conn = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = conn;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(dt);
}
}
}
foreach (DataRow row in dt.Rows)
{
fullname = row["Fullname"].ToString();
department = row["DepartmentDescription"].ToString();
birthdaymsg = "Happy Birthday! " + fullname + " from " + department + "." +
System.Environment.NewLine + "May today be filled with sunshine and smile, laughter and love.";
string queryRecipient = "SELECT * FROM tbl_MPAlertUsers";
string constr2 = ConfigurationManager.ConnectionStrings["Constring"].ConnectionString;
using (SqlConnection conn2 = new SqlConnection(constr2))
{
using (SqlCommand cmd2 = new SqlCommand(queryRecipient))
{
cmd2.Connection = conn2;
conn2.Open();
SqlDataReader reader = cmd2.ExecuteReader();
while (reader.Read())
{
lstUsers.Add(reader["ADname"].ToString());
}
reader.Close();
conn2.Close();
}
}
//Send to Recipient
for (int i = 0; i <= lstUsers.Count - 1; i++)
{
if (lstUsers[i].ToString().Trim().Length > 1)
{
WriteToFile("Trying to send spark to: " + lstUsers[i].ToString());
j.Message(lstUsers[i], birthdaymsg);
}
}
done.Set();
}
this.ScheduleService();
}
catch (Exception ex)
{
WriteToFile("Simple Service Error on: {0} " + ex.Message + ex.StackTrace);
//Stop the Windows Service.
using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController("SparkBirthDayGreeting"))
{
serviceController.Stop();
}
}
}
public void ScheduleService()
{
try
{
Schedular = new Timer(new TimerCallback(j_OnAuthenticate));
string mode = ConfigurationManager.AppSettings["Mode"].ToUpper();
this.WriteToFile("Simple Service Mode: " + mode + " {0}");
//Set the Default Time.
DateTime scheduledTime = DateTime.MinValue;
if (mode == "DAILY")
{
//Get the Scheduled Time from AppSettings.
scheduledTime = DateTime.Parse(System.Configuration.ConfigurationManager.AppSettings["ScheduledTime"]);
if (DateTime.Now > scheduledTime)
{
//If Scheduled Time is passed set Schedule for the next day.
scheduledTime = scheduledTime.AddDays(1);
}
}
if (mode.ToUpper() == "INTERVAL")
{
//Get the Interval in Minutes from AppSettings.
int intervalMinutes = Convert.ToInt32(ConfigurationManager.AppSettings["IntervalMinutes"]);
//Set the Scheduled Time by adding the Interval to Current Time.
scheduledTime = DateTime.Now.AddMinutes(intervalMinutes);
if (DateTime.Now > scheduledTime)
{
//If Scheduled Time is passed set Schedule for the next Interval.
scheduledTime = scheduledTime.AddMinutes(intervalMinutes);
}
}
TimeSpan timeSpan = scheduledTime.Subtract(DateTime.Now);
string schedule = string.Format("{0} day(s) {1} hour(s) {2} minute(s) {3} seconds(s)", timeSpan.Days, timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds);
this.WriteToFile("Simple Service scheduled to run after: " + schedule + " {0}");
//Get the difference in Minutes between the Scheduled and Current Time.
int dueTime = Convert.ToInt32(timeSpan.TotalMilliseconds);
//Change the Timer's Due Time.
Schedular.Change(dueTime, Timeout.Infinite);
}
catch (Exception ex)
{
WriteToFile("Simple Service Error on: {0} " + ex.Message + ex.StackTrace);
//Stop the Windows Service.
using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController("SparkBirthDayGreeting"))
{
serviceController.Stop();
}
}
}
private void WriteToFile(string text)
{
string path = "C:\\ServiceLog.txt";
using (StreamWriter writer = new StreamWriter(path, true))
{
writer.WriteLine(string.Format(text, DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt")));
writer.Close();
}
}
I hope someone can help me with this. I am stuck :(
Thank you.
The problem is that JabberClient's event is handled in j_OnAuthenticate and the timer's event is handled with it:
Schedular = new Timer(new TimerCallback(j_OnAuthenticate));
...
JabberClient j = new JabberClient();
j.OnAuthenticate += new bedrock.ObjectHandler(j_OnAuthenticate);
And in j_OnAuthenticate the first thing you do is cast the sender to JabberClient
private void j_OnAuthenticate(object sender)
{
try
{
JabberClient j = (JabberClient)sender;
...
}
catch (Exception ex)
{
WriteToFile("Simple Service Error on: {0} " + ex.Message + ex.StackTrace);
//Stop the Windows Service.
using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController("SparkBirthDayGreeting"))
{
serviceController.Stop();
}
}
The catch block handles and logs the exception.
You would have to change the code to do different things depending on the sender e.g.
if(sender is JabberClient)
{
//do something
}
else if(sender is Timer)
{
//do something else
}
Or give the timer a different callback function

How do I save continuous console output to a text file in c#?

I'm quite a noob at programming and I've been stuck at this for a while now. I'm using the following code to get continuous data output streamed to a command prompt. How can I ensure that the output gets copied to a text file after closing the prompt manually?
public static void Main(string[] args)
{
Connector connector;
Console.WriteLine("HelloEEG!");
// Initialize a new Connector and add event handlers
connector = new Connector();
connector.DeviceConnected += new EventHandler(OnDeviceConnected);
connector.DeviceConnectFail += new EventHandler(OnDeviceFail);
connector.DeviceValidating += new EventHandler(OnDeviceValidating);
// Scan for devices across COM ports
// The COM port named will be the first COM port that is checked.
connector.ConnectScan("COM40");
// Blink detection needs to be manually turned on
connector.setBlinkDetectionEnabled(true);
Thread.Sleep(400000);
System.Console.WriteLine("Goodbye.");
connector.Close();
Environment.Exit(0);
}
// Called when a device is connected
static void OnDeviceConnected(object sender, EventArgs e)
{
Connector.DeviceEventArgs de = (Connector.DeviceEventArgs)e;
Console.WriteLine("Device found on: " + de.Device.PortName);
de.Device.DataReceived += new EventHandler(OnDataReceived);
}
// Called when scanning fails
static void OnDeviceFail(object sender, EventArgs e)
{
Console.WriteLine("No devices found! :(");
}
// Called when each port is being validated
static void OnDeviceValidating(object sender, EventArgs e)
{
Console.WriteLine("Validating: ");
}
// Called when data is received from a device
static void OnDataReceived(object sender, EventArgs e)
{
Device.DataEventArgs de = (Device.DataEventArgs)e;
DataRow[] tempDataRowArray = de.DataRowArray;
TGParser tgParser = new TGParser();
tgParser.Read(de.DataRowArray);
/* Loops through the newly parsed data of the connected headset*/
// The comments below indicate and can be used to print out the different data outputs.
for (int i = 0; i < tgParser.ParsedData.Length; i++)
{
//string temp = tgParser.ParsedData[1].ToString;
//Console.WriteLine(tgParser.ParsedData.Length + " + " + temp);
if (tgParser.ParsedData[i].ContainsKey("Raw"))
{
//Console.WriteLine("Raw Value:" + tgParser.ParsedData[i]["Raw"]);
//Console.WriteLine("Raw Value:" + tgParser.ParsedData[i]["Raw"]);
}
if (tgParser.ParsedData[i].ContainsKey("PoorSignal"))
{
//The following line prints the Time associated with the parsed data
//Console.WriteLine("Time:" + tgParser.ParsedData[i]["Time"]);
Console.WriteLine("Time:" + tgParser.ParsedData[i]["Time"]);
//A Poor Signal value of 0 indicates that your headset is fitting properly
Console.WriteLine("Poor Signal:" + tgParser.ParsedData[i]["PoorSignal"]);
poorSig = (byte)tgParser.ParsedData[i]["PoorSignal"];
}
if (tgParser.ParsedData[i].ContainsKey("Attention"))
{
//Console.WriteLine("Att Value:" + tgParser.ParsedData[i]["Attention"]);
Console.WriteLine("Att Value:" + tgParser.ParsedData[i]["Attention"]);
}
if (tgParser.ParsedData[i].ContainsKey("Meditation"))
{
//Console.WriteLine("Med Value:" + tgParser.ParsedData[i]["Meditation"]);
Console.WriteLine("Med Value:" + tgParser.ParsedData[i]["Meditation"]);
}
if (tgParser.ParsedData[i].ContainsKey("EegPowerDelta"))
{
//Console.WriteLine("Delta: " + tgParser.ParsedData[i]["EegPowerDelta"]);
Console.WriteLine("Delta: " + tgParser.ParsedData[i]["EegPowerDelta"]);
}
if (tgParser.ParsedData[i].ContainsKey("BlinkStrength"))
{
//Console.WriteLine("Eyeblink " + tgParser.ParsedData[i]["BlinkStrength"]);
Console.WriteLine("Eyeblink " + tgParser.ParsedData[i]["BlinkStrength"]);
}
}
}
It will be much better to log every console output to a file as it happens. Instead of waiting to write to file when the app is closed manually. To save yourself a lot of coding, you can use log4net to handle the logging.
There's several different ways of approaching this, and with a bit of research I'm sure you could find a few, however this is the solution I would use for this particular action :
As Jonesy mentioned in the comments, I would firstly tidy up your Main. Create a separate class to perform the console writeline and the text output at the same time.
In this class perhaps use a loop to output the data to a file as and when it happens, therefore you wouldn't have to code in the logic when the console is closed manually, which in turn would cover unexpected errors and loss of logs.
This might work.
public static void WriteToFileAndConsole()
{
string outFile = "ConsoleOut.txt";
using (FileStream fileStream = new FileStream(outFile, FileMode.OpenOrCreate))
{
using (StreamWriter writer = new StreamWriter(fileStream))
{
using (TextWriter originalConsoleOut = Console.Out)
{
Console.SetOut(writer);
Console.WriteLine("Hello To File");
Console.SetOut(originalConsoleOut);
}
}
}
Console.WriteLine("Hello to console only");
}

Accessing a file by two processes

There is a file in my application. I want to use this file to write data(which is coming from a machine connected on LAN) as well as for reading data from it and writing in a database. Therefore, I am placing a condition to check if the file is free.
This is my code:
static public bool IsFileFree(FileInfo file)
{
FileStream stream = null;
try
{
stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
}
catch (IOException)
{
return false;
}
finally
{
if (stream != null)
stream.Close();
}
return true;
}
static public void dataread()
{
FileInfo info = new FileInfo("C:\\Users\\cdac\\Desktop\\server\\server\\TextFile2.txt");
while (true)
{
if (IsFileFree(info) == true)
{
byte[] bytesFrom = new Byte[1000];
Program.socarray[0].Receive(bytesFrom);
char[] stuffed = System.Text.Encoding.UTF8.GetString(bytesFrom).ToCharArray();
char[] final;
final = stuffed.ToArray();
string foo = new string(final);
System.IO.File.WriteAllText(#"C:\Users\cdac\Desktop\server\server\TextFile2.txt", foo);
System.Threading.Thread.Sleep(10);
}
else
{
MessageBox.Show("File is already ", "My Application", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
}
}
}
static public void datawrite()
{
FileInfo info = new FileInfo("C:\\Users\\cdac\\Desktop\\server\\server\\TextFile2.txt");
while (true)
{
if (IsFileFree(info) == true)
{
string MyConString = "server=localhost;" +
"database=cdac;" +
"User Id=root;" +
"password=cdac56;";
MySqlConnection connection = new MySqlConnection(MyConString);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
connection.Open();
// StreamReader reader = new StreamReader("C:\\tag_log_030610.txt");
StreamReader reader = new StreamReader("C:\\Users\\cdac\\Desktop\\server\\server\\TextFile2.txt");
string line;
while ((line = reader.ReadLine()) != null)
{
string[] parts = line.Split(';');
//command.CommandText = "insert into st_attn(rollno,Th_attn,Name) values('" + parts[0] + "','" + parts[1] + "','" + parts[2] + "')";
command.CommandText = "insert into st_attn(rollno,Name) values('" + parts[0] + "','" + parts[1] + "')";
Reader = command.ExecuteReader();
}
System.Threading.Thread.Sleep(10);
}
else
{
MessageBox.Show("File is already in use", "My Application",
MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
}
}
}
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
int i=0;
TcpListener listener = new TcpListener(8888);
listener.Start();
while(true)
{
Socket soc = listener.AcceptSocket();
socarray[i] = soc;
i++;
if (i == NUMBEROFREADERS)
break;
}
Thread writetotextfile = new Thread(dataread);
writetotextfile.Start();
Thread writetodatabase = new Thread(datawrite);
writetodatabase.Start();
Application.Run(new Form1());
}
When i execute it, my application is not writing anything in textfile and the data which is already existing in this text file is being written in the database with every execution or this application.
I want my application to write data in the text file which is not being written by it currently. Moreover both the processes( one that is for writing data in text file and other for writing data in DB from text file) when make conflict i want to give preference to one which is writing data in text file and want the other process to wait till then. And as soon as data is written in text file and it is free, the data is to be written in database from text file.

Problems with OleDbConnection when opening a c# form with command prompt or hyperlink, but not Windows Explorer

I have a c# program which does the following on form load:
Creates an OleDbConnection to a database in the same folder as the program
Gets the computer name
Gets the username
Fills in some textbox fields on the form with data obtained from the database
When I open the form using Windows explorer, shortcut, or debugging in visual studio express 2013, it does all of this without any issues. When trying to open it with a command prompt or with a hyperlink, the database connection is not established, but no error messages appear. The textbox fields are filled with "not found" as a result of my try-catch statements around the oledb commands. The same try-catch statement should print ex.message to a text file, but that does not happen either. As stated before, this all runs flawlessly when running from debug mode in vs or running the program by opening it in Windows explorer, so I'm not sure how to debug this.
2 questions - Is there a known problem with opening c# forms which try to establish OleDb connections with access databases on form load when launching the program from command prompt or a shortcut? If so, are there any workarounds? Given that it runs fine in debug mode in vs, and my catch statements seem to be terminating prematurely without error messages, is there any other way to debug and find out exactly where the problem occurs?
I left off some of the irrelevant lines of code to make this shorter.
private void Form1_Load(object sender, EventArgs e)
{
userData = onLoad.loadDb(out userNotFound);
ComputerName = onLoad.getComputer();
// Session Notification
WTSRegisterSessionNotification(this.Handle, NotifyForThisSession);
// Initialize Hooks
initialize_Hooks();
if (userData.Count < 4)
{
for(int i = 0; i<4; i++) { userData.Add("Not Found"); }
}
// globals:
FullID = userData[0];
ID = userData[2];
firstName = userData[1];
lastName = userData[0];
nanid = userData[3];
fullName = firstName + " " + lastName;
// Fill in Form
label1.Text = fullName;
label2.Text = ID;
label3.Text = nanid;
}
public class onLoad
{
public static string getUser() // returns Environment.UserName
public static string getComputer() // returns System.Environment.MachineName;
public static List<string> loadDb(out bool userNotFound)
{
List<string> rList = new List<string>();
string strAccessConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=db.mdb";
string strAccessSelect = "SELECT (//select statement which works fine when I open the program in explorer or vs debug)
DataSet myDataSet = new DataSet();
OleDbConnection myAccessConn = null;
try
{
myAccessConn = new OleDbConnection(strAccessConn);
}
catch(Exception ex)
{
for(int i = 0; i<4; i++) { rList.Add("Not Found"); }
error_handler.error_logger(ex.Message);
userNotFound = true;
return rList;
}
try
{
OleDbCommand myAccessCommand = new OleDbCommand(strAccessSelect, myAccessConn);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(myAccessCommand);
myAccessConn.Open();
myDataAdapter.Fill(myDataSet,"table1");
}
catch (Exception ex)
{
error_handler.error_logger(ex.Message);
userNotFound = true;
for(int i = 0; i<4; i++) { rList.Add("Not Found"); }
return rList;
}
finally
{
myAccessConn.Close();
}
try
{
DataRowCollection dra = myDataSet.Tables[0].Rows;
foreach (DataRow dr in dra)
{
code that conditions the data, works fine when running the program
}
}
catch(Exception ex)
{
string returnString = ex.Message;
error_handler.error_logger(ex.Message);
userNotFound = true;
for(int i = 0; i<4; i++) { rList.Add("Not Found"); }
return rList;
}
return rList;
}
}
class error_handler
{
public static string filename = "error.txt";
public static void error_logger(string error_message)
{
error_message = onLoad.getUser() + "\t" + DateTime.Now.ToString("MM/dd/yy hh:mm:ss") + "\t" + onLoad.getComputer() + "\t" + "Error: " + error_message;
if (!File.Exists(filename))
//writes error_message to a new text file or appends if it already exists. works fine when running from windows explorer or vs debug
}
}
I bet that shortcut passes in the working directory as a parameter. The documentation for File.Exists() states that when using a relative path the relative path information is interpreted as relative to the current working directory.
You can use the Directory.GetCurrentDirectory() function to determine if the path is set correctly.
If you are using files that you know are going to be in a path relative to the application I would use Application's path or at least set Environment.CurrentDirectory = Application's path.
Also take a look at the Environment.GetCommandLineArgs()[0]. That is probally being set by the shortcut.

Categories