How to change database from Local to Host to use Identity model - asp.net-mvc-5

I have a databse that located to App_Data folder with below connection string:
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-mydb-20171102055914.mdf;Initial Catalog=aspnet-mydb-20171102055914;Integrated Security=True"
providerName="System.Data.SqlClient" />
I've used it for Asp Identity User Manager Model.
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
but I want to use the database that is located in server. my server connection string structure is something like :
<add name="DefaultConnection" connectionString="metadata=res://*/Models.Database.mydbModel.csdl|res://*/Models.Database.mydbModel.ssdl|res://*/Models.Database.mydbModel.msl;provider=System.Data.SqlClient;provider connection string='data source=134.54.96.45,1355;initial catalog=Db_Server;user id="serverUser";password=serverPass;MultipleActiveResultSets=True;App=EntityFramework'" providerName="System.Data.EntityClient" />
the server connection string works correctly for other models. but when I want to use ASP Identity Model, its caused error. How I cant fix it?

I fixed this by creating a standard connection string that pointed to the database where the ASP.NET Identity tables are.
<add name="DefaultConnection" connectionString="Data Source=134.54.96.45,1355; Initial Catalog=Db_Server; User ID="serverUser"; Password=serverPass; Connect Timeout=60;" providerName="System.Data.SqlClient" />
I do not know why the Identity Model just worked with this connection string and what is the diffrent between these connction strings.
but this last works correctly for me.

Related

Publishing Azure web app puts a connection string inside a connection string

I have an Azure Web App (https://www.triviaweb.net/) and a connection string in the web.config that looks like this.
<connectionStrings>
<add name="Entities" connectionString="metadata=res://*/TriviaWebModel.csdl|res://*/TriviaWebModel.ssdl|res://*/TriviaWebModel.msl;provider=System.Data.SqlClient;provider connection string="data source=tcp:dolaris.database.windows.net;initial catalog={cata};persist security info=True;user id={usr};password={psw};multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
When I publish the web app using Visual Studio 2019 version 16.7.2 to Azure the web.config is transformed to this.
<connectionStrings>
<add name="Entities" connectionString="metadata=res://*/TriviaWebModel.csdl|res://*/TriviaWebModel.ssdl|res://*/TriviaWebModel.msl;provider=System.Data.SqlClient;provider connection string='metadata=res://*/TriviaWebModel.csdl|res://*/TriviaWebModel.ssdl|res://*/TriviaWebModel.msl;provider=System.Data.SqlClient;provider connection string="data source=tcp:dolaris.database.windows.net;initial catalog={cata};persist security info=True;user id={usr};password={psw};MultipleActiveResultSets=True;App=EntityFramework"'" providerName="System.Data.EntityClient" />
</connectionStrings>
It looks like the transformation kind of put a connection string inside the connection string. I can fix this manually on the server to make my app work but would much prefer that the publishing works correctly.
I’ve never seen anything like this.
Provider Connection String contains valid keyword/value pairs for the data provider. An invalid Provider Connection String will cause a run-time error when it is evaluated by the data source.
Make sure to escape the value according to the general syntax of ADO.NET connection strings. Consider for example the following connection string: Server=serverName; User ID = userID. It must be escaped because it contains a semicolon. Since it does not contain double quotation marks, they may be used for escaping:
Provider Connection String ="Server=serverName; User ID = userID";
Try changing your connection string from :
<add
name="Entities"
connectionString="metadata=res://*/TriviaWebModel.csdl|res://*/TriviaWebModel.ssdl|res://*/TriviaWebModel.msl;
provider=System.Data.SqlClient;
provider connection string="
data source=tcp:dolaris.database.windows.net;
initial catalog={cata};
persist security info=True;
user id={usr};
password={psw};
multipleactiveresultsets=True;
application name=EntityFramework""
providerName="System.Data.EntityClient" />
to:
<add
name="Entities"
connectionString="metadata=res://*/TriviaWebModel.csdl|res://*/TriviaWebModel.ssdl|res://*/TriviaWebModel.msl;"
provider= "System.Data.SqlClient"
providerConnectionString="data source=tcp:dolaris.database.windows.net;
initial catalog={cata};
persist security info=True;
user id={usr};
password={psw};
multipleactiveresultsets=True;
application name=EntityFramework;"
providerName="System.Data.EntityClient" />
For more information, you can visit Connection Strings in the ADO.NET Entity Framework.

configuration file does not contain the required providerName attribute, Azure Api

I made an azure web app. When I go to my web app URL it says the app is up and running, https://nameofmyapp.azurewebsites.net/.
When I try to go send a request for the web API by going to https://nameofmyapp.azurewebsites.net/api/Menus to get JSON text I receive this error
{
"Message": "An error has occurred.",
"ExceptionMessage": "The connection string 'PetSchedulerDbContext' in the application's configuration file does not contain the required providerName attribute.\"",
"ExceptionType": "System.InvalidOperationException",
"StackTrace": " at System.Data.Entity.Internal.LazyInternalConnection.InitializeFromConnectionStringSetting(ConnectionStringSettings appConfigConnection)\r\n
Here is my connection string:
<connectionStrings>
<add name="PetschedulerDbContext" connectionString="Server=tcp:petschedulerserver.database.windows.net,1433;Initial Catalog=petschedulerdb;Persist Security Info=False;User ID=Julia;Password=Network5!;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;" providerName="System.Data.SqlClient" />
</connectionStrings>
I have tried changing the provider name to
providerName="System.Data.EntityClient"
with the same result. I don't understand what the required provider name would be? Please let me know if you need more information.
Here are my cents for this issue:
Prerequisite: Please make sure you have the same set of connection string value in the Azure portal Web app configuration setting as well.
If you are using designed based approach, then you need to define the connections string that the designer generates and which looks something like this:
<add name="Northwind_Entities"
connectionString="metadata=res://*/Northwind.csdl|
res://*/Northwind.ssdl|
res://*/Northwind.msl;
provider=System.Data.SqlClient;
provider connection string=
"Data Source=.\sqlexpress;
Initial Catalog=Northwind;
Integrated Security=True;
MultipleActiveResultSets=True""
providerName="System.Data.EntityClient"/>
If you're not using the designer (if you don't have an .edmx file), the connection string should look like this:
<add name="ConnectionStringName" providerName="System.Data.SqlClient" connectionString="Data Source=ServerName;Initial Catalog=DatabaseName;Integrated Security=False;User Id=userid;Password=password;MultipleActiveResultSets=True" />
Additional reference:
https://learn.microsoft.com/en-us/ef/ef6/fundamentals/configuring/connection-strings?redirectedfrom=MSDN
https://forums.asp.net/t/1858681.aspx?The+connection+string+EFDbContext+in+the+application+s+configuration+file+does+not+contain+the+required+providerName+attribute+
Hope it helps.

Custom provider in the url rewrite module

I am developing on a website which is currently hosted in Azure on a VM. Now I am changing this website to be able to run it as an Azure website.
Now my problem:
I am using the url rewrite module from IIS with the database provider, which works perfectly in the VM. With the database provider users of the website can create their own simple rewrite rules.
But when I upload my website as an Azure Website and I access a url that's specified in the database I get an error:
"The page cannot be displayed because an internal server error has occurred.".
This is the logging configuration I currently use:
<rewrite>
<rules configSource="RewriteInbound_Live.config" />
<outboundRules configSource="RewriteOutbound_Live.config" />
<providers>
<provider name="DB" type="DbProvider, Microsoft.Web.Iis.Rewrite.Providers, Version=7.1.761.0, Culture=neutral, PublicKeyToken=0545b0627da60a5f">
<settings>
<add key="ConnectionString" value="*****" />
<add key="StoredProcedure" value="sp_GetRewrittenUrl" />
<add key="CacheMinutesInterval" value="60" />
</settings>
</provider>
</providers>
</rewrite>
I've turned on web server logging which doesn't give me any information, and I've enabled application logging which also doesn't give me any information.
My question, is it possible to use custom providers for the url rewite module in Azure, of can this be achieved in another way?
I had the same problem: DbProvider not available in azure web app. So I left most of the url rewriting stuff in the web.config untouched and moved the database-based rules to the global.asax file's Application_BeginRequest method.
For redirect rules, just use a Response.Redirect or an adequate Redirect301 implementation. On the other hand, for the rewrites, use HttpContext.Current.RewritePath.
You should add a caching mechanism in order to reduce repetitive queries to the DB:
void Application_BeginRequest(Object sender, EventArgs e)
{
//TODO: Cache sql queries
string requestUrl = Request.FilePath;
using (DBConn conn = new DBConn("GetRedirectUrl"))
{
conn["input"] = requestUrl;
string res = conn.ExecuteScalar()?.ToString();
if (!string.IsNullOrEmpty(res))
{
Response.Redirect301(res);
}
}
//TODO: Cache sql queries
using (DBConn conn = new DBConn("GetRewrittenUrl"))
{
conn["input"] = requestUrl;
string res = conn.ExecuteScalar()?.ToString();
if (!string.IsNullOrEmpty(res))
{
HttpContext.Current.RewritePath(res);
}
}
}

Using windows identity to check users custom role using the .IsInRole method

I have created an MVC application whereby the user is able to authenticate either via ADFS or Forms login and in both cases I have been able to use the User.IsInRole method to check my user table that has a roleID attribute which ties to a role table in my database. This is done by including the following section in my webconfig within :
<roleManager enabled="true" defaultProvider="DefaultRoleProvider" cacheRolesInCookie="true">
<providers>
<clear />
<add name="DefaultRoleProvider" type="MyInternal.Providers.MyProvider, MyInternal" connectionStringName="MyContext" />
</providers>
</roleManager>
I am now trying to implement windows authentication and have managed to get the users domain login name etc but when trying to follow same steps as with other two authentication types I am unable to get the IsInRole to work.
How can I tie the User from my repository to the authentication user. Is there some sort of casts or something required? I think that this may have been done by the authentication in ADFS and Forms.
I was able to solve this issue by using the following within my ViewModel:
this.UserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
if (this.UserName.Contains("\\"))
{
string[] stringArray = this.UserName.Split(new Char[] { '\\' });
this.UserName = stringArray[1];
MyUser identity = userRepository.Get(u => u.Username == this.UserName).FirstOrDefault();
HttpContext.Current.User = identity;
}

Specifiy Connection String When Publishing Web

I have a web site I am building where I need to deploy to two environments: stage and prod.
I have three connection strings specified in my web.config.
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=MyWebAppWaitWebDb;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\MyWebAppWaitWeb.mdf" providerName="System.Data.SqlClient" />
<add name="MyWebAppConnection_Stage" connectionString="Server=StageSQL01T;Database=MyWebAppWaitWeb;User Id=foo;Password=bar" providerName="System.Data.SqlClient" />
<add name="MyWebAppConnection_Prod" connectionString="Server=ProdSQL01;Failover Partner=ProdSQL02;Database=prd_SP_ExternalData;User Id=foo;Password=bar" providerName="System.Data.SqlClient" />
In the Publishing Web Wizard I am presented all three of these connection strings in the "settings" portion of the wizard. So in this case I chose stage and un-checked the others so that I can publish to my stage server.
Upon publishing I find it added a new connection called "MyWebAppConnection_Stage_DatabasePublish"
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=MyWebAppWaitWebDb;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\MyWebAppWaitWeb.mdf" providerName="System.Data.MyWebApp" />
<add name="MyWebAppConnection_Stage" connectionString="Data Source=StageSQL01T;Initial Catalog=MyWebAppWaitWeb;User ID=foo;Password=bar" providerName="System.Data.MyWebApp" />
<add name="MyWebAppConnection_Prod" connectionString="Server=ProdSQL01;Failover Partner=ProdSQL02;Database=prd_SP_ExternalData;User Id=MyWebAppWebApp;Password=bar" providerName="System.Data.MyWebApp" />
<add name="MyWebAppConnection_Stage_DatabasePublish" connectionString="Data Source=StageSQL01T;Initial Catalog=MyWebAppWaitWeb;User ID=foo;Password=bar" providerName="System.Data.MyWebApp" />
Why is this 4th connection string being generated? Furthermore, how is this VS 2010 Publishing compatible with the DbContext class I have for my Entity Code-first class that specifies the connection string?
public class MyContextDb : DbContext
{
public MyContextDb(): base("DefaultConnection")
{
Debug.Write(Database.Connection.ConnectionString);
}
...
I would think that I would want to use traditional web.config transformation which simply alters one connection string according to the transform file being used.

Resources