How to add Identity 2.0 users to an object - asp.net-mvc-5

So I am trying to grasp EF6 and it's use of Identity 2.0 for making a many to many relationship. It is Visual Studio 2013 and the MVC 5 template.
I have a fresh MVC app with the following models:
public class Meeting
{
public Guid MeetingID { get; set; }
public string Title { get; set; }
public virtual ICollection<ApplicationUser> Attendees { get; set; }
}
public class ApplicationUser : IdentityUser
{
public ICollection<Meeting> Meetings { get; set; }
}
Then I scaffold a controller and views for Meetings. Now, for instance, if I just wanted to add every user as an attendee to my meeting, I would imagine that I could modify the Create action to look like the following:
public ActionResult Create(Meeting meeting)
{
if (ModelState.IsValid)
{
meeting.MeetingID = Guid.NewGuid();
db.Users.ForEachAsync(u => meeting.Attendees.Add(u));
db.Meetings.Add(meeting);
db.SaveChanges();
return RedirectToAction("Index");
}
else...
}
However I don't think it's working because I don't see it in my LocalDB and if I add this to the detail view for a meeting I get no results:
#{foreach (var item in Model.Attendees)
{
<li>#item.UserName</li>
}}
As a final note, I have two users in the LocalDB, test and test2.
What tutorial or documentation will allow me to make this work?
* Edit *
So I have tried your suggestion (I'll admit, I am unfamiliar with async and await and how to implement it), and I had to modify the controller to allow me to use await so I'm not sure if I'm doing this correctly now, but I got the following to compile and I get run time error of 'object reference not set to an instance of an object' :
public async Task<ActionResult> Create(Meeting meeting)
{
if (ModelState.IsValid)
{
meeting.MeetingID = Guid.NewGuid();
await db.Users.ForEachAsync(u => meeting.Attendees.Add(u));
db.Meetings.Add(meeting);
db.SaveChanges();
(is it possible I'm missing some setup of my model on Entity Framework? The project is exactly the code shown above plus defaults.)

You're going to kick yourself :)
(Drumroll)
You forgot to add await before your ForEachAsync line:
await db.Users.ForEachAsync(u => meeting.Attendees.Add(u));
Without await the application happily continues on and saves the record, all before that async process has completed.
UPDATE
Most likely you haven't initialized the Attendees collection. Just set it to a new List<ApplicationUser> in your constructor.

Related

SwaggerRequestExample attribute does not work in ASP.NET MVC 5 (.NET Framework 4.5.2)

I am toying with Swashbuckle.Examples package (3.10.0) in an ASP.NET MVC project. However, I cannot make request examples appear within the UI.
Configuration (SwaggerConfig.cs)
public static void Register()
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
GlobalConfiguration.Configuration
.EnableSwagger(c => {
c.SingleApiVersion("v1", "TestApp.Web");
c.IncludeXmlComments(string.Format(#"{0}\bin\TestApp.Web.xml", System.AppDomain.CurrentDomain.BaseDirectory));
c.OperationFilter<ExamplesOperationFilter>();
c.OperationFilter<DescriptionOperationFilter>();
c.OperationFilter<AppendAuthorizeToSummaryOperationFilter>();
})
.EnableSwaggerUi(c => { });
}
Request example classes
public class EchoRequestExample : IExamplesProvider
{
public object GetExamples()
{
return new EchoInput { Value = 7 } ;
}
}
public class EchoInput
{
public int Value { get; set; }
}
Action
[HttpGet]
[Route("Echo")]
[CustomApiAuthorize]
[SwaggerRequestExample(typeof(EchoInput), typeof(EchoRequestExample))]
[ResponseType(typeof(EchoServiceModel))]
public HttpResponseMessage Echo([FromUri] EchoInput model)
{
var ret = new EchoServiceModel
{
Username = RequestContext.Principal.Identity.Name,
Value = value
};
return Request.CreateResponse(HttpStatusCode.OK, ret);
}
Swagger UI shows xml comments and output metadata (model and an example containing default values), but shows no request example. I attached to process and EchoRequestExample.GetExamples is not hit.
Question: How to make SwaggerRequestExample attribute work in ASP.NET MVC 5?
Note: Windows identity is used for authorization.
I received an answer from library owner here:
Swagger request examples can only set on [HttpPost] actions
It is not clear if this is a design choice or just a limitation, as I find [HttpGet] examples also relevant.
I know the feeling, lot's of overhead just for an example, I struggle with this for a while, so I created my own fork of swashbuckle, and after unsuccessful attempts to merge my ideas I ended up detaching and renaming my project and pushed to nuget, here it is: Swagger-Net
An example like that will be:
[SwaggerExample("id", "123456")]
public IHttpActionResult GetById(int id)
{
Here the full code for that: Swagger_Test/Controllers/IHttpActionResultController.cs#L26
Wondering how that looks like on the Swagger-UI, here it is:
http://swagger-net-test.azurewebsites.net/swagger/ui/index?filter=IHttpActionResult#/IHttpActionResult/IHttpActionResult_GetById

Entity Framework deleting object upon Update

I have a problem where Entity Framework (Core) is deleting an object upon update. I think this is related to Automapper (map DTO Resource to object). I have other objects mapped the exact same way as this object and updates work just fine.
public async Task<IActionResult> UpdateFeedback(Guid Id, [FromBody] FeedbackResource feedbackResource)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
//removing or else get a tracking error with EF
feedbackResource.FeedbackType = null;
var feedback = await feedbackRepository.GetFeedback(Id);
if (feedback == null)
return NotFound();
//if I use this line to map, EF will delete the object upon save.
mapper.Map<FeedbackResource, Feedback>(feedbackResource, feedback);
// if I map manually, i get no error
//feedback.Title = feedbackResource.Title;
//feedback.Details = feedbackResource.Details;
//feedback.IsGoodFeedback = feedbackResource.IsGoodFeedback;
//feedback.IsReviewed = feedbackResource.IsReviewed;
//feedback.FeedbackTypeId = feedbackResource.FeedbackTypeId;
//if(feedbackResource.IsReviewed){
// feedback.ReviewDate = DateTime.Now;
// feedback.ReviewedBy = UserId;
//} else {
// feedback.ReviewDate = null;
// feedback.ReviewedBy = null;
//}
await uow.CompleteAsync();
return Accepted(feedback);
}
I have no idea what to troubleshoot here and cannot see this issue on any google search.
I was faced with a similar situation (ef core 1.1). I will assume that your problem is similar to mine.
Also a similar problem is described here
I have the following models:
1) ApplicatonUser - standard user from EF
2) AnyDAL - any class in DB, which have link to user
public class AnyDAL
{
public long Id { get; set; }
public long UserId { get; set; }
public ApplicationUser User { get; set; }
}
3) AnyDTO - model that comes from the browser side. Like your's [FromBody] FeedbackResource feedbackResource
public class AnyDTO
{
public long Id { get; set; }
public long UserId { get; set; }
/// It is root of all evil. See below.
/// And yes, it is bad practice.
public ApplicationUser User { get; set; }
}
Scenario:
1) get AnyDAL from the database;
2) map AnyDTO on AnyDAL using AutoMapper _mapper.Map(DTO, DAL);
3) SaveChanges()
In one case, SaveChanges() leads to Delete, in other to Update.
What we should know: in my case property AnyDTO.User is always null after deserialization.
The choice between delete and update depends on the value of property AnyDAL.User before mapping:
1)AnyDAL.User is null - we get Update.
2)AnyDAL.User is NOT null - we get Delete.
In other words. If property AnyDAL.User changed from some value to null - entity will be deleted. Despite the fact that AnyDAL.UserId remains the same.
There is two ways to solve it:
1) Remove property User from AnyDTO;
2) Property AnyDTO.User should always has value.
For me, this issue ended up being caused by an interaction between the automapper and EntityFramework. This was described well by Automapper creating new instance rather than map properties
This is a little old but I ran into the same issue with EF Core 2.2 and based on this
EntityFrameworkCore it is still an issue in 3.0
The issue seems to be that the navigation property being null is causing the entity to be deleted.
I was able to resolve by configuring lazy loading
Install this package
Microsoft.EntityFrameworkCore.Proxies
Enable lazy loading in the configuration
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseLazyLoadingProxies();
for me, this was resolved if I marked as Detached the entity, use automapper to map, then mark entity as Modified.
_context.Entry(product).State = EntityState.Detached;
_mapper.Map<ProductVM, Product>(viewModelProduct, product);
_context.Entry(product).State = EntityState.Modified;
_context.SaveChanges();

How to create service in C# which will perform some operations asynchronously in scenario mentioned below?

I have WebApi Controller as mentioned below. This controller having Update method which will internally call service called CustomerDataService to Update Customer Records.Assume we have n customer records to update.
UpdateMethod in CustomerDataService will perform update and return the update response.
I have requirement to do some heavy processing asynchronously after the update response like manipulating data / managing the data cache. As this processing is time consuming not relevant to the consumer of this API as Update successfully happens So I have to perform this asynchronously. Can I do this with C# with the given scenario? Please suggest.
Note: I do not want to create any batch job to achieve this as I want to perform operation(s) which are user session specific.
Controller
public class CustomerController : ApiController
{
[HttpGet]
public string UpdateCustomer()
{
ICustomerService obj = new CustomerDataService();
return obj.UpdateCustomer(GetCustomerList());
}
private List<CustomerModel> GetCustomerList()
{
return new List<CustomerModel>()
{
new CustomerModel
{
CustomerId="1",
Name="John",
Category="P1"
},
new CustomerModel
{
CustomerId="2",
Name="Mike",
Category="P2"
}
//....n Records
};
}
}
Model
[Serializable]
[DataContract]
public class CustomerModel
{
[DataMember]
public string CustomerId { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public string Category { get; set; }
}
Interface and CustomerDataService
public interface ICustomerService
{
string UpdateCustomer(List<CustomerModel> customerList);
}
public class CustomerDataService : ICustomerService
{
public string UpdateCustomer(List<CustomerModel> customerList)
{
//Do Data Processing - DB Call
//Return Confirmation Message
return "Data Updated Successfully!!!";
//Needs to perform some processing asynchronously i.e. Call ProcessResults()
}
private void ProcessResults()
{
//DO Processing
}
}
What you are looking for is using async/await in c#, see this article on Microsofts website: Asynchronous Programming with Async and Await. Here is another article with plenty of examples: C# Async, Await.
Once you understand how this works it will be very easy to change your code to take advantage of this pattern. Let us know if you have specific questions or run into problems.

Can't seem to expand an Image Navigation property with Breeze JS

I am using MVC, Entity Framework, Durandal and Breeze JS. I've got a user which looks like such (simplified):
public class User : EntityBase<Guid>, IAggregateRoot
{
public Guid Id { get; set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[ForeignKey("UserImage")]
public virtual Guid? ImageId { get; set; }
public virtual UserImage UserImage { get; set; }
}
The UserImage class looks like such. I know I should limit the size of the Image. (Maybe this is the issue?):
public class UserImage
{
public Guid Id { get; set; }
[MaxLength]
public byte[] Image { get; set; }
}
I've got an api function on the server to get the current user:
public IQueryable<User> GetCurrentUser()
{
IPrincipal principal = HttpContext.Current.User;
var users = _uow.Users.FindBy(u => u.UserName.Equals(principal.Identity.Name));
if (!users.Any())
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized));
}
return users;
}
And two calls on the client which get the current user. The first is in the shell:
function loadCurrentUser() {
return uow.CurrentUser.all().then(function (newUser) {
log('Welcome to the Site ' + newUser[0].FullName() + '!', newUser[0], true);
config.CurrentUser(newUser[0]);
return true;
});
}
The second is in a ManageUser viewmodel:
function activate() {
return uow.CurrentUser.all(['UserImage']).then(function (user) {
self.CurrentUser(user[0]);
return $.when(init()).then(boot());
}).fail(function() {
return router.activate('accounts/login');
});
}
Now I can load an Image into the ManageUser page and save and in fiddler it shows that the ImageId and Image are being sent across to the server. Then I checked the BeforeSaveEntity intercept and shows two entities being saved.
Updated User with ImageId set
New UserImage
The data is also visible in the database. Now when I refresh the Manage User page I can see the two GetCurrentUser calls in fiddler.
From the shell call I can see that the User is being returned and an ImageId is set but no UserImage was sent over because didn't expand the query.
From the Manage User call I see the User is returned but only the ImageId is sent over and the Image object was OMITTED from the JSON.
Has anyone come across this issue with images? All my other expands appear to be working correctly. Does anyone have any examples on using breeze to save just the filepath to the image and possibly using windows azure for media storage?
I know this probably won't answer your question but I would propose not sending the byte array to the client and rather have an Image Handler on the server side that takes an ImageId as a parameter and then return the image with the relevant Content Type set. An example of this can be found here.
By using this approach you could reference your image from HTML using an img tag with the source set to the Image Hander with the relevant ImageId.
An example using knockout for data binding would be:
<a data-bind="attr: {href: '/Image/' + User.ImageId()}"></a>
This approach enables you to easily add caching on both the server and client which will improve performance. It also removed the need to convert the byte array to an image on the client side, which may or may not be a pain.
Edit:
When saving the managed user, post the Image to an Upload action on the ImageHandler (have a look at this article). This action must return the new Id of the image. After you've received the new Id, update the User.ImageId on client side and call SaveChanges on breeze.

How do I configure the Users context/table?

With the new ASP.NET MVC 5 Preview released, how do I configure the Users context/table?
In MVC 4 I would just use my own User class and then point the WebSecurity initialize to it, tike this:
WebSecurity.InitializeDatabaseConnection(connectionString, "System.Data.SqlClient", userTableName, userIdColumn, userNameColumn, autoCreateTables);
I wish to add additional properties to the Users class - how?
I think, this can solve your issue:
In Models \ IdentityModels.cs you can redefine your own User model:
public class ApplicationUser : IdentityUser
{
/* identity field from database */
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
[Required]
public bool Internal { get; set; }
public string UserFullName { get; set; }
public string UserEmail { get; set; }
public ApplicationUser()
: base()
{
Internal = false;
}
public ApplicationUser(string userName)
: base(userName)
{
Internal = false;
}
}
now you can change mapping of defaults AspNet tables using OnModelCreating() overridding and ToTable() methode:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// Change the name of the table to be Users instead of AspNetUsers
modelBuilder.Entity<IdentityUser>().ToTable("User");
modelBuilder.Entity<ApplicationUser>().ToTable("User");
modelBuilder.Entity<IdentityRole>().ToTable("Role");
modelBuilder.Entity<IdentityUserClaim>().ToTable("User_Claim");
modelBuilder.Entity<IdentityUserLogin>().ToTable("User_Login");
modelBuilder.Entity<IdentityUserRole>().ToTable("User_Role");
}
}
Finally you will see in the database the following tables:
User, Role, User_Role, User_Claim, User_Login instead of AspNetUsers, AspNetRoles, AspNetUsersRoles, AspNetUsersClaims, AspNetUserLogins.
Of course the User table will contain additional fields: UserId (int identity), Internal, UserFullName and UserEmail.
The UserStore and User classes are there to make EF based implementations easier, but you can always drop down and implement your own custom IUserStore and pass in your own DbContext.
I can provide a more detailed example if you need.
You can download a sample from https://github.com/rustd/AspnetIdentitySample. This is based on the ASP.NET MVC template that shipped with ASP.NET and Web Tools 2013 Preview Refresh (Supports English version of VS2013 Preview only) Once you have this Preview Refresh installed you can do the same for ASP.NET Web Forms and SPA applications.
Following are the steps to Run this project
Open the solution
Build and run
Register a user ---- Notice that the user registration field only has user name and password
Let's ask for a birthdate option from the user while registering an account.
Goto Nuget Package Manager console and run "Enable-Migrations"
Goto Models\AppModel.cs and uncomment BirthDate property in the MyUser class
Goto Models\AccountViewModels.cs and uncomment BirthDate property in RegisterViewModel
Goto AccountController and in Register Action and have the following code var user = new MyUser() { UserName = model.UserName,BirthDate=model.BirthDate }; //var user = new MyUser() { UserName = model.UserName };
Goto Views\Account\Register.cshtml and uncomment the HTML markup to add a BirthDate column
Goto Nuget Package Manager console and run "Add-Migration BirthDate"
Goto Nuget Package Manager console and run "Update-Database"
Run the application
When you register a user then you can enter BirthDate as well

Resources