Change Entity Framework Context Connection String Based On Logged in User - asp.net

I've been struggling with this one for quite some time and have been unable to find a good solution. I'm using the code first method, and this is what I'm trying to accomplish:
First, when a user logs into the application, I authenticate him and retrieve his connection string from a company table in a membership database.
Next, I want to use this connection string for the dbcontext. Each company has it's own database with the same structure.
Here are two things I'd like to avoid:
I don't want to pass the connection string to the context constructor because this is an existing app and there are several calls.
I don't want to use session because the library is shared with a windows service app that loops through the connections in the company table to perform data imports.
Any suggestions? Any help is appreciated. Thanks.

Related

Multiple Database Usage, Second Connection After Login

There is a scenario like in the picture. There is a common database. Customers are connecting to the same database. After the connection, company-specific information is kept in a separate database. The connecting string is pulled from the company information in the database after the user logs in. How can I do this logic in .net core. I'm new and need ideas.
Click to see the script
When the user logs in, company information is also taken as in the picture.
Click for user company information
I can't define it in the "startup.cs" file because the user needs to be logged in.
Where and how can I define the connecting clause? Can you give an idea?
Startup.cs file
appsettings.json file
login method
In the login method, I need to migrate first. To create the tables. If there are tables, I need to connect to the company's product table. Can this special link be added to swagger too?
Specifically within .net core project you can utilise DBFactoryBase class, and create a constructor which accept appsettings json key to fetch another connection string.

signalR generating different ID for various instances

I have created web chat application using signalR. When user is logged in, user can open only 3-4 tabs and each time different connection ID is generated. I want that when we open new tab or refresh the page new connection id should not be generated. I want to use the existing connection id. For that I tried to implement the LocalStorage variable to store the hub connection.
But Problem is i am unable to parse the value of localstorage variable.
Can Anyone give me the solution to my problem or can anyone give me any other solution to the problem?
I have already tried this http://kevgriffin.com/maintaining-signalr-connectionids-across-page-instances/ but it dosen't work for me
If user is authenticated you can store different connectionIds in the HashSet. The key for the HashSet will be the user's name.
http://www.asp.net/signalr/overview/signalr-20/hubs-api/mapping-users-to-connections
You can use this method even if you are not authenticated. In this case you can use SessionId instead of username.
EDITED:
I have found another method. In this article Alex Ford advices to limit your connections to 3.

How to log inserts, updates in SQL Server?

I am wondering what would be the best practice to logging when a user inserts or updates some data from my ASP.NET application.
In my application I need to know which user made the change, I think I have to options:
Register my ASP.NET users into the SQL Server adding them the rights for the tables needed, and store for each of my users
individual connectionstring. Thus I could use the currently logged in
user's connectionstring when connecting to the database, so that I
could write T-SQL triggers for SELECT and UPDATE.
The other option I thought of is that I can write stored procedures that get the ASP.NET user name as input parameter and makes
the log for me, (I use only one connectionstring in the application).
After modifying the database from the application I would call this
procedure giving the currently logged in user's username.
The second option seems simpler to me, but I think that for that purpose I should choose the first option.
Go for the second option. Managing users in a database creates more of a headache for you and what happens if you have to move the database server? You would need to update all of the connection strings for all the users. It just creates an extra admin overhead.
Furthermore, if you need to log all the changes in the database then I have come up with something that I have used in the past to store all changes made to a database over time. Have a look, it might be useful.
http://richhooper.wordpress.com/2012/06/11/sql-server-row-level-versioning/

Dynamically connect to different databases in a hybrid multitenant solution

I was researching about multi-tenancy and multi-instance approaches and chose a hybrid.
I keep a single instance of my ASP.Net MVC 2 application but clone the database structure for each client. I am using LINQ to SQL.
Right now, I have one instance of both so just a single connection string is working.
I am planning to expand it for many clients.
I can write code to create a clone of the database structure, create a db user and give permissions whenever a new client signs up. I also will save all these details (db name, db user, allowed app users) in a table.
But how can I make the app use a different database based on who is logged in?
I can't even figure out the approach I should take to do this. Should I programmatically add connection string to web.config? Is there another way to do this?
One of the constructors for DataContext accepts the connection string. You can assemble this string based on the user for the specific request.
This will override the default connection.
Check the constructor overloads for the DataContext, there is one that takes connection string. You just need to map a string property against the logged in user.
Please don't programmatically add EVERY user's connection string to web.config, think scalability!!!

ASP MVC User Profiles

I've done MVC in the past, but I am new to ASP and ASP MVC. I really love the ease that ASP MVC provides me, so far, but I am having trouble figuring out how to get more control over the Users. By default, the MVC provides a minimal user registration form. I have looked around quite a bit, but I still have two questions:
How do I make the User data base a local database in my project? I think SQLEXPRESS is used to store the user values, in what seems like a magical process. How do I de-magic-ify this? I would like to have more control on the location of this database.
This leads to another question: How do I expand the User? I have been reading up on Profiles, but I am still confused about a few things. How do I prepare a Profile and link it with a User? What serves as the foreign key? And, in my controllers, how can I access various parts of the user like username, email, or even from the profile stuff like firstname, lastname (though I guess once when I have a Profile's database and a User's database locally, I can run sql commands to retrieve data)
I would really appreciate some pointers to the right resources, and/or best practices with ASP.NET
I would start by reading this official Microsoft article on extending the ASP.NET Membership API. It talks about creating extra tables for storing additional information about users.
The membership database
If you have an existing database which holds all your other website information, you can run the aspnet_regsql.exe tool to generate the necessary user tables. You will then need to modify your web.config and add the SqlMembershipProvider along with your connection string.
If you're creating a new project and don't have a database, start with a new MVC project which already has Membership enabled. Your database will be created inside the App_Data folder on first use, and you can take this and attach it to your SQL/SQLEXPRESS server. Then it's just a matter of changing the connection string to use a DB server rather than a local file.
Creating additional tables
This part is actually quite simple and consists of a few short steps:
Create a new table, i.e. UserProfiles
Add a uniqueidentifier column as your primary key, and add a foreign key to the aspnet_Users table
Add any other fields you want to store (Phone, Address, Gender etc.)
If you're using LINQ-to-SQL or the Entity Framework, you can simply drag the tables you need onto the designer, and you'll be ready to query the Membership tables.
Here's a little sample on usage
Add this snippet to your repository responsible for Profile/Account information.
public aspnet_User GetUser()
{
MembershipUser user = Membership.GetUser();
return db.aspnet_Users.SingleOrDefault(u => u.UserId == user.ProviderUserKey);
}
Then inside your models, you can get the user and access the other information stored in your UserProfiles table.
AccountRepo accountRepo = new AccountRepo();
aspnet_User user = accountRepo.GetUser();
string Address = user.UserProfile.Address; // bingo!
And that's pretty much it!
This is obviously a simple example, and you should be checking if the user is null and you could also create a class responsible for returning the necessary information about a user, implement caching, etc..
I would start from here:
Managing Users by Using Membership
Managing Authorization Using Roles
Also a great article series (18 articles!!!) is from Scott Mitchell at 4GuysFromRolla.
The ASP.NET membership model is desgned to have a pluggable architecture. You can write you own MembershipProvider implementation that best suit your needs.
Even if most of the samples you will find on the net regards ASP.NET web forms, there are only very small differences when used with MVC.
If you're still looking for insight into this, I just ran across the fact that in MVC 4 WebPages sites, there's a provider called the SimpleMembership provider. It gives more control to the developer of the Users, Roles and Membership info stored on websites. More here:
http://blog.osbornm.com/archive/2010/07/21/using-simplemembership-with-asp.net-webpages.aspx

Resources