0

I preliminary apologize for possibly asking a question that has already been answered, in which case please lead me to a relevant post, but I could not discover myself the answer.

I have an ASP.NET website which - after publishing - should be able to connect to different databases according to the user's wish. In the Login page there should be a list of databases from which the user will choose and connect to one according to individual credentials. This is how the login page should look:

enter image description here

The code for the Login page:

public partial class Login : Page
    {
        protected void Page_Init(object sender, EventArgs e)
        {
            List<String> conns = new List<string>();
            foreach (ConnectionStringSettings conn in System.Configuration.ConfigurationManager.ConnectionStrings)
            {
                conns.Add(conn.Name);
            }
            listBD.DataSource = conns;
            listBD.DataBind();
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            RegisterHyperLink.NavigateUrl = "Register";
            ForgotPasswordHyperLink.NavigateUrl = "Forgot";
            OpenAuthLogin.ReturnUrl = Request.QueryString["ReturnUrl"];
            var returnUrl = HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
            if (!String.IsNullOrEmpty(returnUrl))
            {
                RegisterHyperLink.NavigateUrl += "?ReturnUrl=" + returnUrl;
            }
            if (User.Identity.IsAuthenticated && this.Request.RawUrl.Contains("Login?"))
            {
                Response.Redirect("~/Interzis.aspx");
            }

            else if (User.Identity.IsAuthenticated && this.Request.RawUrl.Contains("Login"))
            {
                IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
            }
            ApplicationDbContext db = new ApplicationDbContext();
        }

        protected void LogIn(object sender, EventArgs e)
        {
            if (IsValid)
            {
                var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
                var signinManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();

                List<ApplicationUser> us = manager.Users.ToList();

                foreach (var user in us)
                {
                    textSuccess.Text += user.UserName + ": ";
                    foreach (var role in user.Roles)
                    {
                        textSuccess.Text += role.RoleId + ", ";
                    }
                }
                var result = signinManager.PasswordSignIn(Email.Text, Password.Text, true, shouldLockout: false);

                switch (result)
                {
                    case SignInStatus.Success:
                        panelSuccess.Visible = true;
                        IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
                        break;
                    case SignInStatus.LockedOut:
                        Response.Redirect("/Account/Lockout");
                        break;
                    case SignInStatus.RequiresVerification:
                        Response.Redirect(String.Format("/Account/TwoFactorAuthenticationSignIn?ReturnUrl={0}&RememberMe={1}", 
                                                        Request.QueryString["ReturnUrl"],
                                                        RememberMe.Checked),
                                          true);
                        break;
                    case SignInStatus.Failure:
                    default:
                        FailureText.Text = "Înregistrare eșuată";
                        ErrorMessage.Visible = true;
                        break;
                }
            }
        }
    }

The Startup class:

public partial class Startup {

        public void ConfigureAuth(IAppBuilder app)
        {
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login.aspx"),
                Provider = new CookieAuthenticationProvider
                {

                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });

        }

}

This is my current simplified version of DBContext class:

 public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {

        public ApplicationDbContext()
            : base("Users", throwIfV1Schema: false)
        {
            Configuration.ProxyCreationEnabled = true;
            Configuration.LazyLoadingEnabled = true;
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }

        // Override OnModelsCreating:
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            System.Data.Entity.Database.SetInitializer<ApplicationDbContext>(null);
        }

    }

If I add the connection string parameter to the ApplicationDbContext constructor, I'll need to add it in the startup class here:

app.CreatePerOwinContext(() => ApplicationDbContext.Create(connectionString));

But this is invoked before clicking the Submit button on the Login page, thus before selecting a database. It means that there should be a default database to which the app first tries to connect. But this is not what I want. How could I change the situation?

Secondly, what piece of code should I add to the LogIn method in the Login class for connecting to the selected database?

I will add that I use Entity Framework 6 and Code First Migrations in order to deal with the databases.

Thank you very much!

Ionna
  • 223
  • 4
  • 19
  • You can define multiple connection strings in the web.config, give them unique names and then use those names to pass it into your DbContext constructor (which accepts a connection string name). Will that do it? – hbulens Jun 29 '16 at 08:59
  • IT is not necessary to put the connection string in web.config. You can define it in your code also. But it is kept there so that one can easily change the connection after publishing. You can define multiple connection string in your web.config as mentioned above. And create a dictionary kind of structure and use them as required. – Akash Amin Jun 29 '16 at 09:04
  • Could you provide a code example for your suggestion? I have added my DBContext class code. – Ionna Jun 29 '16 at 09:39
  • The databases are identical? So, you only need to change the connection string at runtime? – Tasos K. Jun 29 '16 at 10:43
  • Exactly, @TasosK., they are identical. – Ionna Jun 29 '16 at 11:25
  • @lonna write your connection string and your exception then we can help you – Bassam Alugili Jun 29 '16 at 11:46
  • 1
    See http://stackoverflow.com/questions/20216147/entity-framework-change-connection-at-runtime – Steve Greene Jun 29 '16 at 12:55
  • I have rephrased my question after a couple of trials... Thank you. – Ionna Jun 30 '16 at 10:53

0 Answers0