I have probem when use thread in winform.
I have error when debug program.
My Application throw exception when start program.
I define class RunInUIThread is:
private void RunInUIThread(Delegate method)
{
this.BeginInvoke(method);
}
And in RunInUIThread method like:
BaiXeBUS baixe = new BaiXeBUS();
RunInUIThread(new ThreadStart(delegate ()
{
BaiXeDTO obj = new BaiXeDTO(); //Map all to define database
txtKhuVucBai.Text = mReader.CurrentCardIDBlock1.ToString();
txtMaThe.Text = mReader.CurrentCardIDBlock2.ToString();
//If I comment all below code. It's work. But I need Insert data to database.
txtKhuVucBai.Text = obj.IDBaiXe.ToString();
txtMaThe.Text = obj.IDRF.ToString();
obj.BienSoXe = textBox1.Text;
obj.HinhBienSo = color.ToString();
obj.HinhChuXe = img.ToString();
obj.ThoiGianVao = DateTime.Now.ToLocalTime();
obj.ThoiGianRa = DateTime.Now.ToLocalTime();
baixe.BaiXe_Insert(obj); //Contain data access layer to insert data with store procedure.
}));
Why my code not work. Someone can explain me and how to fix problem?
Thank all reader!!!
What I mean is trying to run this block of code without the ThreadStart
{
BaiXeDTO obj = new BaiXeDTO(); //Map all to define database
txtKhuVucBai.Text = mReader.CurrentCardIDBlock1.ToString();
txtMaThe.Text = mReader.CurrentCardIDBlock2.ToString();
//If I comment all below code. It's work. But I need Insert data to database.
txtKhuVucBai.Text = obj.IDBaiXe.ToString();
txtMaThe.Text = obj.IDRF.ToString();
obj.BienSoXe = textBox1.Text;
obj.HinhBienSo = color.ToString();
obj.HinhChuXe = img.ToString();
obj.ThoiGianVao = DateTime.Now.ToLocalTime();
obj.ThoiGianRa = DateTime.Now.ToLocalTime();
baixe.BaiXe_Insert(obj); //Contain data access layer to insert data with store procedure.
}
This is to debug your code within the main thread.
#JoelLegaspiEnriquez, your recommned me to remove [STAThread] in Program.cs?
If I comment this line. This have problem in control AxLiveX1 is control of camera ip.
The txtKhuVucBai.Text = mReader.CurrentCardIDBlock1.ToString(); is Guid type with 16byte: 8d58d690-6b71-4ee8-85ad-006db0287bf1.
But i assign txtKhuVucBai to Guid type is:
private Guid mCurrentCardIDBlock1;
public Guid CurrentCardIDBlock1
{
get { return mCurrentCardIDBlock1; }
}
The mCurrentCardIDBlock1 is type of RFID reader with 32 character random.
Related
I'm trying to make a database. I made a form and I want to get the data from that. Everything seems okay, but my database didn't get the update and didn't change. I'm using a local database. I tried to change "Copy to output directory" but nothing happened... The SubmitChanges seems ok: I get the Message, but after the program is closed the database doesn't contain the new data... I saw a lot of posts with similar problems, but I didn't find a solution.
My Code:
private void felvetButton_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
if (f2.ShowDialog() == DialogResult.OK)
{
Match m = new Match();
try
{
m.datum = f2.datumTextBox.Text;
m.mod_fk = Convert.ToInt32(f2.modTextBox.Text);
m.acc_fk = Convert.ToInt32(f2.accTextBox.Text);
m.champion = f2.champTextBox.Text;
m.szerep_fk = Convert.ToInt32(f2.roleTextBox.Text);
m.kimenet = f2.resultTextBox.Text;
m.mhossz = f2.lengthTextBox.Text;
m.kill = Convert.ToInt32(f2.killTextBox.Text);
m.death = Convert.ToInt32(f2.deathTextBox.Text);
m.assist = Convert.ToInt32(f2.assistTextBox.Text);
m.kda = float.Parse(f2.kdaTextBox.Text);
m.killpart = float.Parse(f2.kpTextBox.Text);
m.farm = Convert.ToInt32(f2.farmTextBox.Text);
m.ward = Convert.ToInt32(f2.wardTextBox.Text);
m.redward = Convert.ToInt32(f2.redwTextBox.Text);
db.SubmitChanges();
MessageBox.Show("New match added to the database!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
Don't you have to make the entity layer aware of this new object? I imagine you need to call something like this for new entities:
db.Matches.InsertOnSubmit(match);
Its perfectly fine to load entities from the database via this entity layer, modify them, and then use db.SubmitChanges() because the entity layer already knows about existing objects! How is it supposed to know about this new object if the entity layer doesn't have any reference to it?
I am fairly new to c# and am getting an error "Object reference not set to an instance of an object." I am creating an XML packet and sending it to an external device for control. If I put the following code on the form in a click event it works beautifully.
On the btn Click event it looks like this:
SetTestInfoResponse testDataDs = null;
TestInformation testInfo = null;
this.PopulateTestDataXml();
string stringRequestXML = string.Empty;
string stringResponseXML = string.Empty;
//Creates Request packet
stringRequestXML = XMLCommunicationPackets.SetTestInformation (testInfo, testInfo.TestID, testInfo.TestUser, testInfo.TestSampleType, testInfo.TestSampleId, testInfo.TestMethodNumber, testInfo.TestTubeSn, testInfo.TestComments);
//Write set Test Info XML Packet and get response for ack or failure.
stringResponseXML = PluginContext.GetInstance().InstrumentDriverCurrent.GetInstrumentControl().SetCommonParameter(stringRequestXML);
However, If I move my entire function out of the form and try to call it when clicking a button I get the error.
written in a method off the form in a .cs file it reads:
public static SetTestInfoResponse SetTestData()
{
SetTestInfoResponse testDataDs = null;
TestInformation testInfo = null;
string stringRequestXML = string.Empty;
string stringResponseXML = string.Empty;
//Creates Request packet
stringRequestXML = XMLCommunicationPackets.SetTestInformation (testInfo, testInfo.TestID, testInfo.TestUser, testInfo.TestSampleType, testInfo.TestSampleId, testInfo.TestMethodNumber, testInfo.TestTubeSn, testInfo.TestComments);
//Write set Test Info XML Packet and get response for ack or failure.
stringResponseXML = PluginContext.GetInstance().InstrumentDriverCurrent.GetInstrumentControl().SetCommonParameter(stringRequestXML);
The error occurs when building stringRequestXml.
Part of my problem is the PopulateTestData() is a method on the form itself. Its purpose is to take data from txtboxes and cmbboxes and assign them to their respective arguments..
private TestInformation PopulateTestDataXml()
{
TestInformation UiTestData = new TestInformation();
UiTestData.TestID = txtTestId.Text;
UiTestData.TestUser = cmbUsers.SelectedItem.ToString();
UiTestData.TestSampleType = txtSampleType.Text;
UiTestData.TestSampleId = txtSampleId.Text;
UiTestData.TestMethodNumber = Convert.ToInt32(cmbMethod.SelectedItem);
UiTestData.TestTubeSn = txtTubeSerialNum.Text;
UiTestData.TestComments = txtComments.Text;
return UiTestData;
}
Here is the SetTestInformation() method where I am getting the error:
public static string SetTestInformation(TestInformation testInfo, string stringTestId, string stringUser, string stringSampleType, string stringSampleId, int intMethodNumber, string stringTubeSn, string stringComments)
{
try
{
string stringRequestXMLPacket = string.Empty;
string stringType = #"Request";
string stringCommand = #"Set";
string stringArgument = #"TestInformation";
CommunicationPacket requestXMLPacket = new CommunicationPacket(stringRootTag, stringXMLVersion, stringType, stringCommand);
requestXMLPacket.AddCommandArgument(stringArgument);
requestXMLPacket.AddArgumentItem(stringArgument, "sTestId", testInfo.TestID.ToString());
requestXMLPacket.AddArgumentItem(stringArgument, "sUser", testInfo.TestUser.ToString());
requestXMLPacket.AddArgumentItem(stringArgument, "sSampleType", testInfo.TestSampleType.ToString());
requestXMLPacket.AddArgumentItem(stringArgument, "sSampleId", testInfo.TestSampleId.ToString());
requestXMLPacket.AddArgumentItem(stringArgument, "nMethodNumber", testInfo.TestMethodNumber.ToString());
requestXMLPacket.AddArgumentItem(stringArgument, "sTubeSn", testInfo.TestTubeSn.ToString());
requestXMLPacket.AddArgumentItem(stringArgument, "sComments", testInfo.TestComments.ToString());
stringRequestXMLPacket = requestXMLPacket.CreateXMLPacket();
return stringRequestXMLPacket;
}
catch (Exception ex)
{
throw ex;
}
}
Iknow I am having trouble with the variable scope here. I still have to use the method PopulateTestDataXml on the form before I call the setTestData() method. But when I call the Method I have to declare testInfo = null or the parameters for SetTestInformation are not valid ("Does not exist in the current context"). What would I need to pass and how for this to work as a called method on the form btn click? I need to do this as I have alot of deserializing functions written as well to catch error messages in the response xml (these all work fine) and its just too much info on the click event. (And I need to learn).
Thanks
Neither of your examples should work (regardless of where you put them). This is simply incorrect:
TestInformation testInfo = null;
// ...
stringRequestXML = XMLCommunicationPackets.SetTestInformation (testInfo,
testInfo.TestID, ...);
// ^^ BANG!
Your testInfo object is null. When you try and access anything on a null object.. a NullReferenceException is thrown. You need to initialize it first. You're trying to do that in your PopulateTestDataXml method.. which returns the object your after. So change your code to this:
TestInformation testInfo = PopulateTestDataXml(); // assign it
Here is your problem..
public static SetTestInfoResponse SetTestData()
{
SetTestInfoResponse testDataDs = null;
TestInformation testInfo = null;
string stringRequestXML = string.Empty;
string stringResponseXML = string.Empty;
//Creates Request packet
stringRequestXML = XMLCommunicationPackets.SetTestInformation (testInfo, testInfo.TestID, testInfo.TestUser, testInfo.TestSampleType, testInfo.TestSampleId, testInfo.TestMethodNumber, testInfo.TestTubeSn, testInfo.TestComments);
//Write set Test Info XML Packet and get response for ack or failure.
stringResponseXML = PluginContext.GetInstance().InstrumentDriverCurrent.GetInstrumentControl().SetCommonParameter(stringRequestXML);
Are you assigning values for these objects I see they are just declared but never assigned.
SetTestInfoResponse testDataDs = null;
TestInformation testInfo = null;
i don't see you use null objects, so i'm wonder if you set them later, also u said the error happen on
private TestInformation PopulateTestDataXml()
{
TestInformation UiTestData = new TestInformation();
UiTestData.TestID = txtTestId.Text;
UiTestData.TestUser = cmbUsers.SelectedItem.ToString();
UiTestData.TestSampleType = txtSampleType.Text;
UiTestData.TestSampleId = txtSampleId.Text;
UiTestData.TestMethodNumber = Convert.ToInt32(cmbMethod.SelectedItem);
UiTestData.TestTubeSn = txtTubeSerialNum.Text;
UiTestData.TestComments = txtComments.Text;
return UiTestData;
}
after moving it out of your form, which mean possibly it's text box references is broken...
so what you can do, is store a pointer, like in your program.cs where you call your form to show up,
you can create an static object of form, and then put it in your class, then set it in program.cs file like :
Form1 f=new Form();
MyClass.staticFormPointer = f;
and also replace (new Form()), with (f) on the calling method,
your my class is like this:
class MyClass{
public static Form1 staticFormPointer = null;
//your code
.
.
.
// and in your methods you call it like this txtBox1.Text -> staticFormPointer.txtBox1.Text
}
I have below classes and one mainForm. I want to get user login inputs and connect my oracle database. But when I track in debugging mode user inputs not assigned to getters and setters so, when I called my helper class to connect database null values passing to my connection string inside my connection class... and I can not access to my database. What I am doing wrong?
You don't set any values.
This:
AccessorClass s = new AccessorClass();
... = ConnectionClass.Connection(s.DB, s.ID, s.Password);
// ^^ ^^ ^^^^^^^^^ - no values in these
Use an initialization list to set them:
AccessorClass s = new AccessorClass() { DB = "Database", ID = "ID", Password = "Password" };
EDIT:
Your update won't work either. You're creating an AccessorClass object, then calling a method. In that method.. you're new'ing up another AccessorClass. Do this:
AccessorClass s = new AccessorClass ();
s.DB = txtDatabase.Text;
s.ID = txtID.Text;
s.Password = txtPassword.Text;
HelperClass.Get(s); // <--- pass the instance through
Then change your HelperClass.Get function to this:
public static void Get(AccessorClass s)
{
// REMOVED: AccessorClass s = new AccessorClass();
OracleConnection conn = ConnectionClass.Connection(s.DB, s.ID, s.Password);
My payments are not showing up in QuickBooks.
I can successfully create and update Customers. I can also successfully create and update Invoices. I cannot create Payments. But here's the thing, when I execute the Update command on my Payment object I do get a proper Id and Domain (NG) passed back. I've checked the Sync log file (IntuitSyncManagerLogger.log) after running a Sync but it has no error messages. Everything looks ok, there just is no payment associated with the invoice in QuickBooks.
I believe I'm setting all of the required fields but I'm not sure about two of them.
1) The PaymentLine has a field named TxnId. I'm setting it to be the Id and Domain of the InvoiceHeader, but am not sure if this is correct.
2) There is another required field (per the documentation) but I'm leaving it blank as I don't know what to populate it with. It's the DiscountAccountId field. I don't want a discount associated with the invoice.
Here is my code...
SqlConnection connection = new SqlConnection(m_connectionString);
connection.Open();
SqlCommand cmd = new SqlCommand("dbo.Intuit_GetPayment", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#glmvSyncId", SqlDbType.Int).Value = glmvSyncId;
SqlDataReader rdr = cmd.ExecuteReader();
rdr.Read();
Intuit.Ipp.Data.Qbd.PaymentHeader paymentHeader = new Intuit.Ipp.Data.Qbd.PaymentHeader();
paymentHeader.ARAccountId = new Intuit.Ipp.Data.Qbd.IdType() {
idDomain = Intuit.Ipp.Data.Qbd.idDomainEnum.QB,
Value = "37"
};
paymentHeader.ARAccountName = "Accounts Receivable";
paymentHeader.DepositToAccountId = new Intuit.Ipp.Data.Qbd.IdType() {
idDomain = Intuit.Ipp.Data.Qbd.idDomainEnum.QB,
Value = "35"
};
paymentHeader.DepositToAccountName = "Undeposited Funds";
paymentHeader.CustomerId = new Intuit.Ipp.Data.Qbd.IdType() {
idDomain = (rdr["cust_iddomain"].ToString() == "QB" ? Intuit.Ipp.Data.Qbd.idDomainEnum.QB : Intuit.Ipp.Data.Qbd.idDomainEnum.NG),
Value = rdr["cust_idvalue"].ToString()
}; // cust_iddomain and cust_idvalue are from the Customer
paymentHeader.DocNumber = rdr["invoicekey"].ToString();
paymentHeader.TxnDate = DateTime.Now;
List<Intuit.Ipp.Data.Qbd.PaymentLine> listLine = new List<Intuit.Ipp.Data.Qbd.PaymentLine>();
var paymentLine = new Intuit.Ipp.Data.Qbd.PaymentLine();
paymentLine.Amount = Convert.ToDecimal(rdr["amount"]);
paymentLine.TxnId = new Intuit.Ipp.Data.Qbd.IdType() {
idDomain = (rdr["invc_iddomain"].ToString() == "QB" ? Intuit.Ipp.Data.Qbd.idDomainEnum.QB : Intuit.Ipp.Data.Qbd.idDomainEnum.NG),
Value = rdr["invc_idvalue"].ToString()
}; // invc_iddomain and invc_idvalue are from the InvoiceHeader
listLine.Add(paymentLine);
Intuit.Ipp.Data.Qbd.Payment syncPayment = new Intuit.Ipp.Data.Qbd.Payment();
syncPayment.Header = paymentHeader;
syncPayment.Line = listLine.ToArray();
connection.Close();
Intuit.Ipp.Data.Qbd.Payment resultPayment = new Intuit.Ipp.Data.Qbd.Payment();
resultPayment = commonService.Add(syncPayment);
I suspect the problem is with TxnId.
All I'm doing is creating a Customer, then creating an Invoice for the Customer, then creating a Payment for the Invoice. Am I missing a object someplace?
Any and all help is greatly appreciated.
The Payment is likely going into an error state after sync. You can check by executing a PaymentQuery and setting ErroredObjectsOnly=true.
https://ipp.developer.intuit.com/0010_Intuit_Partner_Platform/0050_Data_Services/0500_QuickBooks_Windows/0100_Calling_Data_Services/0015_Retrieving_Objects#Objects_in_Error_State
If the entity is in error state, you can query for the specific reason using the Status API:
https://ipp.developer.intuit.com/0010_Intuit_Partner_Platform/0050_Data_Services/0500_QuickBooks_Windows/0600_Object_Reference/SyncStatus
SyncStatusRequest syncStatusRequest = new SyncStatusRequest();
syncStatusRequest.ErroredObjectsOnly = true;
syncStatusRequest.NgIdSet = new NgIdSet[] { new NgIdSet { NgId = <<EnterYourNgIdHere>>, NgObjectType = objectName.Payment } };
SyncStatusResponse[] response = dataServices.GetSyncStatus(syncStatusRequest);
If the payment is in error state, you can delete the entity from the cloud since it was never synced with QuickBooks:
https://ipp.developer.intuit.com/0010_Intuit_Partner_Platform/0050_Data_Services/0500_QuickBooks_Windows/0100_Calling_Data_Services/Deleting_an_Object
If a successful sync did occur with the entity at least once, but then an Update pushed it into error state, you will need to do a Revert:
https://ipp.developer.intuit.com/0010_Intuit_Partner_Platform/0050_Data_Services/0500_QuickBooks_Windows/0100_Calling_Data_Services/Reverting_an_Object
You can also try doing an Update directly on the entity in error state once you know the reason from the Status API, but it is not documented so it may not work.
Adding the following lines of code seems to have fixed the problem. The Payment is now being recorded in QuickBooks.
paymentHeader.TotalAmt = Convert.ToDecimal(rdr["amount"]);
paymentHeader.TotalAmtSpecified = true;
So, here is my hopefully unique spin on this common problem.
I do my query, get my objects then pass the object into a form where it populates the form with the data from the object (this is not passed in by reference).
I then edit the values of the object that was queried (via the form) and then return a new object constructed from the values in the form.
I then want to update this to the database. Attach does nothing (runs but does not update). SubmitChanges also does nothing (and both do nothing when used together).
What am I missing?
Update: here is the code I am using:
// In constructor
_dataMap = new DataMapDataContext();
_addresses = _dataMap.AddressItems
.Where(address => address.InsertUserName == _currentUser.Name).ToList();
public void EditButtonClick()
{
using (AddAddressForm form = new AddAddressForm(_addresses[_currentAddress]))
{
form.Text = "Edit Address";
if (DialogResult.OK == form.ShowDialog())
{
_addresses[_currentAddress] = form.Item;
_dataMap.SubmitChanges();
DisplayItem();
}
}
}
You'll need to get the record from the database, update it's values and then call SubmitChanges()
using(MyDataContext db = new MyDataContext())
{
// get the record
Product dbProduct = db.Products.Single(p => p.ID == 1);
// set new values
dbProduct.Quantity = 5;
dbProduct.IsAvailable = false;
// save them back to the database
db.SubmitChanges();
}
Turns out I was doing almost everything right.
I just needed to pass in the object I was editing by reference. That way when it got changed, it was not a new object that was returned, but the same one (that Linq-to-SQL already knew about.)
These are the two lines from the code above that got changed:
AddressItem itemToEdit = _addresses[_currentAddress];
using (AddAddressForm form = new AddAddressForm(ref itemToEdit))