My connection class doesn't read inputs values? - c#

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);

Related

Change DBase On Run Time C# app

I have developed an accounting program that is working beautifully, but now a new need has arisen.
When I enter the program, by default it reads the DB that I put in the file WinSCM.exe.config and if I want to change I have to exit the program and edit the file changing the DB name.
I did not want it to be this way, because my client does accounting for several companies and each company is a DB, so I wanted a way to select a company and when selecting this company the database is automatically changed in the release version.
I'm using Entity Framework to connect to Sql Server DB
Can someone help me?
I'm not sure what reading your DB is, but normally when you use Entity Framework you create a DbContext object whenever you need to do a query, or at utmost a few queries. You are not supposed to keep this DbContext alive for longer periods of time, say more than a few seconds. A minute would be very rare.
Whenever you create the Dbcontext instance you could use the default constructor that uses the config file to get the connection string to the database.
However one of the other constructors let you define the connection string to the database in the constructor. So if you want to construct your DbContext and connect it to a different database, just use that constructor
If you don't know the connection string, but you have a DbConnection to the database, there will be even a constructor for this case.
Hi Everybody Thank alot for your Answer. I just Solved My Question like this:
Fisrt of all, I created a class wich I called ConnetionTolls with this Content://.
public static class ConnectionTools
{
// all params are optional
public static void ChangeDatabase(
this DbContext source,
string initialCatalog = "",
string dataSource = "",
string userId = "",
string password = "",
bool integratedSecuity = true,
string configConnectionStringName = "")
/* this would be used if the
* connectionString name varied from
* the base EF class name */
{
try
{
// use the const name if it's not null, otherwise
// using the convention of connection string = EF contextname
// grab the type name and we're done
var configNameEf = string.IsNullOrEmpty(configConnectionStringName)
? source.GetType().Name
: configConnectionStringName;
// add a reference to System.Configuration
var entityCnxStringBuilder = new EntityConnectionStringBuilder
(System.Configuration.ConfigurationManager
.ConnectionStrings[configNameEf].ConnectionString);
// init the sqlbuilder with the full EF connectionstring cargo
var sqlCnxStringBuilder = new SqlConnectionStringBuilder
(entityCnxStringBuilder.ProviderConnectionString);
// only populate parameters with values if added
if (!string.IsNullOrEmpty(initialCatalog))
sqlCnxStringBuilder.InitialCatalog = initialCatalog;
if (!string.IsNullOrEmpty(dataSource))
sqlCnxStringBuilder.DataSource = dataSource;
if (!string.IsNullOrEmpty(userId))
sqlCnxStringBuilder.UserID = userId;
if (!string.IsNullOrEmpty(password))
sqlCnxStringBuilder.Password = password;
// set the integrated security status
sqlCnxStringBuilder.IntegratedSecurity = integratedSecuity;
// now flip the properties that were changed
source.Database.Connection.ConnectionString
= sqlCnxStringBuilder.ConnectionString;
}
catch (Exception ex)
{
// set log item if required
}
}
********the way to use it is like this***************
//I use this method in a diferent Class
//This method returns the Entity i use with new connections
public static MyEntities SelectDb(String DataBase,String sqlUser,String pw, String serverInstance){
var selectedDbase = new MyEntities();
// so only reference the changed properties
// using the object parameters by name
selectedDbase.ChangeDatabase
(
initialCatalog: DataBase,
userId: sqlUser,
password: pw,
dataSource: serverInstance// could be ip address 100.23.45.67 etc
);
return selectedDbase;
}
I want to thank everyone here and on other forums because this was the result of Your Contributions

Error throw exception when insert data with thread

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.

Payment not being created

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;

linq to sql one-one relationship C#

It is necessary that after the creation of records in the table "Clients" took up ID. Later ID used to create a new entry in the "Clients_details".
var user = GetUsers();
var userdet = GetclientsDetails();
string hashedpass = getMd5Hash(UIPassword.Text);
var newreg = new Clients
{
login = UILogin.Text,
password = hashedpass,
subscribeid = Convert.ToInt32(UIId.Text)
};
user.InsertOnSubmit(newreg);
user.Context.SubmitChanges();
var details = new Clients_details
{
city = UICity.Text,
first_name = UIFirst_name.Text,
last_name = UIFamiliya.Text,
name = UIName.Text,
Clients = newreg
};
userdet.InsertOnSubmit(details);
userdet.Context.SubmitChanges();
After this code fails:
"An attempt was made to perform an operation Attach or Add in relation to an object that is not new, and possibly loaded from another DataContext. This operation is not supported."
How to properly create a record that does not appear a mistake? Thank you!
private static Table<Clients> GetUsers()
{
var dce = new BaseDBMLDataContext();
return dce.Clients;
}
private static Table<Clients_details> GetclientsDetails()
{
var dce = new BaseDBMLDataContext();
return dce.Clients_details;
}
Looks like userdet.Context and user.Context was built using a different dataContext and that needs to be created using the same dataContext rather than instantiating a new one.
I think you need to only call the SubmitChanges only once in the end, and also you need to make sure the user and userdet you are using share the same context
As the error clearly states, you're using different contexts (user and userdet) for each entity to add. You should have one DataContext and use that one to add the entities.
Yes looks like you're using two different instances of the same context:
user.Context.SubmitChanges();
userdet.Context.SubmitChanges();
A good approach to build up your entities should be something like :
//Create your client details entity
var details = new Clients_details
{
city = UICity.Text,
first_name = UIFirst_name.Text,
last_name = UIFamiliya.Text,
name = UIName.Text
};
//Create your client entity
var newreg = new Clients
{
login = UILogin.Text,
password = hashedpass,
subscribeid = Convert.ToInt32(UIId.Text),
//Assigning the details entity (FK) to the client
ClientDetails = details
};
//Saving both the client and its details
user.InsertOnSubmit(newreg);
user.Context.SubmitChanges();

How To add another constructor with parameter in linq class(Table)

I am using LINQ to SQL in an ASP.NET project. While inserting the table I need to convert the values to the particular table object and I need to insert.
For that I created a new constructor in that table with parameter so that I can assign my value to that table object , the assign the functionality is working but while inserting (obj.TS_Questions.InsertOnSubmit(mytableobject);) I get null exception.
my code::
default constructor for my table
public TS_Question()
{
this._TS_Options = new EntitySet<TS_Option>(new Action<TS_Option>(this.attach_TS_Options), new Action<TS_Option>(this.detach_TS_Options));
this._TS_QuestGroups = new EntitySet<TS_QuestGroup>(new Action<TS_QuestGroup>(this.attach_TS_QuestGroups), new Action<TS_QuestGroup>(this.detach_TS_QuestGroups));
this._TS_QuestRecords = new EntitySet<TS_QuestRecord>(new Action<TS_QuestRecord>(this.attach_TS_QuestRecords), new Action<TS_QuestRecord>(this.detach_TS_QuestRecords));
this._TS_Admin = default(EntityRef<TS_Admin>);
this._TS_LevelType = default(EntityRef<TS_LevelType>);
this._TS_OptionTypeLT = default(EntityRef<TS_OptionTypeLT>);
OnCreated();
}
constructor created by me
public TS_Question(Guid Quest_QuestIDBL, string Quest_NameBL, Nullable<Guid> Quest_OptionTypeIDBL, Guid Quest_AdminIDBL, Guid Ques_LevelIDBL, int Quest_TimeBL, int Quest_MarkBL, string Qest_ExplanationBL, Nullable<bool> Qest_IsMultipleAnswerBL)
{
this._TS_Options = new EntitySet<TS_Option>(new Action<TS_Option>(this.attach_TS_Options), new Action<TS_Option>(this.detach_TS_Options));
this._TS_QuestGroups = new EntitySet<TS_QuestGroup>(new Action<TS_QuestGroup>(this.attach_TS_QuestGroups), new Action<TS_QuestGroup>(this.detach_TS_QuestGroups));
this._TS_QuestRecords = new EntitySet<TS_QuestRecord>(new Action<TS_QuestRecord>(this.attach_TS_QuestRecords), new Action<TS_QuestRecord>(this.detach_TS_QuestRecords));
this._TS_Admin = default(EntityRef<TS_Admin>);
this._TS_LevelType = default(EntityRef<TS_LevelType>);
this._TS_OptionTypeLT = default(EntityRef<TS_OptionTypeLT>);
OnCreated();
this._Quest_QuestID = Quest_QuestIDBL;
this._Quest_Name = Quest_NameBL;
if (Quest_OptionTypeIDBL != null)
{
this._Quest_OptionTypeID = Quest_OptionTypeIDBL;
}
this._Quest_AdminID = Quest_AdminIDBL;
this._Ques_LevelID = Ques_LevelIDBL;
this._Quest_Time = Quest_TimeBL;
this._Quest_Mark = Quest_MarkBL;
this._Qest_Explanation = Qest_ExplanationBL;
this._Qest_IsMultipleAnswer = Qest_IsMultipleAnswerBL;
}
Please help me out from this problem
Honestly, I haven't looked too deep, but it looks like that OnCreated is sitting a little far north... You probably want to call it after you're done setting up your variables. Other than that i'd say make sure you're properly initializing everything in the method calling the constructor.
You can call default constructor like this, it works fine for me:
public partial class MyClass
{
public MyClass(string fieldValue1,int fieldValue2)
: this()
{
this.field1= fieldValue1;
this.field2 = fieldValue2;
}
}
If this do the trick, you can read more about using contructors in C# here.

Categories