codefirst database is not creating - c#

I am trying to create a Database with entity framework code-first environment.
The tables in database are identity tables.
The problem is with SQL server's database creation. There is no database created When I ran application.
However, I am able to find physical find here at this location -
C:\Users\user\AppData\Local\Microsoft\Microsoft SQL Server Data\SQLEXPRESS\HWAPI.mdf
So whenever I do add any table or change the structure then all the changes are happening in above location and think that this is not using master database.
There is no database created in my local SQL server.
Have a look at my code -
StartUp.cs
public class Startup
{
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
ConfigureOAuth(app);
config.DependencyResolver = new NinjectResolver(NinjectWebCommon.CreateKernel());
WebApiConfig.Register(config);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(config);
}
public void ConfigureOAuth(IAppBuilder app)
{
app.CreatePerOwinContext(OwinAuthDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new AuthorizationServerProvider()
};
}
}
And there is the context -
public class OwinAuthDbContext : IdentityDbContext<ApplicationUser>, IDisposable
{
public OwinAuthDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
Database.SetInitializer<OwinAuthDbContext>(null);
}
public static OwinAuthDbContext Create()
{
return new OwinAuthDbContext();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<IdentityUser>().ToTable("AspNetUsers");
modelBuilder.Entity<IdentityRole>().ToTable("AspNetRoles");
modelBuilder.Entity<IdentityUserClaim>().ToTable("AspNetUserClaims");
modelBuilder.Entity<IdentityUserLogin>().ToTable("AspNetUserLogins");
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
}
web.config
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=HWAPI;Integrated Security=SSPI;Connect Timeout=30;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Please assist and let me know if additional info is required.

Your problem is with the connection string.You need to try as shown below.
If you need to use Localhost then :
<connectionStrings>
<add name="DefaultConnection" connectionString="Server=localhost; Database=HWAPI;Trusted_Connection=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
If you need to use LocalDb then :
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\HWAPI.mdf;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>

Thanks everybody for putting their inputs.
It turns out that I needed to setup credentials for existing database. After I setup credentials security for database then it worked.
before -
<add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=HWAPI;Integrated Security=SSPI;Connect Timeout=30;User Instance=True"
providerName="System.Data.SqlClient" />
after -
<add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=HWAPI;User ID=sa;Password=truw#123" providerName="System.Data.SqlClient"/>
This solved my issue and I was able to connect to database within SQLEXPRESS.

Related

What is the connection String to connect to the SQL Server database in web.config?

What is the connection string in web.config to connect to a SQL Server database using ASP.NET ?
You can find it in node <connectionStrings></<connectionStrings>>
Example:
<connectionStrings>
<add
name="NorthwindConnectionString"
connectionString="Data Source=serverName;Initial
Catalog=Northwind;Persist Security Info=True;User
ID=userName;Password=password"
providerName="System.Data.SqlClient"
/>
</connectionStrings>
And how to read it in code:
System.Configuration.Configuration rootWebConfig =
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/MyWebSiteRoot");
System.Configuration.ConnectionStringSettings connString;
if (rootWebConfig.ConnectionStrings.ConnectionStrings.Count > 0)
{
connString =
rootWebConfig.ConnectionStrings.ConnectionStrings["NorthwindConnectionString"];
if (connString != null)
Console.WriteLine("Northwind connection string = \"{0}\"",
connString.ConnectionString);
else
Console.WriteLine("No Northwind connection string");
}
Update: You need to specify the connection name in your DbContext
public class YourDbContext : DbContext
{
public YourDbContext()
: base("YourConnectionName")
{
}
}
And your web config:
<connectionStrings>
<add name="YourConnectionName"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|DatabaseName.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
Demo
<add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />

read,write and update connectionstring in app.config file at run time in C#

I have created a form for connection settings, where user can update server name, datatbase and user id and password. I have stored my connection string in app.config file.
My problem is, how can I update connection string in app.config file at run time and How can I change the information of the conectionstring through the text box on the form in the first time, the text box will display information of server name, id, password after the first time
here my app.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="Data123.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<connectionStrings>
<add name="Data123Entities" connectionString="metadata=res://*/Data123DB.csdl|res://*/Data123DB.ssdl|res://*/Data123DB.msl;provider=System.Data.SqlClient;provider connection string="data source=nguyenduyhai;initial catalog=Data123;persist security info=True;user id=sa;password=1234567;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
<!--<add name="Data123Entities" connectionString="metadata=res://*/Data123DB.csdl|res://*/Data123DB.ssdl|res://*/Data123DB.msl;provider=System.Data.SqlClient;provider connection string="data source=NGUYENDUYHAI\SQLEXPRESS;initial catalog=Data123;persist security info=True;user id=sa;password=1234567;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />-->
</connectionStrings>
</configuration>
here the code that i am trying but not work , please help me
void saveconect(string address,string id,string pass)
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
connectionStringsSection.ConnectionStrings["Data123Entities"].ConnectionString = "data source=" + address + ";initial catalog=" + "Data123" + ";user id=" + id + ";password=" + pass + "";
config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection("connectionStrings");
}
private void buttonUpdate_Click(object sender, EventArgs e)
{
saveconect(textboxServerAddress.Text, textBoxUserID.Text, textBoxPassword.Text);
}
Have you tried to run application in release folder?
Because in Debug mode won't change.
With using System.Xml.Linq; it will be something like:
var doc = XElement.Load(fileName);
var target = doc.Element("configuration").Elements("configurationStrings").Where(e => e.Element("name").Value == "Data123Entities").Single();
target.Element("connectionString").Value = "metadata=res://*/Data123DB.csdl|res://*/Data123DB.ssdl|res://*/Data123DB.msl;provider=System.Data.SqlClient;provider connection string="data source=" + dataSource + ";initial catalog=" + initCatalog + ";persist security info=True;user id=sa;password=1234567;MultipleActiveResultSets=True;App=EntityFramework""
doc.Save(fileName);

Using MySQL and SQL Server contexts in single Web API request

i have a web application with custom AuthHandler that uses MySQL connection for checking permissions and business logic, that is linked to MS SQL database instance entities
so, the problem happens when the MS SQL Context is creating:
System.ArgumentException
Additional information: Keyword not supported.
at MySql.Data.MySqlClient.MySqlConnectionStringBuilder.GetOption(String key)
at MySql.Data.MySqlClient.MySqlConnectionStringBuilder.set_Item(String keyword, Object value)
at System.Data.Common.DbConnectionStringBuilder.set_ConnectionString(String value)
at MySql.Data.MySqlClient.MySqlConnectionStringBuilder..ctor(String connStr)
at MySql.Data.MySqlClient.MySqlConnection.set_ConnectionString(String value)
at System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.<SetConnectionString>b__18(DbConnection t, DbConnectionPropertyInterceptionContext`1 c)
contexts code:
public SqlServerContext()
:base("SQLServer")
{
this.Configuration.LazyLoadingEnabled = false;
this.Configuration.AutoDetectChangesEnabled = true;
}
public MySqlContext()
:base("MySQL")
{
}
connection strings in config:
<add name="SQLServer"
connectionString="Data Source={};Initial Catalog={};Persist Security Info=True;User ID={};Password={};MultipleActiveResultSets=True"
providerName="System.Data.SqlClient" />
<add name="MySQL" connectionString="Server={};Port=3306;Database=Test;Uid={};Pwd={}" providerName="MySql.Data.MySqlClient" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6" />
</providers>
contexts are now injected with Ninject container:
binder.Bind<DbContext>().ToConstructor(i => new SqlServerContext()).Named(GlobalConstants.Context.ContentCodename);
binder.Bind<DbContext>().ToConstructor(i => new MySqlContext()).Named(GlobalConstants.Context.UserCodename);
for the first, i don't understant, why code is trying to build connection strings with MySql instances. so i've decided to create SQL Server context with implicit connection string:
public SqlServerContext()
: base(a())
{
this.Configuration.LazyLoadingEnabled = false;
this.Configuration.AutoDetectChangesEnabled = true;
}
private static string a()
{
var a = new EntityConnectionStringBuilder
{
Provider = "System.Data.SqlClient",
ProviderConnectionString = new SqlConnectionStringBuilder
{
DataSource = #"{}",
InitialCatalog = "{}",
UserID = "{}",
Password = "{}",
MultipleActiveResultSets = true
}.ConnectionString
}.ConnectionString;
return a;
}
but there are errors something like: provider name keyword is not supported, multiple active results set keyword is not supported - that is characteristically for MySQL behavior. does have anybody solutions for that problem?
MySQL context was marked by attribute:
[DbConfigurationType(typeof (MySqlEFConfiguration))]
that is recommended for MySQL contexts using EF. removing this attribute solving issue

NHibernate. SessionFactory.Delete deletes all tables

I try to run example from https://github.com/jagregory/fluent-nhibernate/wiki/Getting-started but after running next code all tables are cleared. I don't understand why it happens. I expecting that the store var barginBasin = new Store { Name = "Bargin Basin" }; and rows from table StoreProduct with Store_id of this store will be deleted.
using (var session = sessionFactory.OpenSession())
{
session.Delete(session.CreateCriteria(typeof (Store)).List<Store>()[0]);
session.Flush();
}
sessionFactory initialization:
var dbConfig = OracleDataClientConfiguration.Oracle10
.ConnectionString(c => c.FromConnectionStringWithKey("Oracle"))
.Driver<OracleDataClientDriver>()
.ShowSql();
sessionFactory = Fluently.Configure()
.Database(dbConfig)
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<Employee>())
.BuildSessionFactory();
App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<connectionStrings>
<add name="Oracle"
connectionString="DATA SOURCE=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=[IP])(PORT=[PORT]))(CONNECT_DATA=(SERVICE_NAME=XE)));PASSWORD=[PASSWORD];PERSIST SECURITY INFO=True;USER ID=[USER ID]"
providerName="Oracle.DataAccess.Client" />
</connectionStrings>
</configuration>

How can I configure ASP.Net membership providers through code?

We're using ASP.Net membership providers (the SQL Server provider), and I want to be able to set up an Admin user account as part of our installer. To do this, I need the ASP.Net membership provider configured so that my installer can use it - but I don't want to have to set up a config file for the installer.
So is there a way of configuring an ASP.Net membership through code without writing a custom provider?
Ok, following the solution they conjured up here: http://forums.asp.net/p/997608/2209437.aspx
I created a class which, in the parameterless constructor (which you need) just gets the server and port from the command line arguments. Such that I can go "MembershipInitializer.exe "SomeSqlServer\Instance" 51000.
public class CustomSQLMembershipProvider : SqlMembershipProvider {
private readonly string _server;
private readonly string _port;
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Web.Security.SqlMembershipProvider"/> class.
/// </summary>
public CustomSQLMembershipProvider() {
string[] args = System.Environment.GetCommandLineArgs();
// args[0] is the exe name
_server = args[1];
_port = args[2];
}
public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
{
base.Initialize(name, config);
// Update the private connection string field in the base class.
string connectionString = string.Format(#"Data Source={0},{1};Initial Catalog=aspnetdb;UID=NICCAMembership;PWD=_Password1;Application Name=NICCA;Connect Timeout=120;", _server, _port);
// Set private property of Membership provider.
FieldInfo connectionStringField = GetType().BaseType.GetField("_sqlConnectionString", BindingFlags.Instance | BindingFlags.NonPublic);
connectionStringField.SetValue(this, connectionString);
}
}
In the app.config of your console app (or windows app)
<configuration>
<connectionStrings>
<clear/>
<add name="MembershipDB"
connectionString="Some Bogus String here that gets overrided in the custom class"
providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
<authentication mode="Forms"/>
<authorization>
<deny users="?"/>
</authorization>
<membership>
<providers>
<remove name="AspNetSqlMembershipProvider"/>
<add name="AspNetSqlMembershipProvider"
connectionStringName="MembershipDB"
applicationName="NICCA"
type="MyInitializeMembershipDB.CustomSQLMembershipProvider, MyInitializeMembershipDB"
requiresUniqueEmail="false"
requiresQuestionAndAnswer="false"/>
</providers>
</membership>
</system.web>
</configuration>
If you are in need of the role provider bit as well, you probably have to override SqlRoleProvider in much the same way.
If you are creating a program to automatically initialize your membership database to a specific state based but the sql server address and port name aren't known until someone enters them into a install wizard, this will do the trick..
Does this help?
Membership.ApplicationName = "yourfbaApplicationame";
MembershipUser user = Membership.CreateUser("admin,"password","emaiol#g.com");
and Make sure that you have the following entries in the config file.
<connectionStrings>
<add connectionString="server=sqd01-1-cll;database=FBA;Integrated Security=SSPI;" name="FBASqlConnString" providerName="System.Data.SqlClient"/>
If you still wanted to use the complete code and dont need to use the config file. Use the below
SqlMembershipProvider ObjSqlMembershipProvider = new SqlMembershipProvider();
SqlRoleProvider ObjSqlRoleProvider = new SqlRoleProvider();
NameValueCollection ObjNameValueCollRole = new NameValueCollection();
NameValueCollection ObjNameValueCollMembership = new NameValueCollection();
MembershipCreateStatus enMembershipCreateStatus;
ObjNameValueCollMembership.Add("connectionStringName", "Connection String Name");
ObjNameValueCollMembership.Add("applicationName", "ApplicatioNAme");
//these items are assumed to be Default and dont care..Should be given a look later stage.
ObjNameValueCollMembership.Add("enablePasswordRetrieval", "false");
ObjNameValueCollMembership.Add("enablePasswordReset", "false");
ObjNameValueCollMembership.Add("requiresQuestionAndAnswer", "false");
ObjNameValueCollMembership.Add("requiresUniqueEmail", "false");
ObjNameValueCollMembership.Add("passwordFormat", "Hashed");
ObjNameValueCollMembership.Add("maxInvalidPasswordAttempts", "5");
ObjNameValueCollMembership.Add("minRequiredPasswordLength", "1");
ObjNameValueCollMembership.Add("minRequiredNonalphanumericCharacters", "0");
ObjNameValueCollMembership.Add("passwordAttemptWindow", "10");
ObjNameValueCollMembership.Add("passwordStrengthRegularExpression", "");
//hard coded the Provider Name,This function just need one that is present. I tried other names and it throws error. I found this using Reflector ..all the rest are take care by the above
//name value pairs
ObjSqlMembershipProvider.Initialize("AspNetSqlMembershipProvider", ObjNameValueCollMembership);MembershipUser user = ObjSqlMembershipProvider.CreateUser("admin,"password","emaiol#g.com");
One this You need to give the connection string in the Config file no other go. If you want that too to be from the code you need to inherit the class

Categories