C# ASP.net MVC database questions - c#

I am trying to develop a website with C# ASP.net MVC. It's my first time using Visual Studio, C# and ASP.net so I have lots to learn but so far so good.
So far... I started a C# ASP.net MVC project and added a database by going to the Database Explorer and clicking "add connection". I then did some standard CRUD controllers and views.
I am at the stage where I want to implement User authentication. I'm a bit confused here. I am trying to make a custom Membership Provider. So I added it to my web.config file with the correct connection string etc.
When I run the project and go to register I get an error. "Could not find stored procedure 'dbo.aspnet_CheckSchemaVersion'."
From searching, I see lots of people have this problem and they always reference their hosting. People say this (http://weblogs.asp.net/scottgu/archive/2005/08/25/423703.aspx) is their solution but when I try pick a database I get an error. Not even sure of my server name.
So at this point I am wondering, did I set up the database right?
EDIT
Adding in a few pics to show exactly what I am doing. This is the aspnet_regsql.exe:
This is the provider with connection string, taken from an example on one of the links given.
This is my customized provider with connection string pointing to the last image.
This is a screen cap when I run the project and go to the default project Account register action:
and finally, this is the error screen when I submit
EDIT
Another update..
I sorted something out but I am not sure if it is correct. I am now getting an error when the page loads: "Invalid object name 'dbo.Tag'"

In order to solve this problem the only thing you need to do is create an application services DB. You can achieve this by running the following command from your Visual Studio Command Prompt
aspnet_regsql
Anyways it seems that your "custom provider" isn't using a custom structure for your DB, which might be the reason why you weren't expecting this error.
If you are using the default implementation, you can access to the user administration using ASP .NET Configuration, located on your project menu in visual studio.
The default implementation uses the following conn string keyword
LocalSqlServer
The are many ways of implementing the membership provider. My guess is that probably this conn string is not pointing to your aspnet services db, you could do something like this to specify a custom location for this db
<remove name="LocalSqlServer"/>
<add name="LocalSqlServer" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\aspnetdb.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient" />
I made a blog post regarding this topic: How to use MembershipRole Provider and when to use custom implementations

It's hard to figure out anything from your post.
but when I try pick a database I get
an error.
You can check your server name in Surface area configuration or Sql Server Configuration Manager. If you installed Visual Studio it's probably YOUR_MACHINE_NAME\SQLEXPRESS. You can connect to it using Windows Authentication. You could also write localhost,1433 instead, but that would require enabling TCP/IP first(it's disabled by default) and setting the port number first(which in most cases is already set).

Related

Cannot Create Database with credentials using Entity Framework Code-First?

I'm a bit new to code-first approach but I used Database first approach before using entity framework, now I want to work with code first instead and its kinda a habit.
I started creating models and its all good, then enabled migrations and add-migration as well and all works well, but when I run Update-Database command I get an error.
Hence I want to create a database with code-first using credentials, after a lot of research I didn't find a solution and mostly tutorials use "Trusted Connection".
What I use
App.Config
<connectionStrings>
<add name="CodeFirst" connectionString="Server=.\SQLEXPRESS;Database=CodeFirst;User ID=anyuser;Password=anypassword;"
providerName="System.Data.SqlClient" />
</connectionStrings>
DbContext Class
public class CodeFirstContext : DbContext
{
public CodeFirstContext() : base("name=CodeFirst")
{
}
public DbSet<Product> Products { get; set; }
public DbSet<Category> Categories { get; set; }
}
The Error I get
Login failed for user 'anyuser'.
The question is I did something wrong ? or using credentials can't be done using code-first approach ?
Thanks in advance
OP:
I want to create a database with code-first using credentials,
...and:
after a lot of research I didn't find a solution and mostly tutorials use "Trusted Connection".
Therein lies the problem with code-first approaches when deploying to a new database using a specific login - it's a chicken and egg because:
the database doesn't yet exist
the connection string is requesting an explicit login
the login does not yet exist in say SQL
because the database doesn't exist
OP's config:
<connectionStrings>
<add name="CodeFirst"
connectionString="Server=.\SQLEXPRESS;Database=CodeFirst;User ID=anyuser;Password=anypassword;"
... />
</connectionStrings>
So what's the solution?
Use Integrated Security: this allows you to create the database from scratch from code. However any other logins you may need might have to be created later. However, DB-speaking, it's a bit of a bad practice because you should get into the habbit of having one account for deployment (with just enough rights for deployment) and another for general app access (and no rights for deployment)
Create Login First: this allows you to use your specified login however you most likely will need to create a blank database first from SQL before you can create the login. Code-first purists may not like this idea.
The latter does follow DACPAC best practices you should already be familiar with from your time in database-first. Just like how a DACPAC shouldn't be deploying logins and adjusting security neither should code-first. Afterall at the end of the day, databases don't care about whether you use code-first or database-first (under the hood, both probably employ some form of encasulated scripting) but your DB Admin might raise an eyebrow depending on how security is being used.
Are database-first approaches better?
In the theme of don't do that, try this instead, code-first tries to do everything via code and whilst a noble pursuit perhaps isn't realistic. Some things like attempting to create logins perhaps isn't possible as mentioned above.
Meanwhile database-first schema changes are carried out by deploying DACPACs from the database side. Authentication is via the login used to get into SSMS (for example) in the first place. DACPAC deployment doesn't require code, .NET or otherwise.
DACPACs can create and/modify database security including logins but is generally frowned upon.
You might want to re-think code-first. Code-first and EF Migrations hasn't really succeeded as a concept in the real world where you have staged CD environments such as DEV; TEST; UAT and PROD.
I see so many developers using code-first only for deploying to their local database. Once there, they use different means to deploy the changes to other computers including TEST and PROD whether it's TSQL scripts or database backup.
It just seems to be so much effort for something that doesn't even complete the race.

How to solve open id configuration error with identity server 4?

I am trying to use Identity Server 4 for Authenticationa and authorization purpose but which ever project i try to run is throwing only 1 error which is like bugging me alot because i have search for this error and i cant find a stable and proper solution for this.
Error :
Error connecting to
http://localhost:5000/.well-known/openid-configuration: An error
occurred while sending the request.
Couple of projects in which i am getting same error and dont know how to solve it :
https://www.dropbox.com/s/9hs3huwt8h035ek/oauth2Demo-master.rar?dl=0
Another Project : Download but same error
In my first project it seems like there is some problem related to SSL certificate though i tried to follow below link to install certificate but still this error exist :
https://github.com/IdentityServer/IdentityServer3.Samples/tree/master/source/Certificates
But in my second project there is no such SSL certificate problem but still same error.
Is there any way to resolve that error?
I downloaded the solution and I can confirm you need to make sure to run the OAuth2Demo.IdentityServer project, you can actually start it up and navigate to https://localhost:44305/admin/ to see the admin environment of identityserver. It apperantly also needs a sql connection to store configuration information, I didn't dig into those details but with the OAuth2Demo.IdentityServer running the other projects can also be started.
My suggestion is to get the things done one by one.
From your screens I see that on the first you are trying to reach IDS at localhost:44305, and on the second screen, you are trying to reach it at localhost:5000. It will be a good thing to set it as a constant value ( right click on your Identity Server project ->Properties->Debug->Web Server Settings->App URL) and then use this value through all of your clients.
Then - enable Identity Server logging - check here. You can extend this example - serilog basic configurations. So far logging has saved me many times, so I can say that it is really important. Make sure that the App pool account, running the application has the rights to create files, where you want them to be created.
Now the real problem:
Lets assume that you select localhost:5000 as url for your IDS.
First of all start (debug) only the Identity Server project. This should take you to localhost:5000 and you will see a welcome message from Identity Server 4.
If you see it, this means that your IDS is working. This also means that you will be able to access the Discovery Document - the one thing that is failing in your clients. Now its about time to setup your clients.
If not, this means that there is something wrong with your Identity Server instance, and that is the place to dig.
First thing I'll do is to check the logs. They will say what the problem is.
Then - I figure out that you are trying to use custom certificate for this (correct me if I've misunderstood). Why don't you try using the Developer Signing Credential (check the ConfigureServices of Startup.cs) at least for starting it up.
Later on, if you decide to use your custom certificate, have in mind that the user, that is running the IDS application (by user I mean the application pool user) should have at least read privileges over the certificate (I guess that you've seen that in the article you have provided).
Do all these, and let's see what progress you will have, but most important - enable the logging.

Unable to Update Model from Database using EF 6 and Visual Studio 2015 Update 3

Right click on the EF Model Designer surface and choose Update Model from Database.
In the dialog box that pops up, you should be able to browse the database, and select objects to add. But in this case, nothing can be selected:
Removing the Connection String from the App.Config and allowing the Designer to re-add it did not resolve the issue.
The credentials used in the Connection String when copied and pasted in SSMS.
The database can be browsed from the VS Server Explorer window.
Creating a new blank EF project and repeating from there works fine.
What could be causing this?
One of 2 problems exist, the Model already has the Tables/SP/View you are looking for or the Login does not have the Authority the access those Tables/SP/View.
One of the factor unable to select any checkbox in Update Wizard is you don't have any updates in your database, therefore entity framework doesn't allow you to select.
If your scenario is not the factor above, you may try the method I listed below:
I had this issue too and I noticed that I didn't grant the db_owner under Database role membership for my database (eg 22Aug_M) in Microsoft SQL Server Management Studio.
After I checked it and it works as normal.

DNN Database Repository Reuse in Console Application

I have a project based on the Chris Hammond, Christoc, module template. I have a ton of code that I use to access data an external database. In my repositories I change the database from the default to whichever I need for that particular object. I do so with code that looks like this:
using (IDataContext ctx = DataContext.Instance(MyModuleSettingsBase.DATABASE_CONNECTION_STRING_KEY))
{
var rep = ctx.GetRepository<Product>();
products = rep.Get().ToList();
}
The default database is switched in the call to .Instance(). The repositories are used by my custom DNN modules. The repository is part of the solution that contains multiple custom modules. When I compile and install using the Extensions part of DNN, everything works well. In the code above, MyModuleSettingsBase.DATABASE_CONNECTION_STRING_KEY is found in a file MyModuleSettingsBase.cs file of my module solution. It is set to a simple string like "ProductDatabase". In the solution for the base DNN install (not the module solution), within the web.config file, there is a value in <connectionStrings> with name="ProductDatabase" which contains the actual connection string. This all links up fine on the DNN website.
Now I am writing a console application that does some monitoring of the site. I want to access the database to check values in the product table. I would like to reuse all of the repository code I have written. In an attempt to do so, I added a reference to the MyModules.dll file so I would only have one copy of the base code. This works to give me access to all the objects and the associated repositories but when I attempt to query data it fails. When debugging I can see that it fails on the line:
using (IDataContext ctx = DataContext.Instance(MyModuleSettingsBase.DATABASE_CONNECTION_STRING_KEY))
When viewed in a debugger, the string value MyModuleSettingsBase.DATABASE_CONNECTION_STRING_KEY is correctly set to "ProductDatabase" but the code is unable to link this with the actual connection string. I don't know where it would be checking for the connections string when running from my console application. I attempted to put a <connectionStrings> section into my App.config file but this didn't do the trick.
Is it possible to have MyModuleSettingsBase.DATABASE_CONNECTION_STRING_KEY map to the connection string in an external application which references the DLL?
If so, where can I set the value of my connection string so it matches up to the key value stored in MyModuleSettingsBase.DATABASE_CONNECTION_STRING_KEY?
I was faced similar problem 3 months ago, at that time I want to use DNN core libraries in my console application but I was failed.
I placed my queries in DNN official forum website and I got a valid response from Wes Tatters (DNN MVP).
Here is the post link: Reference URL
As your requirement of monitoring, I suggest you to create DNN Schedule Application. You can schedule it within DNN (Host->AdvancedSettings->Schedule), even good point is that you can use your repositories (DNN Libraries) in that schedule application.
I hope it solved your problem. Let me know if you have any questions.

Access .NET Membership on Live or Local provider

In my web.config file I have two SQL Server connection strings, one for local and one for live:
<connectionStrings>
<remove name="LocalSqlServer" />
<add name="LocalSqlServer" connectionString="[removed]" providerName="System.Data.SqlClient"/>
<add name="LiveSqlServer" connectionString="[removed]" providerName="System.Data.SqlClient"/>
</connectionStrings>
I then have a "utils" singleton class which basically sets the connection string depending if I'm running the site on "localhost" or on my live server:
if (Environment.MachineName.ToUpper() == MyOwnConfig.GetAppSettingsValue(ConfigKeys.localhost).ToUpper()) {
this.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["LocalSqlServer"].ToString();
//MembershipProvider provider = Membership.Providers["LocalAspNetMemberSqlProvider"];
//RoleProvider role = Roles.Providers["LocalAspNetMemberSqlProvider"];
}
else {
this.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["LiveSqlServer"].ToString();
//MembershipProvider provider = Membership.Providers["LiveAspNetMemberSqlProvider"];
//RoleProvider role = Roles.Providers["LiveAspNetMemberSqlProvider"];
}
My Database class then simply uses the connectionString property of my utils class. All this works fine so when I place the site locally I can then simply upload it to live without making changes to the connection strings etc in the config file and it starts using my live database.
Now I'm currently implementing "membership" into my site and for ajax for use some webmethods I'm storing the providerUserKey in a text field of the current logged in user. my web method then checks that this key is authenticated. e.g.
ajaxCreds.ajaxID1 = ((MembershipUser)Membership.GetUser()).ProviderUserKey.ToString();
QUESTION:
the question I have is How do I know if this membership is from the LIVE database or my LOCAL database. As you can see from the web config I've added in the membership/provider lines (commented out) but I don't know how to use them with the above membership.getUser() command.
Alternative... Is this a good way to go? or is it simpler to edit the web.config file when I upload to live?
Many thanks
Most people don't do it this way though I applaud you for figuring all this out. Typically, people use the deployment manager or some other build system to have a different web.config value on the server verses local.
Here is a link on changing in deployment: How do I use Web.Config transform on my connection strings?
I would suggest you to read this article:
http://blogs.msdn.com/b/schlepticons/archive/2010/07/22/modifying-asp-net-providers-at-runtime.aspx
It will show you, that also others were trying to do the similar. And this is how to succeed. Solution (if adjusted) could be similar to your needs.
put all the providers into your web.config
On App_Start adjust which will be the default (based on the Environment)
Membership API will be available as you need for Provider Key
No need to search for Provider by Name
NOTE: you have to tweak the void Application_Start(object sender, EventArgs e) implementation but the idea is there
NOTE2: What you are trying to do is definitely not exception. Configuration based on environment is pretty smart! What must be achieved is standard API usage, e.g. calls via Manager pattern
System.Web.Security.Membership
System.Web.Security.Roles
and not calls to the providers by name.

Categories

Resources