ConfigurationManager.Connectionstrings("DBConnection") - Null Exception - asp.net

In data layer I am trying to fetch connection string from app.config.
App.config
<connectionStrings>
<add name="DBConnection" connectionString="Data Source=****;Initial Catalog=****;Persist Security Info=True;User ID=*****; Password=***" />
</connectionStrings>
Fetching Value:
Shared _ConnectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings("DBConnection").ConnectionString
this is not working.
And I tried
Shared _ConnectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings(0).ConnectionString
it is partially fetching - "Data Source=****;Initial Catalog=****;Persist Security Info=True"
Kindly explain.

Try using ConnectionStrings["DBConnection"].ConnectionString instead of ConnectionStrings("DBConnection").ConnectionString.

Related

WebSecurity.InitializeDatabaseConnection Function does not found my connection String

So i get the error that i should call WebSecurity.InitializeDatabaseConnection
before i call any function of the webSecurity Class
So i created _AppStart.cshtml and placed this code in it :
#using System.Configuration;
#{
string connString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
WebSecurity.InitializeDatabaseConnection(connString, "users", "id", "email", autoCreateTables: true);
}
and in Web.Config i got
<appSettings>
<add key="enableSimpleMembership" value="true" />
</appSettings>
<connectionStrings>
<add name="conString" providerName="System.Data.SqlClient"
connectionString="Data Source=(local)\SQLEXPRESS;Initial Catalog=sales;Integrated Security=True;Pooling=False"/>
</connectionStrings>
now i get this error from the InitializeDatabaseConncection method :
Connection string "Data Source=(local)\SQLEXPRESS;Initial Catalog=sales;Integrated Security=True;Pooling=False" was not found.
whats the problem ?
WebSecurity.InitializeDatabaseConnection is not asking you for a connection string. It's asking you for the name of the connection string. It will then retrieve the connection string form the configuration file for you.
WebSecurity.InitializeDatabaseConnection("conString", "users", "id", "email", autoCreateTables: true);
When you have a question about why a method is not behaving as expected, read the documentation! It states for that parameter:
The name of the connection string for the database that contains user information. If you are using SQL Server Compact, this can be the name of the database file (.sdf file) without the .sdf file name extension.

Move ASP.NET Identity store to EF Sql database

By default ASP.NET Identity user data is stored in an mdf file.
I want to store the data in a Sql database so that I changed the defaultconnection string in my web.config to my EF based connection:
<add name="DefaultConnection" connectionString="metadata=res://*/Models.StartifyModel.csdl|res://*/Models.StartifyModel.ssdl|res://*/Models.StartifyModel.msl;provider=System.Data.SqlClient;provider connection string="data source=MYPC\SQLEXPRESS;initial catalog=mydb;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
Now I am getting the error The entity type ApplicationUser is not part of the model for the current context. as soon as I want to register a user.
I use the default MVC5 project template of VS2013.
Please try specify the connection string in the format:
<add name="DefaultConnection" connectionString="Data Source=127.0.0.1, 1433;Initial Catalog=YourDB;User Id=XXXX;Password=XXXXX;Asynchronous Processing=True;Encrypt=False;TrustServerCertificate=True;Persist Security Info=True" providerName="System.Data.SqlClient" />
And then make sure in Models/IdentityModels.cs you have
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}

Mysql syntax error while creating Database for Entity Framework

I'm playing around with asp.net for the first time. I want to use it with a MySQL database because this is what is offered by my hosting service and I don't want to upgrade/change services. I'm using visual web developer 2010 express. I created an MVC 4 project from the default template. The template created the ASP.NET Simple Membership objects which is what I'm trying to get working. The project builds and runs correctly when using the default database connection string. When I change the web.config file to point to MySQL I get the following error when I attempt to navigate to any of the pages in the account folder.
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'IDENTITY,
RoleName nvarc' at line 2
When I open the MySQL work bench and connect to the local server I notice that the database has been created. If I drop the DB and run the app again it gets recreated. I'm note sure if it was created correctly or if the entire database was created but there is something there.
Obviously there is an issue with the SQL syntax that is created by the Entity Framework. Do I need to add something to the web.config file to tell it what syntax it should use when creating the queries?
I've been searching for an answer to this for the past two days. any help pointing in the right direction would be appreciated.
I'm using mysql server version 5.5.27. and connector 6.5.4.0
here is the mysql part of my web.config file:
<system.data>
<DbProviderFactories>
<remove invariant="MySql.Data.MySqlClient"/>
<add name="MySQL Data Provider"
invariant="MySql.Data.MySqlClient"
description=".Net Framework Data Provider for MySQL"
type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.5.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</DbProviderFactories>
</system.data>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=aspnet-MyWebPage-20120817115958;Integrated Security=SSPI" providerName="System.Data.SqlClient" />
<add name="myDatabaseConnection" connectionString="server=localhost;Port=3306;uid=root;pwd=****;database=myDatabase;" providerName="MySql.Data.MySqlClient" />
</connectionStrings>
Edit adding code
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute
{
private static SimpleMembershipInitializer _initializer;
private static object _initializerLock = new object();
private static bool _isInitialized;
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Ensure ASP.NET Simple Membership is initialized only once per app start
LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
}
private class SimpleMembershipInitializer
{
public SimpleMembershipInitializer()
{
Database.SetInitializer<UsersContext>(null);
try
{
using (var context = new UsersContext())
{
if (!context.Database.Exists())
{
// Create the SimpleMembership database without Entity Framework migration schema
((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
}
}
WebSecurity.InitializeDatabaseConnection("LocalMySqlServer", "UserProfile", "UserId", "UserName", autoCreateTables: true);
}
catch (Exception ex)
{
throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
}
}
}
}
public class UsersContext : DbContext
{
public UsersContext()
: base("LocalMySqlServer")
{
}
public DbSet<UserProfile> UserProfiles { get; set; }
}
Try to modify the source of the SMP and remove the syntax specific to ms sql server.
The role provider is still defaulting to the standard ASP one which is expecting a SQLServer DB on the end of the connection, "Identity" is SQLServerese for "autoinc".
You can set the default providers in the web.config like this:-
<configuration>
<system.web>
<profile defaultProvider="MySQLProfileProvider"></profile>
<roleManager defaultProvider="MySQLRoleProvider"></roleManager>
</system.web>
</configuration>

Encrypting only Passwords in web.config ASP.NET

How can I encrypt only passwords in a web.config file?
<add name="PSystem" connectionString="Server=test;Database=Dev;User ID=testuser;Password=password#123;Trusted_Connection=False;Encrypt=True;" providerName="System.Data.SqlClient" />
I believe that built-in encryption mechanisms work on the entire connectionString section:
See this website for more info
If you would like to encrypt in-memory passwords, maybe entered by the user through a login form, you could use SecureString
you can try using flags in the connecction string as follows:
<add name="PSystem"
connectionString="Server=test;
Database=Dev;
User ID=#UserID#;
Password=#Password#;
Trusted_Connection=False;
Encrypt=True;"
providerName="System.Data.SqlClient" />
then you can have the encrypted user and password as follows:
<add key="DB_User" value = [Encrypted Username]>
<add key="DB_Password" value = [Encrypted Password]>
Then in code you just replace the flags:
string _connectionString = ConfigurationManager.ConnectionStrings["PSystem"].ConnectionString;
string user = Decrypt(ConfigurationManager.AppSettings["DB_User"]);
string password = Decrypt(ConfigurationManager.AppSettings["DB_Password"]);
_connectionString = _connectionString.Replace("##User##", user).Replace("##Password##", password);
To encrypt configuration file
contents, use the Aspnet_regiis.exe tool with the –pe option and the
name of the configuration element to be encrypted.
aspnet_regiis -pe "connectionStrings" -app "/SampleApplication" -prov
"RsaProtectedConfigurationProvider"
Source: http://msdn.microsoft.com/en-us/library/zhhddkxy(v=vs.100).aspx

Substituting values into web.config at runtime

We have an application that runs in three environments: development, QA, and production. The application accesses an SQL server and several web services. The web.config file has the connection string for the SQL server and the IP addresses of the web services. We would like to be able to have one web.config file that works in all three environments, but somehow picks up the varying data for each environment. Does anyone know of a way to do this?
Look at Web.config Transformation.
We use the exact same config options as you, and we have created 3 connection strings in our web.config like this:
<connectionStrings>
<add name="Dev" connectionString="Server=localhost;Database=WebDev;User=devo;Pwd=xxxxx;" providerName="System.Data.SqlClient"/>
<add name="Stage" connectionString="Server=localhost;Database=WebStage;User=stago;Pwd=xxxxx;" providerName="System.Data.SqlClient"/>
<add name="Live" connectionString="Server=localhost;Database=WebLive;User=livo;Pwd=xxxxx;" providerName="System.Data.SqlClient"/>
</connectionStrings>
Then we have a static method that bases itself on the url to determine which conn str to use:
public static string ConnStr
{
get
{
if (Config.WebRoot.StartsWith("http://www.")) { return ConfigurationManager.ConnectionStrings["Live"].ToString(); }
else if (Config.WebRoot.StartsWith("http://stage.")) { return ConfigurationManager.ConnectionStrings["Stage"].ToString(); }
else if (Config.WebRoot.StartsWith("http://localhost")) { return ConfigurationManager.ConnectionStrings["Dev"].ToString(); }
else { return null; }
}
}
You may have to adjust the method to work for you.

Resources