Entity Framework DB Model First - asp.net

I've created a fresh ASP.NET Web Forms model, with authentication pre built. I've then run through the following link
http://msdn.microsoft.com/en-us/data/jj206878
and created an entity framework from my exisiting database.
Ok, so far so good, however, when i fire up the project and click Register, the user created is still being inserted into a local db in the App_Data folder.
Why is this, and how can I ensure that all new users are pooled / created in my own database?

Probably because your DbContext is using built-in connection string. You can specify which connectionstring from your web.config to use when you initialize it in constructor like so.
public class MainDataContext : DbContext
{
public MainDataContext() : base("Name=NameOfConnectionString") { }
// public DbSet ...
}

Change you Default Connection String at Web.config/App.config with credentials of your own database.
Hope following link will help you:
http://hgminerva.wordpress.com/2013/09/21/how-to-create-the-asp-net-membership-tables-in-your-own-database/

Related

SQL Server database set, configs set - but data from database not displaying with #Html.DisplayFor<>()?

I have a question to ask about the SQL Server, Visual Studio and the Entity Framework and how it can update the Model-view with the use of #HTML.DisplayFor<>().
Currently everything is set up as it should be:
DbContext is good (Primary key is setup, alongside OnModelCreate(ModelBuilder modelBuilder))
SQL Server (local) is good
Migrations is good (and is showing up in SQL Server in VS2022)
... So pretty much the IIS Server is able to show my ASP.NET Core web-app without any debug/error information. It just won't show my elements in a DisplayFor<>().
My team and I are kind of perplexed, can someone please help us out? Thank you in advance.
I solved it!
I wasn't updating the Controller which was controlling the:
[HttpGet(IndexExample.cshtml)]
public IActionResult GetIndex()
{
var model = new IndexModel {
IndexSubclassGetSetSyntacticSugared = new IndexModel.IndexSubclass()
};
return View(model);
}

Upgraded to MS Identity Core 2.0 and EF6.1 and login fails: Invalid column name 'Email'

I went to the Manage NuGet Package option and updated all the packages. I'm not using much: Linq-to-EF 6.1 and the packages needed to make MS Identity work. However, something broke because now when I go to log in, I get an error
Exception Details: System.Data.SqlClient.SqlException: Invalid column name 'Email'.
Invalid column name 'EmailConfirmed'.
Invalid column name 'PhoneNumber'.
Invalid column name 'PhoneNumberConfirmed'. //and so on
The exception looks like this:
What might have caused this and how do I fix and prevent this from happening again when all I did was just update the NuGet packages?
Edit
I resolved this issue by totally removing the database; the app recreated a new DB with the necessary columns. I was able to do that because the app is still in dev and no real user data was involved. However, I'm still interested in this issue because when new updates will be released, I want to make sure I don't have to throw away the current DB.
I solved this for my application by removing the DefaultConnection connection string. If you have DefaultConnection and MySpecialConnection in your config file, ASP.net identity seems to use DefaultConnection.
Sounds like you would need to create your own user object with the additional fields you want that are not provided by the base object. That would then need to match the table in the database.
Then you use that new user object every time you use the usermanager.
var mgr = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>());
public class ApplicationUser : IdentityUser
{
//my custom fields
public string Email { get; set; }
}
Hope that helps

Login fails when recreating database with Code First

I'm using ASP.NET Entity Framework's Code First to create my database from the model, and the login seems to fail when the database needs to be recreated after the model changes.
In Global.asax, I've got the following:
protected void Application_Start()
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<EntriesContext>());
// ...
}
In my controller, I've got the following:
public ActionResult Index()
{
// This is just to force the database to be created
var context = new EntriesContext();
var all = (from e in context.Entries select e).ToList();
}
When the database doesn't exist, it is created with no problems. However, when I make a change to the model, rebuild and refresh, I get the following error:
Login failed for user 'sa'.
My connection string looks like this:
<add name="EntriesContext"
connectionString="Server=(LOCAL);Database=MyDB;User Id=sa;Password=password"
providerName="System.Data.SqlClient" />
The login definitely works as I can connect to the server and the database from Management Studio using these credentials.
If I delete the database manually, everything works correctly and the database is recreated as expected with the schema reflecting the changes made to the model.
It seems like either the password or access to the database is being lost.
Is there something else I need to do to get this working?
It seems like Code First has a problem using the password specified in the connection string when connecting to a database that has been recreated. Changing this to use a trusted connection gets around the problem as the password no longer needs to be stored.
So, instead of this:
Server=(LOCAL);Database=MyDB;User Id=sa;Password=password
Use the following instead
Server=(LOCAL);Database=MyDB;Trusted_Connection=true
You may need to add your account or the one being used by ASP.NET to SQL Server and grant it the 'dbcreator' permission so that it can drop and recreate the database.
I believe using sa may be an issue. Either way I believe it is good practice to create a separate user profile to use in your connection string.

DbContext ASP.Net and Quartz.net

I just created a cron job like job using Quartz.net. For the test, it execute a simple request to the database. It simply adds a field.
I have a dbcontext:
private TotoContext db = new TotoContext();
In my job I have:
var totos = from u in db.totos where u.name == name select u;
Toto[] totoArray = totos.ToArray();
In my web.config, I have a special field with my specific connectionstring and so on ("TotoContext").
But when I create a new dbContext it seems that it uses doesn't use the good connectionString. In the watch the connectionString is not linked with "TotoContext".
I initialize my job in:
public override bool OnStart()
And I have a specific Web.toto.config file with the connectionString for the build.
Why it doesn't use the good connectionString ?!
Thanks a lot !
Edit: if I set manually the connectionString in my db.Database.Connection.ConnectionString, it works. But why it doesn't use the web.config ConnectionString.
If you use full IIS mode (default configuration for web role), web.config will be ignored in the role entry point. So it is recommended to put all ASP.NET specific initialization tasks in Global.asax's Application_Start method. Role entry point is used to do something before ASP.NET application starts up, for example, modify IIS configuration. Inside Global.asax, web.config (and config transform) is respected.
I just found why it's not using the Web.config: https://stackoverflow.com/a/10153375/1396323
But the next question is how to store different connectionString depending on the build config (Debug, Release etc...) and where ?

Creating folders using DirectoryEntry

I am writing an ASP.NET (C#) application to create users for my domain. It also has to create folders and shares on a separate file server. I have so far been able to accomplish my task using
System.IO.Directory.CreateDirectory to create the folders,
a ("WinNT://fileserver/lanmanserver") DirectoryEntry to create the shares.
Unfortunately, my ASP.NET application has to run with impersonation on to create the folder. I don't like that. I would like to know if there is a way to create a folder on the file server using a DirectoryEntry object since i can pass the needed credentials to its constructor. Or, alternatively, is there a way to pass credentials to Directory.CreateDirectory?
Thanks in advance.
Here is the current code, just in case
strPath = "\\myServer\D$\newDir";
Directory.CreateDirectory(strPath);
using (DirectoryEntry deFS = new DirectoryEntry("WinNT://myServer/lanmanserver"))
{
using (DirectoryEntry deSH = deFS.Children.Add("newDir$", "fileshare"))
{
deSH.Properties["path"].Value = "D:\\newDir";
deSH.Properties["description"].Value = "My Stackoverflow sample share";
deSH.CommitChanges();
}
}
I don't believe you should be using DirectoryObject for that purpose, it wasn't made for such an access. But here's a trick you could be using to make impersonation easier. Create an impersonator class, which would implement IDisposable, something like this:
public class Impersonator : IDisposable
{
public Impersonator(userid, password)
{
... LogonUserEx();
... DuplicateToken();
... Impersonate();
}
public void Dispose()
{
... RevertToSelf();
}
}
then you would be able to do this:
using(new Impersonator("myaccount", "password"))
{
... do stuff that requires impersonation
}
As far as I know you have two options: impersonate a user that has permissions to create the directory on the remote share or give the permissions to the default user that runs asp.net services.
What is wrong with that? You are accessing a non-default resource on your network and the default privileges dont allow you to do that. It's pretty much like a regular user account trying to write on a network share.
The DirectoryEntry class has a constructor which take username and password as input. Have you tried this?
See documentation at Microsoft

Resources