Config that I set connectionstring to:
<connectionStrings>
<add name="default" connectionString="data source=database\data.db;" providerName="System.Data.SQLite" />
</connectionStrings>
But in myDbContext I change my database location to :
base.Database.Connection.ConnectionString = #"data source=" + AppVariable.myPath + #"database\data.db;";
After that when my app launch my tables are not created, where is the problem?
extract from my code with nuget package...no need of connection string and datasource...
using SQLite;
public string SQLitePath => Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "xxxxx.sqlite");
try
{
using (var db = new SQLiteConnection(SQLitePath) { Trace = IsDebug })
{
List<TargetModel> test = db.Table<TargetModel>().Select(p => p).ToList();
return test;
}
}
catch (Exception ex)
{
BusinessLogger.Manage(ex);
return null;
}
Related
I have a ConnectionString and I want to pass it values (DataSource, Database, User ID, Password) with values from a .txt file and I need to read them, then pass them to the connectionString but I'm very confused how should I do this.
In my program I have a Helper Class to return the connectionString
public static class Helper
{
public static string ConnectionString(string name)
{
return ConfigurationManager.ConnectionStrings[name].ConnectionString;
}
}
This is how I call the connectionString so I can access the database data
using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(Helper.ConnectionString("Hotel")))
{
connection.Execute($"INSERT INTO dbo.Registos_Cancelados(Nome, Telemovel, Data) VALUES(#Nome, #Telemovel, #Data)", new { Nome = nome, Telemovel = telemovel, Data = data });
}
I have a text file with the values
"DataSourceName"
"DataBaseName"
"User IDName"
"PasswordName"
And I want them in the connection string.
<connectionStrings>
<add name="Hotel" connectionString="DataSource="DataSourceName";Database="DatabaseName";User Id="UserIdName";Password="PasswordName""
providerName="System.Data.SqlClient" />
</connectionStrings>
You're using SqlClient, so: your best bet here is SqlConnectionStringBuilder:
var cb = new SqlConnectionStringBuilder(theBaseString);
cb.DataSource = dataSourceName;
cb.InitialCatalog = dataBaseName;
cb.UserID = userId;
cb.Password = password;
var connectionString = cb.ConnectionString;
If you don't have a template string (theBaseString), just use new SqlConnectionStringBuilder() instead.
The advantage of using SqlConnectionStringBuilder here is that it knows all about the escaping rules for non-trivial values, reserved characters, etc.
You can format your connection string like below to pass the necessary values like dbname later.
<connectionStrings>
<add name="Hotel" connectionString="DataSource={0};Database={1};User Id={2};Password={3}"
providerName="System.Data.SqlClient" />
</connectionStrings>
After that in your Helper class, return the formatted connection string with the values that you read from txt file.
public static string ConnectionString(string name)
{
var dataSourceName = "...";
var dbName = "...";
var userId = "...";
var password = "...";
var connectionString = ConfigurationManager.ConnectionStrings[name].ConnectionString;
return string.Format(connectionString, dataSourceName, dbName, userId, password);
}
I am getting the following error when I debug my setupConnections method
public string SetupConnections(SourceDatabases database)
{
EntityConnectionStringBuilder efBuilder = new EntityConnectionStringBuilder();
try
{
string metaData = #"res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl";
string initialcatalog = "";
const string appName = "EntityFramework";
const string providerName = "System.Data.EntityClient";
if (database == SourceDatabases.COASTALCAROLINAPODIATRY)
{
initialcatalog = "COASTALCAROLINAPODIATRY";
}
if (database == SourceDatabases.COASTALVISIONCARE)
{
initialcatalog = "COASTALVISIONCARE";
}
if (database == SourceDatabases.ELEANORSAHN)
{
initialcatalog = "ELEANORSAHN";
}
if (database == SourceDatabases.GLAUCOMACONSULTANTS)
{
initialcatalog = "COASTALCAROLINAPODIATRY";
}
if (database == SourceDatabases.MARIANNEROSEN)
{
initialcatalog = "COASTALCAROLINAPODIATRY";
}
const string dataSource = "sourcenet";
SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
sqlBuilder.DataSource = dataSource;
sqlBuilder.InitialCatalog = initialcatalog;
sqlBuilder.MultipleActiveResultSets = true;
sqlBuilder.IntegratedSecurity = false;
sqlBuilder.UserID = "scheduler";
sqlBuilder.Password = "BORG8472";
sqlBuilder.ApplicationName = appName;
efBuilder.Metadata = metaData;
efBuilder.Provider = providerName;
efBuilder.ProviderConnectionString = sqlBuilder.ConnectionString;
}
catch(Exception EX)
{
}
return efBuilder.ConnectionString;
}
It claims the following that is not installed but I have had no issues using ef through out my project is this another nuget i need
The ADO.NET provider with invariant name 'System.Data.EntityClient' is
either not registered in the machine or application config file, or
could not be loaded. See the inner exception for details.
Inner: Unable to find the requested .Net Framework Data Provider. It may not
be installed.
My Providers Simply have the following in my app.config
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
You can see from below I have it installed this is bugging the hell out of me it only complains when i switch connections using the below method?.
I am fetching my Database object in PetaPoco using this method:
internal static Database GetCurrentDatabase()
{
if (HttpContext.Current == null)
{
if (Thread.GetData(Thread.GetNamedDataSlot(_databaseKey)) != null)
return Thread.GetData(Thread.GetNamedDataSlot(_databaseKey)) as Database;
else
{
var database = new Database("testDB");
database.KeepConnectionAlive = true;
database.EnableAutoSelect = true;
database.CommandTimeout = 180;
Thread.SetData(Thread.GetNamedDataSlot(_databaseKey), database);
return database;
}
}
else
{
if (HttpContext.Current.Items.Contains(_databaseKey))
return HttpContext.Current.Items[_databaseKey] as Database;
else
{
Database database = new Database("testDB");
database.EnableAutoSelect = true;
database.CommandTimeout = 180;
database.KeepConnectionAlive = true;
HttpContext.Current.Items[_databaseKey] = database;
return database;
}
}
}
My connection string in web.config:
<add name="testDB" connectionString="Data Source=192.168.10.10;Initial Catalog=testDB;User Id=test;Password=test;pooling='true'; Max Pool Size=200"
providerName="System.Data.SqlClient" />
Question is already connection pooling is enabled. Do I have to set KeepConnectionAlive as true or false? What is the use of this property?
Yes, pooling is already enable and you don't need to set KeepConnectionAlive to true (in fact, it will bring trouble if you set it to true)
I have 3 different folders in TFS : tables, scripts and objects.
I Want to loop through three folders to get the file contents and execute them in the SQL server in the order tables, scripts and objects using C#. Want to make it configuration based.
Can anybody help me out with this?
Code:
class Program
{
public void DownloadFiles()
{
string teamProjectCollectionUrl = "";
string serverPath = ConfigurationManager.AppSettings["key2"];
string localPath = ConfigurationManager.AppSettings["key1"];
TfsTeamProjectCollection teamProjectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(teamProjectCollectionUrl));
VersionControlServer versionControlServer = teamProjectCollection.GetService<VersionControlServer>();
foreach (Item item in versionControlServer.GetItems(serverPath, VersionSpec.Latest, RecursionType.Full, DeletedState.NonDeleted, ItemType.File, true).Items)
{
string target = Path.Combine(localPath, item.ServerItem.Substring(2));
if (item.ItemType == ItemType.Folder && !Directory.Exists(target))
{
Directory.CreateDirectory(target);
Console.WriteLine("Created the target folder");
}
else if (item.ItemType == ItemType.File)
{
item.DownloadFile(target);
}
}
Console.WriteLine("Downloaded files from TFS");
ExecuteFiles();
}
public void ExecuteFiles()
{
var connectionString = ConfigurationManager.ConnectionStrings["Conn1"].ToString();
using (SqlConnection conn = new SqlConnection(connectionString))
{
foreach (string file in Directory.GetFiles(ConfigurationManager.AppSettings["key1"], "*.sql", SearchOption.AllDirectories))
{
string contents = File.ReadAllText(file);
Console.WriteLine(file);
Console.WriteLine(contents);
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = contents;
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
}
static void Main(string[] args)
{
Program obj = new Program();
obj.DownloadFiles();
Console.ReadLine();
}
}
Config File:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="key1" value="C:\downloads"/>
<add key="key2" value="$/App1/Application"/>
</appSettings>
<connectionStrings>
<add name="Conn1" connectionString="Data Source=Server_Name;Initial Catalog=db_Name;Integrated Security=True"/>
</connectionStrings>
</configuration>
I have class application that uses ado.net to connect to Sqlite database. The application uses the db to store some data and the db may be changed at run time. The user may make backups of the db and change the location, but in this case i need to know how to change the connection string.
I have tried this code but it didn't work:
string conn =
#"metadata=res://*/KzDm.csdl|res://*/KzDm.ssdl|res://*/KzDm.msl;" +
#"provider=System.Data.SQLite;" +
#"provider connection string=" +
#""" +#"Data Source=" +
#"F:\My Own programs\KrarZara2\KZ\KZ\Kzdb.s3db" +
#""";
Entities ent = new
Entities(conn);
this error "Keyword not supported: 'data source'."
happen at this line
public Entities(string connectionString) : base(connectionString, "Entities")
i write that and it worked with me
EntityConnectionStringBuilder conn = new EntityConnectionStringBuilder();
conn.Metadata = #"res://*/KzDm.csdl|res://*/KzDm.ssdl|res://*/KzDm.msl";
conn.Provider = "System.Data.SQLite";
conn.ProviderConnectionString = #"data source=F:\My Own programs\KrarZara2\KZ\KZ\KrarDS.krar;Version=3;";
EntityConnection entity = new EntityConnection(conn.ConnectionString);
using (DmEnt ent = new DmEnt(entity))
{
var parcel = ent.Parcels.SingleOrDefault(d => d.id == 1);
var pparcc = ent.Parcels.Select(d => d.id == 2);
Parcel r = new Parcel();
r.ParcelNumber = "11ju";
r.Area = 8787;
ent.AddToParcels(r);
ent.SaveChanges();
}
Dm ent is the entity model in edmx ado.net
wrong line order, should be:
#""" +
#"Data Source=" +
I'd actually surprised that connection string works at all. In addition, it would be simpler to use string.Format to build this connection string:
var filename = #"F:\My Own programs\KrarZara2\KZ\KZ\Kzdb.s3db";
var connString = string.Format("Data Source={0};UseUTF16Encoding=True;", filename );
using( var conn = new SQLiteConnection( connString ) )
{
...
}
First, you would replace UseUTF16Encoding with the proper value for your setup. Second, note that the file path in the connection string is not surrounded by quotation marks.
If you are looking for a means to swap Sqlite data files at runtime you might look at this blog entry:
SQLite and Entity Framework 4
A summary of the solution is to parse the Entity framework connection string, change the data file and then reset it:
public static string RedirectedEntityFrameworkConnectionString(string originalConnectionString, string databaseFile, string password)
{
// Parse the Entity Framework connection string.
var connectionStringBuilder = new EntityConnectionStringBuilder(originalConnectionString);
if (connectionStringBuilder.Provider != "System.Data.SQLite")
{
throw new ArgumentException("Entity Framework connection string does not use System.Data.SQLite provider.");
}
// Parse the underlying provider (SQLite) connection string.
var providerConnectionStringBuilder = new SQLiteConnectionStringBuilder(connectionStringBuilder.ProviderConnectionString);
// Redirect to the specified database file, and apply encryption.
providerConnectionStringBuilder.DataSource = databaseFile;
providerConnectionStringBuilder.Password = password;
// Rebuild the Entity Framework connection string.
connectionStringBuilder.ProviderConnectionString = providerConnectionStringBuilder.ConnectionString;
return connectionStringBuilder.ConnectionString;
}
To use, you would do something like:
const string OriginalConnectionString = "..."; // (Copy out of app.config)
var connectionString = RedirectedEntityFrameworkConnectionString(OriginalConnectionString, myFileName, null);
using (var context = new MyEntities(connectionString))
{
...
}