C# + SQL + Xamarin Android: - c#

I've been stumped on this problem for a while, and although I have searched up my problems online, I haven't had much luck. So in my Android program made in Xamarin, in the button click event, I try to send data to the server, however, I would get this error:
System.InvalidOperationException: Update requires the command clone to have a connection object. The Connection property of the command clone has not been initialized.
I am using this code at this point:
using (SqlConnection connection = new SqlConnection(cs))
{
connection.Open();
SqlDataAdapter dataAdapter = new SqlDataAdapter($"Select * from Room", connection);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
Spinner roomsSPNR = FindViewById<Spinner>(Resource.Id.rooms);
int room = Convert.ToInt32(roomsSPNR.SelectedItem.ToString());
DataRow[] selected = rooms.Tables[0].Select($"RoomNo = {room}");
selected[0][3] = Id;
dataAdapter.Update(rooms); //Line giving the error
}
changeColors(Id);
I'm stumped on this, I can't really figure out why it is doing this. Can anyone help?
I have tried:
Setting the update.connection manually
Making an SQL command and putting the command builder's command into there(There is another error)
Setting the DataAdapter's update command to the method for the command builder
In the DataAdapter's initialization, I have changed the connection to the connection string
Many others that may not have any importance
Edit: Earlier in the code the program is able to read from the server and put it into 'rooms. On the other hand, I'm not familiar with making web services; is that what I need to do to allow it to update the database?

You cannot directly connect with a database in xamarin. You need to first create a webservice and use that web service to insert or fetch data from database.
If you need I will help you with webservices.

Related

Oracle Managed DataAccess connection object is keeping the connection open

I'm using Oracle.ManagedDataAccess Nuget package version 18.3.0. I tried many things. I tried to dispose everything I can think of, even oracle parameters objects. And wrapped everything inside a using block but to no avail. The only thing that actually worked for me is that the commented line OracleConnection.ClearPool(oracle);. Is this a bug, or some configuration related issue, or am I misunderstand things here? Also, I tried to remove the reference of Oracle.ManagedDataAccess and replaced it with a reference to System.Data.OracleClient and that actually worked for me. It automatically closed the connection, so no connection left with "In-Active" status. The code below I moved it into a simple, single button, Windows Forms application to make 100% sure nothing is interfering and the problem still occurring.
using (var oracle = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=myhost)(PORT=SomePortHere))(CONNECT_DATA=(SERVER=SHARED)(SERVICE_NAME=anotherHost)))", new OracleCredential(userName,password)))
{
oracle.Open();
using (var command = new OracleCommand())
{
var query = "SELECT x from y where z=:param1";
command.Connection = oracle;
command.CommandText = query;
command.CommandType = System.Data.CommandType.Text;
var param1 = new OracleParameter(":param1", xyz);
command.Parameters.Add(param1);
using (var reader = command.ExecuteReader())
{
if (reader.Read())
{
//read the data from the reader
}
}
param1.Dispose();
}
//If this line is commented, there will be a connection left open, with InActive status
//OracleConnection.ClearPool(oracle);
}
password.Dispose();
return myData;
And this is an image to show the opened connection through Toad.
Of course, for each click to that button, the code above will execute and a new session will remain open, until what you see in the image.
The name "TheTesterOfAllTests.exe" is the Windows Forms app.
Is this a configuration problem?
Is there any way to solve this issue other than using ClearPool method? Because it affects the performance of the app.
P.S. The application that is originally using the code above is a WCF Service that is consumed by a Web application.
P.S. 2 There is some kind of memory leakage, with each click to that button the memory usage increases
I ran into the same problem.
I solved it by changing the initialization of the OracleConnection.
from
var con = new OracleConnection(
"Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=myhost)(PORT=SomePortHere))(CONNECT_DATA=(SERVER=SHARED)(SERVICE_NAME=anotherHost)))",
new OracleCredential(userName,password));
to
var con = new OracleConnection(
"USER ID=myuser;PASSWORD=mypwd;Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=myhost)(PORT=SomePortHere))(CONNECT_DATA=(SERVER=SHARED)(SERVICE_NAME=anotherHost)))");
To me, this different behavior looks like a bug.
As a result, i can no longer use OracleCredential and must store the password as a string. That's okay for me.
remark: SecureString shouldn't be used
It turns out the problem is in the way internally oracle creates connection, since for each newly created OracleConnection object, a new Connection is added to the Connection pool. I counted 91 connection entry in the connection pool.
The solution was to use one OracleConnection instance for each request "Per Request Scope". I implemented that by using a simple generic IDatabase<TConnection> interface with one TConnection GetConnection<TConnection>() method and of course for each method that will be called on that same request's instance, a pair of Open/Close call will take place so we don't keep the connection open the whole time.
Regarding the memory leak, I'm still not able to 100% confirm this, but when I used the Oracle.DataAccess.Client library instead of Oracle.ManagedDataAccess the memory usage reduced dramatically. So, I switched back to Oracle.DataAccess.Client.
P.S. I will update this answer in case of new information regarding these two issues, and contributions are very welcome, maybe I misunderstand something regarding how Oracle deals with the database connection.

how to talk to local databases?

I just added a new "local database" in my project using visual studio. Now I added the "New Data Source".
What I want to know is how you can do sql queries to the DB. I know how this is done in PHP but cant find good information about how to do this in C#. All I find is tutorials on how to drag detail or gridviews into the form.
I have one database called 'words' with three tables. I want to be able to do update queries to a row in each of these tables. something like this:
UPDATE easy SET words='blahblahblah' WHERE id=1;
How do you do this?
I am going to use SQL Server as example.
First you need to find out the connection string which should be similar to
_connectionString = "Data Source=(localdb)\\v11.0; Initial Catalog=words;Integrated Security=true;"
and then you do
using (SqlConnection connection = new SqlConnection(_connectionString))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand("UPDATE easy SET words='blahblahblah' WHERE id=1;", connection))
{
cmd.ExecuteNonQuery();
}
}

C# to MS Access.mdb 2007 ODBC connection "Thread Failed To Start" Error

We are using a c# application (Ranorex) to connect to a Microsoft Access (.mdb) database using an ODBC Connection. During a single run of the code we receive no errors and the connection is made successfully.
Basically the code opens a connection to the DB, retrieves data from the database and then we use the .close method on the database connection when we're done.
However when the code is run continually in a loop after a couple of days the following error is displayed:
"Thread Failed To Start".
This happens at the point the ODBC connection is (attempted) to open.
Does anybody have any suggestions as how to fix this?
Thanks
This is just an example. I cannot answer your question with a direct reference to your code, because, well there is no code to look at. However, the pattern to follow when working with expensive resources like database connections is always the same: Create, Open, Use, Close, Destroy
using(OdbcConnection con = new OdbcConnection(conString))
using(OdbcCommand cmd = new OdbcCommand(commantText, con))
{
OdbcDataAdapter da = new OdbcDataAdapter(cmd);
con.Open();
DataSet ds = new DataSet();
da.Fill(ds, "Table");
dataGridView1.DataSource = ds.Tables[0];
}
The using statement play a fundamental role here. When the code exits from the using block, the command is disposed, the connection is closed and then disposed. Also if you get an Exception in the middle of the using block. It is a very handy replacemente for writing try{....}finally{close/dispose}. Of course I cannot claim that this will resolve your problems, but nevertheless this is the correct first aid to apply to your code.

Connecting a MS Access (.mdb) Database to a MVC3 Web Application

Right, I have been tasked with developing a new application in MVC3 that unfortunately has to integrate very slightly with a classic asp web site. This won't be forever as the old site will get an update at some point, but not yet. In the mean time however the new MVC3 application will need a little bit of access to the database for the old site, which is a old MS Access .mdb whereas the new app will be using sql server 2008.
I would greatly appreciate it if someone could give me some examples of how to connect to the access db, aswell as how to execute sql queries (i am fine writing the sql, just got no idea how to execute against the database from my mvc3 app).
thanks in advance
EDIT: I've not got much experience with the old site, but it appears to use the JET adaptor if that helps! ;-)
Your question requires an answer too extensive to be given in detail
I will give you a check list of things and class to research
Define the connection string used to reach your database [see
here]
Create and open the OleDbConnection
Define your OleDbCommand and the command text to be executed
Create and use an OleDbDataReader to read your data line by line
Create and use an OleDbDataAdapter to read your data and load a
DataSet or DataTable
Now don't forget to close your connection and use parametrized query
string connectionString = Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydatabase.mdb;Jet OLEDB:Database Password=MyDbPassword;
public void InsertRow(string connectionString, string insertSQL)
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
// The insertSQL string contains a SQL statement that
// inserts a new row in the source table.
OleDbCommand command = new OleDbCommand(insertSQL);
// Set the Connection to the new OleDbConnection.
command.Connection = connection;
// Open the connection and execute the insert command.
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// The connection is automatically closed when the
// code exits the using block.
}
}

C# Sync MS Access database to sql server

I am trying to set up a synchronization routine in C# to send data from a ms access database to a sql server. MS Access is not my choice it's just the way it is.
I am able to query the MS Access database and get OleDbDataReader record set. I could potentially read each individual record and insert it onto SQL Server but it seems so wasteful.
Is there a better way to do this. I know I could do it in MS Access linking to sql server and perform the update easy but this is for end users and I don't want them messing with access.
EDIT:
Just looking at SqlBulkCopy I think that may be the answer if I get my results into DataRow[]
I found a solution in .NET that I am very happy with. It allows me to give the access to the sync routine to any user within my program. It involves the SQLBulkCopy class.
private static void BulkCopyAccessToSQLServer
(CommandType commandType, string sql, string destinationTable)
{
using (DataTable dt = new DataTable())
{
using (OleDbConnection conn = new OleDbConnection(Settings.Default.CurriculumConnectionString))
using (OleDbCommand cmd = new OleDbCommand(sql, conn))
using (OleDbDataAdapter adapter = new OleDbDataAdapter(cmd))
{
cmd.CommandType = commandType;
cmd.Connection.Open();
adapter.SelectCommand.CommandTimeout = 240;
adapter.Fill(dt);
adapter.Dispose();
}
using (SqlConnection conn2 = new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString))
{
conn2.Open();
using (SqlBulkCopy copy = new SqlBulkCopy(conn2))
{
copy.DestinationTableName = destinationTable;
copy.BatchSize = 1000;
copy.BulkCopyTimeout = 240;
copy.WriteToServer(dt);
copy.NotifyAfter = 1000;
}
}
}
}
Basically this puts the data from MS Access into a DataTable it then uses the second connection conn2 and the SqlBulkCopy class to send the data from this DataTable to the SQL Server. It's probably not the best code but should give anyone reading this the idea.
You should harness the power of SET based queries over RBAR efforts.
Look into a SSIS solution to synchronize the data and then schedule the package to run at regular intervals using SQL Server Agent.
You can call an SSIS package from the command line so you can effectively do it from MS Access or from C#.
Also, the SQL Server, the MS Access DB and the SSIS package do not have to be on the same machine. As long as your calling program can see the SSIS package, and the package can connect to the SQL Server and the MS Access DB, you can transfer data from one place to another.
It sounds like what you are doing is ETL. There are several tools that are built to do this and to me, there is little reason to reinvent the functionality. You have SQL Server, therefore you have SSIS. It has a ton of tools for automated transformations, cleanups, lookups, etc. that you can use out of the box.
Unless this is a real cut-and-dry data load and there is absolutely no scope for the complexity of the upload to increase later on (yeah, right!) I would go with a tried and tested ETL tool.
If SQL Server Integration Services isn't an option, you could write out to a temporary text file the data that you read from Access and then call bcp.exe to load it to the database.
I have done something like this before.
I used
OleDbConnection aConnection = new OleDbConnection(String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}", fileName));
aConnection.Open();
to open the access db. Then
OleDbCommand aCommand = new OleDbCommand(String.Format("select * from {0}", accessTable), aConnection);
OleDbDataReader aReader = aCommand.ExecuteReader();
to execute the read from the table. Then
int fieldCount = aReader.FieldCount;
to get the field count
while (aReader.Read())
to loop the records and
object[] values = new object[fieldCount];
aReader.GetValues(values);
to retrieve the values.
There are several ways to sync but it can give a problem when you change a field name in sql server or add a new column or delete. The best option would be:
Create connections for sql server and oledb.
Write custom query to fetch record from one connection and save it to another.
Before executing make sure to program in a way that you update all table definitions.
In my case this helped in a way because the load on sql server became down.
can you not transfer Access file to the server and delete it once sync is complete?
You can create windows service for that..

Categories

Resources