Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Any one help me to create a database in MySQL only on the first run of my c# application. Second time when i run this application if database exists then creation of database code should be skipped.
If you use code first in the Entity Framework you can create your database from the classes in C# that define you tables and relationships.
Once you have your classes you just have to change or setup a connection string to your database and then run code... then the database will be created for you... by magic .. or your classes!!
There are many samples online
Code First with Azure
http://www.dotnetjalps.com/2015/04/entity-framework-code-first--mysql-azure.html
Entity Framework Code First - Create Database with MySql?
private static bool CheckDatabaseExists(SqlConnection tmpConn, string databaseName)
{
string sqlCreateDBQuery;
bool result = false;
try
{
tmpConn = new SqlConnection("server=(local)\\SQLEXPRESS;Trusted_Connection=yes");
sqlCreateDBQuery = string.Format("SELECT database_id FROM sys.databases WHERE Name
= '{0}'", databaseName);
using (tmpConn)
{
using (SqlCommand sqlCmd = new SqlCommand(sqlCreateDBQuery, tmpConn))
{
tmpConn.Open();
object resultObj = ExecuteScalar();
int databaseID = 0;
if (resultObj != null)
{
int.TryParse(resultObj.ToString(), out databaseID);
}
tmpConn.Close();
result = (databaseID > 0);
}
}
}
catch (Exception ex)
{
result = false;
}
return result;
}
This will work with any database name you pass in as a parameter, and it will return a bool true = database exists, false = database does not exist (or error happened).If true mean skip the creation false mean create database..
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I want to get blocked file extension and maximum file size for attachment set by admin in c# code .Below image displays what I actually want using c# code.
Please suggest me answer.
Please use the following code to get any property in the System Settings.
var query = new QueryExpression("organization")
{
ColumnSet = new ColumnSet("blockedattachments", "maxuploadfilesize")
};
EntityCollection orgCollection = _service.RetrieveMultiple(query);
if (orgCollection.Entities.Count > 0)
{
Entity org = orgCollection.Entities.First();
string blockedattachments = org.GetAttributeValue<string>("blockedattachments");
int numberMaxUploadFileSize = org.GetAttributeValue<int>("maxuploadfilesize");
}
Try using below code, it is tested and working fine.
var query = new QueryExpression("organization")
{
ColumnSet = new ColumnSet("blockedattachments", "maxuploadfilesize")
};
var record = service.RetrieveMultiple(query).Entities.FirstOrDefault();
if (record != null)
{
var blockedAttachments = record.GetAttributeValue<string>("blockedattachments");
var maxAttachmentSize = record.GetAttributeValue<int>("maxuploadfilesize");
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a csv file and I need to update data in only a few columns in my sql database table. What is the best way to do this? I was thinking bulk import however, it will not let me do this without using all of the columns. I was thinking of using format file, but I wanted to know if this is the most efficient way.
Here is how I was trying it from my C# class:
/// <summary>
/// Update all of the PropertyDefinitions
/// </summary>
internal static void InsertPropertyDefinitions()
{
//
// Define the connection
//
SqlConnection insertConnection = null;
try
{
RetryStrategy retryStrategy = new Incremental(5, TimeSpan.FromMilliseconds(500), TimeSpan.FromMilliseconds(3000));
RetryPolicy retryPolicy = new RetryPolicy<SqlDatabaseTransientErrorDetectionStrategy>(retryStrategy);
retryPolicy.ExecuteAction(() =>
{
//
// Try to connect to the database
//
using (insertConnection = new SqlConnection(m_ConnectionString))
{
//
// Open the connection
//
insertConnection.Open();
//
// Get the insert command ready
//
using (SqlCommand insertRecordCmd = insertConnection.CreateCommand())
{
//
// Define the Insert command
//
insertRecordCmd.CommandText = #"
BULK INSERT dbo.[PropertyDefinition]
FROM '//my file path'
WITH(
FIRSTROW = 2,
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
)
";
// Execute the INSERT command
insertRecordCmd.ExecuteNonQuery();
}
insertConnection.Close();
}
});
}
catch (Exception ex)
{
//
// This is unexpected so display full exception information
//
m_Log.WriteLine("Exception while creating table");
m_Log.WriteLine(ex.Message.ToString());
throw;
}
}
A recommendation would be to put the csv data into memory and filter out the columns you don't want.
The following SO article has an example of how to populate a DataTable from a CSV and use SqlBulkCopy to bulk insert into SQL Server. You can modify the code to filter out the columns you don't want.
Upload CSV file to SQL server
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I want to create a new database using c#. I just want to pass database name from user interface and for that database name i want to run a sql script of database for creating the same schema of that script for new database.
I do not have exactly whay you intend to do, but I have done some functionality to seed some default data to the master tables.
//sql file location
private static readonly string IndexScriptSeedMasterDataLocation = "SqlSeedMasterData.sql";
In the function I have :
private static void SeedMasterData ( IpDataContext context, string databaseName)
{
context.Database.CreateIfNotExists();
var sqlContent = Content(IndexScriptSeedMasterDataLocation);
var modifiedSqlScript = sqlContent.Replace("#DatabaseName", databaseName);
context.Database.ExecuteSqlCommand(modifiedSqlScript);
}
// Content function :
private static string Content(string fileLocation)
{
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(fileLocation))
{
if (stream == null)
{
return string.Empty;
}
var streamReader = new StreamReader(stream);
return streamReader.ReadToEnd();
}
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
Im trying to create a form that allows users to edit a value in the database. My code below runs without error however
This is the calling method
private void BTNSavePool_Click(object sender, EventArgs e)
{
RWCStatTracker.Database.CLSDB.EditPool(TXTEditPool.Text, CMBBXSearchPool.SelectedItem.ToString());
CMBBXSearchPool.Text = "Please select a Pool....";
MessageBox.Show("Pool edited", "Alert");
this.FRMEditPool_Load(this, null);
PNLEditPoolSearch.Show();
}
This is the code in my database connection class
public static void EditPool(String OldName, String NewName)
{
string UPDTStmt = "UPDATE TBL_Pool SET Name = #NewName WHERE Name = #OldName";
SqlConnection conn = GetConnection();
SqlCommand UPDTCmd = new SqlCommand(UPDTStmt, conn);
UPDTCmd.Parameters.AddWithValue("#NewName", NewName);
UPDTCmd.Parameters.AddWithValue("#OldName", OldName);
try { conn.Open(); UPDTCmd.ExecuteNonQuery(); }
catch (SqlException ex) { throw ex; }
finally { conn.Close(); }
}
Any ideas why it's not updating?
Most likely the WHERE clause isn't selecting any records.
It may have spaces: "Smith " will not match "Smith" or it may be case sensitive: "Smith" will not match "smith".
Check the data to see if it has spaces and string trim your parameters.
I've just figured out the issue with it, the arguments are in the wrong order
This
public static void EditPool(String OldName, String NewName)
Should be
public static void EditPool(String NewName, String OldName)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I've got an application that's an extension for another application. The primary application has a context which provides a connection string. In the past, I've setup entity framework and the first step is to set to connection string.
In this case, I can't set the connection string because I don't have it until runtime. Can I still use Entity Framework? If so, how do I set it up?
Absolutely:
SqlConnection dbConn = new SqlConnection("your_connection_string");
EntityConnection entityConnection = new EntityConnection(dbConn);
var yourEdmx = new DbModel(entityConnection);
Use EntityConnectionStringBuilder Class.
EntityConnectionStringBuilder entityBuilder =
new EntityConnectionStringBuilder();
entityBuilder.Provider = providerName;
entityBuilder.ProviderConnectionString = providerString;
Yes, you can specify a connection when creating the Context.
You can also set the context database default connection factory after the fact:
dbContext.Database.DefaultConnectionFactory = someConnectionString;
Simple method:
var DB = new Your_Entities();
DB.Database.Connection.ConnectionString = "Your_Connection_String";
I had this problem with a project... everything is fine, all wonders... When you run the application in you computer, how do you adapt the database connection to the different users?
I did everything here and other many post similar to this, and nothing seams to work... Yes, the code works, the data context catch the new info for the connection, but it simply DON'T WORK... :'(
I found a lifesaver example that solve my problems, it's a bunch of code but, DBCon has the information of the new connection:
Encripter enc = new Encripter();
string strconfig = u.readFile(u.ubicacionActual() + "\\conn.config");
DBCon dbcon = JsonConvert.DeserializeObject<DBCon>(enc.decrypt(strconfig));
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
EntityConnectionStringBuilder efb = new EntityConnectionStringBuilder(config.ConnectionStrings.ConnectionStrings["ProyectEntities"].ConnectionString);
SqlConnectionStringBuilder sqb = new SqlConnectionStringBuilder(efb.ProviderConnectionString);
// Now we can set the datasource
sqb.DataSource = dbcon.datasource;
sqb.InitialCatalog = dbcon.catalog;
sqb.UserID = dbcon.user;
sqb.Password = dbcon.password;
efb.ProviderConnectionString = sqb.ConnectionString;
// to rewrite the app.config!
ChangeEFConnectionString("ProyectEntities", efb.ProviderConnectionString);
ProyectEntities db = new ProyectEntities(); // dbcontext
The magic function (Well it's not really magic! Just overwrite the app.config)
private bool ChangeEFConnectionString(string connStringName, string newValue)
{
try
{
//CreateXDocument and load configuration file
XDocument doc = XDocument.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
//Find all connection strings
var query1 = from p in doc.Descendants("connectionStrings").Descendants()
select p;
//Go through each connection string elements find atribute specified by argument and replace its value with newVAlue
foreach (var child in query1)
{
foreach (var atr in child.Attributes())
{
if (atr.Name.LocalName == "name" && atr.Value == connStringName)
{
if (atr.NextAttribute != null && atr.NextAttribute.Name == "connectionString")
{
// Create the EF connection string from existing
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder(atr.NextAttribute.Value);
//
entityBuilder.ProviderConnectionString = newValue;
//back the modified connection string to the configuration file
atr.NextAttribute.Value = entityBuilder.ToString();
}
}
}
}
doc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return false;
}
}
All credits to a Bahrudin Hrnjica