Sessions in .net6 after upgrading from .net4.8 - c#

I just upgraded my .net 4.8 MVC web app to .net6.
I used Sessions to store objects.
for example the User class:
public class User
{
[Key]
public string UserID { get; set; }
public string TenantId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string MobilePhone { get; set; }
public bool IsEnabled { get; set; }
public virtual ICollection<Department> Departments { get; set; }
}
This is how I set the session:
Session[Consts.CURRENTUSER] = userFromDb;
This is how I use it:
User _currentUser = Session[Consts.CURRENTUSER] as User;
Now, after the upgrade it does not compile. I get the following error:
Error CS0103 The name 'Session' does not exist in the current context
If i use the following HttpContext.Session[Consts.CURRENTUSER] as User it still does not allow the the above use.
Will appreciate an example on how I will be able to use the above scenario in .net core.

after reading Microsoft docs, I followed this guide from step 4 to allow the usage of Sessions.
Then, in order to use complex objects in .net core I followed this link which provided an extension method that implementing the use of complex objects in sessions.

Related

Multitier architecture and Identity. Why to use UserManager and RoleManager?

Microsoft Identity introduces UserManager<T> and RoleManager<T> classes to interact with AspNetUsers, AspNetRoles and the other database tables. But why we should use them? Maybe it is a better solution to scaffold the database and work with its tables directly using the Entity Framework and forget about classes UserManager<T> and RoleManager<T>?
Why am I asking?
I my application I want to follow the multitier architecture.
I started with creating the DTO-class for the user:
public class UserDto
{
public string Id { get; set; }
public string UserName { get; set; }
...
public List<RoleDto> Roles { get; set; }
}
public class RoleDto
{
public string Id { get; set; }
public string Name { get; set; }
...
}
Type IdentityUser I want to map into UserDto, type IdentityRole - into RoleDto.
As you can see, in UserDto I want to store roles of a user.
Now let's have a look at the IdentityUser type: link.
It contains a lot of properties, but it doesn't have roles of the user.
So, when mapping IdentityUser into the UserDto, I need to work with RoleManager<T> to get roles of the user. I think, it's a dirty solution.
My idea
We can forget about UserManager<T> and RoleManager<T> types. We can simply scaffold the database and work with it using the Entity Framework.
After scaffolding of database I have the following:
public partial class AspNetUser
{
public string Id { get; set; }
public string UserName { get; set; }
public string NormalizedUserName { get; set; }
public string Email { get; set; }
public string NormalizedEmail { get; set; }
public bool EmailConfirmed { get; set; }
public string PasswordHash { get; set; }
public string SecurityStamp { get; set; }
public string ConcurrencyStamp { get; set; }
public string PhoneNumber { get; set; }
public bool PhoneNumberConfirmed { get; set; }
public bool TwoFactorEnabled { get; set; }
public DateTimeOffset? LockoutEnd { get; set; }
public bool LockoutEnabled { get; set; }
public int AccessFailedCount { get; set; }
public virtual ICollection<AspNetUserClaim> AspNetUserClaims { get; set; }
public virtual ICollection<AspNetUserLogin> AspNetUserLogins { get; set; }
public virtual ICollection<AspNetUserRole> AspNetUserRoles { get; set; }
public virtual ICollection<AspNetUserToken> AspNetUserTokens { get; set; }
}
// AspNetUserClaim, AspNetUserLogin, AspNetUserRole and AspNetUserToken
I introduced only AspNetUser class to be short. As you can see, it has a property AspNetUserRoles - roles of the user. It's great, because now it's really simple to map this class into the UserDto.
Question
Is it a good idea to scaffold the database and don't work with UserManager and RoleManager classes?
Maybe you can introduce a better solution?
Why do you think that this is a good idea? What would you gain by re-writing something like identity?
From the Introduction to Identity on ASP.NET Core
ASP.NET Core Identity:
Is an API that supports user interface (UI) login functionality.
Manages users, passwords, profile data, roles, claims, tokens, email confirmation, and more.
It's not just database access. It is also code that manages login functionality, secure token creation, secure password management and much more.
You need to take all of the above into consideration if you create a custom system, have an external auditor to pen-test your solution (even though this is a good idea whatever choice you make), unit test, performance test etc.
All the above is already done. You can easily customize the identity with various hook points too.
BTW, identity uses ef to access the datastore already by default.
Do structure your multilayer application, but leave identity out of it. It is a horizontal concern and it's presence is there to simplify your development and let you worry about your business needs only.

Azure Mobile Services linked tables

I have an application with 3 tables
Items, Clients, Types
Each item can be associated to one client and one type
This was originally stored using SQL Server CE and I have now pushed the data up to azure mobile services.
I am attempting to reuse this data in a new windows universal application written in c#.
In Azure I created 3 tables itemtable clienttable typetable, in itemtable I have columns for the id of the clienttable and typetable entry (item.clienttableid = clienttable.id).
The Azure mobile services backend is set to javascript, I chose this as I thought it would be more compatible across platforms than the .net backend is that true?
I want to be able to read all the items from the items table and reference the properties of the client and type table from the item (e.g. item.client.clientname)
Is there a way of defining my class so that when I request all items from azure I also get the associated type and client.
This is how I have my class so far
public class ItemTable
{
public string Id { get; set; }
[JsonProperty(PropertyName = "itemdate")]
public DateTime ItemDate { get; set; }
[JsonProperty(PropertyName = "itemamount")]
public decimal ItemAmount { get; set; }
[JsonProperty(PropertyName = "itemdescription")]
public string ItemDescription { get; set; }
[JsonProperty(PropertyName = "ItemClientID")]
public ClientTable Client { get; set; }
[JsonProperty(PropertyName = "ItemTypeID")]
public TypeTable Type { get; set; }
}
public class ClientTable
{
public string Id { get; set; }
[JsonProperty(PropertyName = "clientname")]
public string ClientName { get; set; }
}
public class TypeTable
{
public string Id { get; set; }
[JsonProperty(PropertyName = "typename")]
public string TypeName { get; set; }
}
I have seen this http://blogs.msdn.com/b/carlosfigueira/archive/2013/08/23/complex-types-and-azure-mobile-services.aspx
but cannot wrap my head around how to adapt it to my situation
The Azure mobile services backend is set to javascript, I chose this as I thought it would be more compatible across platforms than the .net backend is that true?
No matter which time of backend you are using, it will be easy in each case because Azure Mobile Services Team created a "Azure Mobile Services SDK" for client applications, which you can install by "Manage Nuget Package".
This is how I have my class so far
I saw the model and next time you can show the class diagram from your model, learn about in this article Class diagram: a easy way to understand code. If this model is for the client/.Net Backend, I think it is not completely correct because you said this
3 tables Items, Clients and Types. Each item can be associated to one client and one type
In the ItemTable class you need to have something like it
public ClientTable ClientId { get; set; }
[ForeignKey("ClientId")]
[JsonProperty(PropertyName = "ItemClientID")]
public virtual ClientTable Client { get; set; }
public string TypeTableId { get; set; }
[ForeignKey("TypeTableId")]
[JsonProperty(PropertyName = "ItemTypeID")]
public virtual TypeTable TypeTable { get; set; }
Note: In client apps remove the attribute ForeignKey.
If you have doubts I recommend to see this
Azure Mobile Services Samples - Samples and articles to help developers to use Azure Mobile Services

Using ASP.Net Identity with model classes

I'm new to ASP.Net Identity, and I'm looking for a good tutorial for using Identity in conjunction with other classes in my model.
As an example I have a basic Ratings class that looks like this (from a project not using Identity)
public class Rating
{
public int Id { get; set; }
public Product Product { get; set; }
public User User { get; set; }
public int Stars { get; set; }
public string Comment { get; set; }
public bool Active { get; set; }
}
And a User Class that looks a bit like this
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public ICollection<Rating> Ratings { get; set; }
}
Looking for a way to achieve the same with Identity. My test project is set up with MVC5, and code first
The recommended solution is to add the properties you need to the ApplicationUser class
You can also use your own "User table", in your case that would be the User class. You'd have to inherit from IdentityUser.
This article has examples of how to do both.
I agree with Rui.
Here is a site that will teach you How to Extend Identity Accounts and also Implement Based Authentication. When I was starting with Identity, that site taught me a lot.
As a related hint: Watch out when you implement a Unit of Work pattern in your project. ASP.NET identities datacontext needs to be the same as the Uow datacontext, otherwise the whole think will crash.
A good starting point may be this: ASP.NET Identity with Repository and Unit of Work

MVC Code First: One-to-many relationship between own model and SimpleMembership user

I am currently working on an event calendar website and I am still a novice when it comes to ASP.NET. I am using the MVC4 Framework, as well as the EntityFramework (CodeFirst) and the SimpleMembershipProvider, which comes with the MVC4 template. I am also using Migrations - If that is from any interest.
What I've got so far
I do currently have two models, with a one-to-many relationship, which work just fine:
_Events.cs (had to name it that way, because event is reserved)
public class _Event
{
public int _EventId { get; set; }
public string Name { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public virtual List<Comment> comments { get; set; }
}
Comment.cs
public class Comment
{
public int CommentId { get; set; }
public string Text { get; set; }
public int _EventId { get; set; }
public virtual _Event _Event { get; set; }
}
The problem
Now, I would like to add another one-to-many relationship between Comment and the User from the Membership model, but can't seem to figure out how to do so.
The goal I would like to archieve is, that I can have a list of commments for each event and print out the user information for each comment. I tried several things, but could not get it to work yet. My last attempt looks like this:
public class Comment
{
// snip - see above
public virtual UserProfile User { get; set; }
}
I would like to thank you very much for any help in advance.
You need to have UserId in your Comments as so.
public class Comment
{
// snip - see above
public int UserId {get; set;}
public virtual UserProfile User { get; set; }
}
You will also need to set the relationship between your Comment and your User so in your account controller have something like this.
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
}
In an ASP.net MVC project if you want to use default Microsoft Membership Provider, note that you need to implement membership system like role provider to have relationships and navigation and more functionalists between your created models and membership system. Microsoft Stores User related info at the separate place (like databases in App_Data folder) in your project.
So you need to store other models to Microsoft storage place, work with Microsoft functions directly and set connection string for this purpose OR implement Microsoft Membership to store User Info at relevant database like this NUGET Package that implements codefirst membership provider in C#. You can install this package and learn to write your own membership provider. More helps will be found by searching 'custom membership provider for MVC or aspnet membership provider'.

Adding a controller with read/write actions and views using entity framework results in a warning

Hi I am following the steps from this tutorial :
http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application
When I try to add a controller that use one of my models , I get this warning:
This is the model based on witch I am tryng to create the controller:
public class Student
{
public int StudentID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
And this are the setting that I am adding when I try to create it :
I am not really sure what that warning is telling so I do not know If I posted the correct information needed in order to solve it.If anything else is needed I will post it later.
How can I solve this problem?
For some reason changing the provider from System.Data.SqlServerCe.4.0 to System.Data.SqlClient seems to solve this problem.

Categories