How to create an EntityConnection - c#

I have a Solution with multiple projects.
One project is my DataAccess project with 2 SQL CE databases defined, one for local users and one for company data, both with similar table structures. Public, static, readonly strings are defined for each database, and connections can be made.
Another project is my WPF project that will (eventually) display my data. To display data here, I have tried creating an Entity Context object, but nothing seems to work.
What is preventing me from accessing my data in the other project? (Currently, error states 'data source' is not defined)
How do I fix it?
AbcEntities abcContext;
public MainWindow() {
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e) {
try {
EntityConnection ec = new EntityConnection(DataClass.AbcConnectionString);
abcContext= new AbcEntities(ec);
listbox1.ItemsSource = from c in abcContext.Customers select c;
abcCustomersBox.DisplayMemberPath = "Name";
} catch (Exception err) {
MessageBox.Show(err.Message);
}
}

For others, I found out how to do this.
In my static DataClass, I created the following routine to generate the Entity Connection String for me:
static string BuildEntityConnString(string dbFileName, string resourceData, string password) {
string resAll = #"res://*/";
string dataSource = #"Data Source=|DataDirectory|\" + dbFileName;
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
entityBuilder.Metadata = string.Format("{0}{1}.csdl|{0}{1}.ssdl|{0}{1}.msl", resAll, resourceData);
entityBuilder.Provider = "System.Data.SqlServerCe.3.5";
if (String.IsNullOrEmpty(password)) {
entityBuilder.ProviderConnectionString = dataSource;
} else {
entityBuilder.ProviderConnectionString = dataSource + ";Password=" + password;
}
using (EntityConnection con = new EntityConnection()) {
try {
con.ConnectionString = entityBuilder.ToString();
con.Open();
Console.WriteLine("{0} Entity String created.", dbFileName);
con.Close();
return con.ConnectionString;
} catch (Exception err) {
Console.WriteLine(err);
}
}
return null;
}
Notice that if there is any error, a NULL String is returned.
If anyone wants to use this, they should either place a breakpoint at the Exception, throw it, or handle it in some way. The Console.WriteLine() was just for me to debug through this.
I created Entity Connection Strings for my applications as follows:
public static readonly string EntityConnString =
BuildEntityConnString("sqlCeDb.sdf", "myModel", "abc123~Funky");
Hope others get some mileage out of this.

Explanation (more of an example, really) of how to create an EntityConnection can be found on MSDN here:
http://msdn.microsoft.com/en-us/library/bb738533.aspx
Looks pretty similar to what you have.

Related

How to fix “Invalid operation on a closed object” exception when trying to Read an OracleDataReader

I'm creating a web API using .Net Core and the Oracle.ManagedDataAccess.Core plugin that accesses an Oracle database to retrieve a Blob field and return it as a byte array. I created a function (getBlobfromDB) that gets the Oracle connection string from an encrypted field on a SQL database, connects and uses an OraleDataReader to retrieve and return the Blob field. But when the OraleDataReader tries to Read the record, I'm getting this exception: "Invalid operation on a closed object".
When you search for this issue, the most relevant answer is this post
However, I'm 100% percent sure that user on the conn string has access since that is the schema owner, and I also tried adding the schema owner to the Select query (SELECT FIELD FROM SCHEMA_OWNER.TABLE WHERE ID = "") getting the same error
So I tried two other things, getting a different VARCHAR field from another table on the same database, still getting the same error; and trying on a different Oracle database and I was able to successfully retrieve the data. I noticed that the Oracle versions on the servers are different, 12.2 for the working one and 11.2 for the non-working, this may be the reason? I don't know what else I can do or try, I'll appreciate any help/advice that you can give me
This is the simplified function
private OracleBlob getBlobfromDB(string sSystem, string sID)
{
string sSQL = String.Empty;
string connString = String.Empty;
OracleConnection oConn = new OracleConnection();
if (string.IsNullOrWhiteSpace(sID) || string.IsNullOrWhiteSpace(sSystem) )
{
return null;
}
sSQL = "SELECT BLOB_FIELD FROM TABLE WHERE ID = " + sID;
connString = getConnectionString(sSystem);
try
{
using (oConn = new OracleConnection(connString))
{
oConn.Open();
OracleCommand oCom = new OracleCommand(sSQL, oConn);
OracleDataReader oDr = oCom.ExecuteReader();
if (oDr.HasRows)
{
//I'm able to reach to this point before getting the exception
oDr.Read();
OracleBlob blob = oDr.GetOracleBlob(0);
// Clean up
oDr.Close();
oDr.Dispose();
oCom.Dispose();
return blob;
}
else
{
// Clean up
oDr.Close();
oDr.Dispose();
oCom.Dispose();
return null;
}
}
}
catch (Exception x)
{
return null;
}
finally
{
oConn.Close();
}
}
With the Oracle.ManagedDataAccess dependency you should not Close() the connection and do not use the using clause. It seems that the dependency itself closes the connection at will.
Remove: using(){} keyword and oConn.Close() from your code.

System.InvalidOperationException: 'The ConnectionString property has not been initialized.'

I am trying to fill list boxes with elements and been doing everything by a clean guide but I am getting connection string error when I am trying to run it.
Clearly i have done something foolish and can't understand it so a deeper explanation would be appreciated
The error
The ConnectionString property has not been initialized.
The Code
public partial class FormMain : Form
{
SqlConnection connection;
string connectionString;
public FormMain()
{
InitializeComponent();
connectionString = ConfigurationManager.ConnectionStrings["NaujasAutoSalonas.Properties.Settings.AutoSalonasConnectionString"].ConnectionString;
}
private void FormMain_Load(object sender, EventArgs e)
{
PopulateAutoKlases();
}
private void PopulateAutoKlases()
{
using (connection = new SqlConnection(connectionString));
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM AutoKlases", connection))
{
DataTable KlasesTable = new DataTable();
adapter.Fill(KlasesTable);
lstKlases.DisplayMember = "KlasesPavadinimas";
lstKlases.ValueMember = "KlasesID";
lstKlases.DataSource = KlasesTable;
}
}
}
As you have stated that the connection string property is not initialized,so I guess that your applications is not able to read the connection string from the config file.You can confirm this by putting a breakpoint in the constructor of FormMain class.
If the connection string is not being set in the constructor then you need to identify whether you have declared the connection string properly in your config file.As there could be few config files ,so it is important that you declare your connection string in the correct config file.
Or if you are defining properties for your connection string in the .settings file,you can validate if you are accessing it correctly.

can't find the logical error in c# asp.net below

I wrote this code to get data from mysql database using odbc connection. Its giving no error but no output as well. Am not able to find what the matter is.
public partial class Members : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable table = new DataTable();
string conString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
try
{
using (OdbcConnection con = new OdbcConnection(conString))
{
con.Open();
// We are now connected. Now we can use OdbcCommand objects
// to actually accomplish things.
using (OdbcCommand com = new OdbcCommand("SELECT * FROM abc", con))
{
using (OdbcDataAdapter ad = new OdbcDataAdapter(com))
{
ad.Fill(table);
}
}
con.Close();
}
}
catch (Exception ei)
{
Label1.Text = ei.Message;
}
GridView1.DataSource=table;
GridView1.DataBind();
}
}
In web.config do you have a connectionString? Please check that.
If not you can add datasource from visual studio designer and it will ask to add connection string in one of the steps .At the end you can remove datasource from designer but still have connectionstring in web.config file .And in your code behind can you try this
string SQL_CONNECTION_STRING = System.Configuration.ConfigurationManager.ConnectionStrings["SqlConnectionTest"].ConnectionString;
where "SqlConnectionTest" is the name of connection string in web.config.
The problem was that I converted a vb project just by replacing the c# file with the vb ones to make it a c# project, and this created this whole mess.The code work perfectly fine when done on a new projects.

How to handle the connection string in an external dll?

If i have a dll which i use in many web applications to use methods in this dll in my applications.
What 's the best practice to handle the connection string ?
The dll methods are static methods ..
this is what i do
private static String connectionString = "User Id=xxx;Password=xxx;Host=xxx;Server=xxx;Service=1525;Database=xxx; Client Locale=ar_ae.1256; Database Locale=ar_ae.8859-6; Protocol=olsoctcp;pooling=true;Min Pool Size=4;Max Pool Size=400;Connection Timeout=30";
public static int Is_Valid_User(string p_u, string p_p)
{
int ret = 0; // invalid user
using (IfxConnection conn = new IfxConnection(connectionString))
{
IfxCommand DBCmd = new IfxCommand();
String p = My_Decryption_2(p_p);
try
{
if (conn.State == ConnectionState.Closed)
conn.Open();
DBCmd = new IfxCommand();
DBCmd.Connection = conn;
DBCmd.CommandText = "SELECT nvl(emp_num,0) FROM emp_net WHERE username = ? AND DECRYPT_CHAR(password, 'xxxxxx') = ? ";
DBCmd.Parameters.Add("user_name", p_u);
DBCmd.Parameters.Add("password", p);
using (IfxDataReader dataReader = DBCmd.ExecuteReader())
{
if (dataReader.Read())
ret = (int)dataReader[0];
dataReader.Close();
}
}
catch (ApplicationException e)
{
}
conn.Close();
}
return ret;
}
Is this a good way to use a dll in my web application ?or there 's a way better than this ?
You have pretty much shot yourself in the foot with those static methods.
Best practise is probably to refactor the class to use instance methods and inject the connection string through the constructor or properties.
Failing that you can refactor the static methods to include the connection string?
public static int Is_Valid_User(string p_u, string p_p, string connectionString)
You can hard code a reference to the [web|app]config connection string too, but that has only changed the problem (the dependency on a fixed string), not solved it.
Its better to have connection string in some sort of configuration like web.config.

c# - entity framework with SqlServerCe.3.5 - Connection exception

i have problem with entity framework with SqlServerCe.3.5 connection.
i have small project called Assets with .SDF database and entity(the model name is Main).
now,when i'm trying to connect to the entity happend something weird.
in the first time everything works fine but now i had must to added this:
if (edmConnection.State != ConnectionState.Open)
{
edmConnection.Open();
}
because the connection to the entity all time was closed.
after i added this lines,i can reach to the database and the entity,but i got this message:
The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.
this is the stack Trace:
at System.Data.EntityClient.EntityConnection.ChangeConnectionString(String newConnectionString)
at System.Data.EntityClient.EntityConnection..ctor(String connectionString)
at System.Data.Objects.ObjectContext.CreateEntityConnection(String connectionString)
at System.Data.Objects.ObjectContext..ctor(String connectionString, String defaultContainerName)
at BL.Model.DBEntities..ctor() in C:\Users\Orel\Documents\Visual Studio 2010\Projects\Assets\BL\Model\Main.Designer.cs:line 34
at BL.Handlers.mModelHandler..ctor()
at BL.Handlers.mModelHandler.GetOnlyInstance() in C:\Users\Orel\Documents\Visual Studio 2010\Projects\Assets\BL\Handlers\mModelHandler.cs:line 30
this is my code and the app.config:
private static mModelHandler _mInstance = null;
public static DBEntities m_context = null;
public static mModelHandler GetOnlyInstance()
{
if (_mInstance == null)
{
try
{
m_context = new DBEntities(GetConnectionString());
_mInstance = new mModelHandler();
}
catch (Exception)
{
throw;
}
}
return _mInstance;
}
public static EntityConnection GetConnectionString()
{
try
{
var filePath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
if (filePath == null) throw new ArgumentNullException("filePath");
if (filePath.EndsWith("\\Assets\\bin\\Debug"))
{
filePath = filePath.Replace("\\Assets\\bin\\Debug", "\\BL\\DB.sdf");
}
var sqlCeConnectionString = string.Format("Data Source={0}", filePath);
// Create an EDM connection
EntityConnectionStringBuilder entity = new EntityConnectionStringBuilder();
entity.Metadata = "res://*/Model.Main.csdl|res://*/Model.Main.ssdl|res://*/Model.Main.msl";
entity.Provider = "System.Data.SqlServerCe.3.5";
entity.ProviderConnectionString = sqlCeConnectionString;
var edmConnectionString = entity.ToString();
var edmConnection = new EntityConnection(edmConnectionString);
if (edmConnection.State != ConnectionState.Open)
{
edmConnection.Open();
}
return edmConnection;
}
catch (Exception e)
{
throw;
}
}
the app.config:
<add name="DBEntities" connectionString="metadata=res://*/Model.Main.csdl|res://*/Model.Main.ssdl|res://*/Model.Main.msl;provider=System.Data.SqlServerCe.3.5;provider connection string='Data Source=|DataDirectory|\DB.sdf'" providerName="System.Data.EntityClient" />
i read in the fourm that the problem can be that the app.config and the connection string are not match,i tried this also and it dosen't work..
i just added an image of this:
Link
Help!
Orel
I think your connection string isn't being parsed correctly. Try using " in place of the '.
I also believe that, for SqlCE, the provider within the quotes should be provider=System.Data.SqlServerCe,3.5; instead of provider=System.Data.SqlServerCe.3.5;.
Notice the , just before the version 3.5.
Putting it all together, we have:
<add name="DBEntities"
connectionString="metadata=res://*/Model.Main.csdl|res://*/Model.Main.ssdl|res://*/Model.Main.msl;provider=System.Data.SqlServerCe,3.5;provider connection string= "Data Source=|DataDirectory|\DB.sdf""
providerName="System.Data.EntityClient" />
Hope this helps.

Categories