ASP.NET MVC 5 API, Changing a class in GET function - asp.net-mvc

I'm working on a dotnet mvc5 application. Here's a function from my api of customer controller
public IHttpActionResult GetCustomers()
{
var customerDtos = _context.Customers.ToList().Select(Mapper.Map<Customer, CustomerDto>);
return Ok(customerDtos);
}
I need to add "TYPEAHEAD" plugin to my application. The video series/instructor I'm following says to make the function code change to
public IHttpActionResult GetCustomers(string query = null)
{
var customersQuery = _context.Customers
.Include(c => c.MembershipType);
if (!String.IsNullOrWhiteSpace(query))
customersQuery = customersQuery.Where(c => c.Name.Contains(query));
var customerDtos = customersQuery
.ToList()
.Select(Mapper.Map<Customer, CustomerDto>);
return Ok(customerDtos);
}
in order to make "TypeAhead" plug in work on my view.
The only problem is previously while creating customers I didn't feel the need to add "MembershipType" class to my customer. So how do I use the new code without MembershipType. Is there any other attribute I can replace it with? Name, ID etc.

.Include(c => c.MembershipType);
essentially means that you also want to include the 'child' collection of MembershipType
See here for more information on Loading Related Entities
For your case, you can simply omit this.
public IHttpActionResult GetCustomers(string query = null)
{
var customersQuery = _context.Customers;
if (!String.IsNullOrWhiteSpace(query))
customersQuery = customersQuery.Where(c => c.Name.Contains(query));
var customerDtos = customersQuery
.ToList()
.Select(Mapper.Map<Customer, CustomerDto>);
return Ok(customerDtos);
}
You don't need to replace it with anything.
customersQuery is then an IQueryable<Customer> which the rest of this code can append Where clause to.
It is not executed against the database until the ToList call.

Related

Cast List<ViewModel> to ViewModel?

I want to preface this by saying I am new to working with models. Please forgive me if this question has a simple answer.
I have been struggling to revert a listed view model back to view model. To give some background, I have a search form being passed to a model coming from my ActionResult and am then getting a filter out the results.
[ Controller ]
public ActionResult GetFilters(MembershipVM model)
{
var uDataList = new List<MembershipVM>();
model = _service.GetFilters(model);
return View("SendEmail", model);
}
[ Service ]
public List<MembershipVM> GetFilters(MembershipVM model)
{
var query = _context.Members.Where(f => f.Deleted == 0).AsQueryable();
var members = _context.Members.ToList();
query = query.Where(f => agencyTypes.Contains(f.AgencyType));
var uDataList = new List<MembershipVM>();
foreach (var member in members)
{
var uData = new MembershipVM();
uData.Email = member.Email;
uData.AgencyType = member.AgencyType;
...
uDataList.Add(uData);
}
return uDataList;
}
How can I cast the List from "_service.GetFilters" to MembershipVM? Is there a better/easier way to get the results as an object from the "_service.GetFilters" service?
Thanks so much in advance!
Daisy
I am not sure what you are trying to do here. First you get the results of your filter from this code:
model = _service.GetFilters(model);
And the definition of your method is this:
public List<MembershipVM> GetFilters(MembershipVM model)
So you would expect that this is a list of results. In short, a collection of results.
Now if you want to pass it on your ActionResult as one entity only, then getting one of your results will do the trick:
return View("SendEmail", model.Take(1).SingleOrDefault());
But why do you need to pass one entity only? But that should work with your current requirement.

Passing SItecore Item ID to Model from Controller

I am creating products from a product template. Each time a customer selects a product to view information about, the data from that product needs to get loaded. I have created a controller, model and view. The model is generated with TDS. I need to pass the item id to the [SitecoreId] from the controller. Here is the code I am using:
From the layout:
#{var id = Sitecore.Data.ID.Parse("{74A67488-8E33-47E2-86F5-25AD23FDF3D3}"); }
#Html.Sitecore().ControllerRendering("ProductOverview", "Index", new { ItemId = #id })
The controller:
public class ProductOverviewController : Controller
{
private readonly IMvcContext _mvcContext;
public ProductOverviewController(IMvcContext mvcContext)
{
_mvcContext = mvcContext;
}
// GET: ProductOverview
public ActionResult Index()
{
var itemId = string.Empty;
var rc = RenderingContext.CurrentOrNull;
if (rc != null)
{
var parms = rc.Rendering.Properties;
itemId = parms["ItemId"];
}
var dataSource = _mvcContext.GetContextItem<ProductOverviewModel> ();
return View(dataSource);
}
}
The itemId var has the correct id that I am passing from the layout (hard coded for now). From here I am at an absolute loss on how to get that into the model. I have tried dozens of suggestions from searches but the model always uses the current item (as set by GlassBase in the model itself) as opposed to the product id that contains the data for that product.
Is what I want to do even possible? Can the [SitecoreId] even be overridden?
The line where you are setting the value for dataSource using Glass Mapper is where you'll want to make your change..
Glass Mapper lets you use a number of different options to get the Item and cast to your "type" which looks to be ProductOverviewModel currently.
you can use the following for example (notice that I've used .SitecoreService.GetItem instead of .GetContextItem ):
//pass the GUID into here (you'd need to cast to a Guid first instead of ID)
var dataSource = _mvcContext.SitecoreService.GetItem<ProductOverviewModel>(guid);
//or if you wanted to get your ID as a Sitecore Item you could use
var dataSource = _mvcContext.SitecoreService.GetItem<ProductOverviewModel>(item.Paths.Path);

How to get list of all ApplicationUsers who are in certain Role from database by LINQ expression?

I want to get:
list of ApplicationUsers who are in role "NormalUser" to anybody
list of all ApplicationUsers only to Admins only.
I did this:
// GET: ApplicationUsers
public ActionResult Index() {
// if you are Admin you will get all users
if (User.IsInRole("Admin"))
return View(db.Users.ToList());
//if you are somebody else(not Admin) you will see only list of NormalUsers
//HERE I GET ERROR
var list = db.Users.Where(x => UserManager.IsInRole(x.Id, "NormalUser")).ToList(); // here I get error
return View(list);
}
UserManager inside code above is: UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
But unfortunately my LINQ expresiion is incorrect. I get error:
LINQ to Entities does not recognize the method 'Boolean IsInRole[ApplicationUser,String](Microsoft.AspNet.Identity.UserManager`2[WebApplication2.Models.ApplicationUser,System.String], System.String, System.String)' method, and this method cannot be translated into a store expression.
Question: How to correctly get list of users who are in role "NormalUser"?
The UserManager.IsInRole function isn't supported at the database, but if your application can bear the weight of pulling the whole User table back from the database before applying your filter then you can just add a ToList between your Users table reference and your Where filter, i.e.
var list = db.Users.ToList().Where(x => UserManager.IsInRole(x.Id, "NormalUser")).ToList();
I reached here for a good quick answer but could not find one. So decided to put on what I got for any other visitor who comes here. To get the List of Users in any particular Role, one can use this code.
public async Task<ActionResult> Index()
{
List<ApplicationUser> appUsers=new List<ApplicationUser>();
await Task.Run( () =>
{
var roleManager = new RoleManager<IdentityRole>( new RoleStore<IdentityRole>( db ) );
var adminRole=roleManager.FindByName("Admin");
appUsers = db.Users.Where( x => x.Roles.Any( s => s.RoleId == adminRole.Id ) ).ToList();
} );
return View( appUsers );
}
It would be useful to know how Roles and Application users relate.
If the user can only belong to one role, it would be fine for you to do something like this:
var list = db.Users.ToList().Where(x => x.Role == "NormalUser").ToList();
Id the user can be part of multiple roles, it would look something more like this:
var list = db.Users.ToList().Where(x => x.Roles.Contains("NormalUser")).ToList();
Hope this helps.

EF Code First to create multiple databases dynamically

Is it possible to generate different databases according to a specific parameter?
My final goal is john.domain.com => create john db, paul.domain.com => create paul db
How could I achieve this using EF6 code first, MVC5? Could model first do it?
Yes you can change the connection string at runtime, something like.
Need to add reference to System.Data.
public static class ConnectionStringExtension
{
public static void ChangeDatabaseTo(this DbContext db, string newDatabaseName)
{
var conStr = db.Database.Connection.ConnectionString;
var pattern = "Initial Catalog *= *([^;]*) *";
var newConStr = Regex.Replace(conStr, pattern, m =>
{
return m.Groups.Count == 2
? string.Format("Initial Catalog={0}", newDatabaseName)
: m.ToString();
});
db.Database.Connection.ConnectionString = newConStr;
}
}
Usage.
using (var db = new AppContext())
{
// Uses it just before any other execution.
db.ChangeDatabaseTo("MyNewDatabase");
}

How to improve my Entity Framework , to join several database queries into single query

I have the following ActionFilter class, to implement my custom authorization system:-
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class CheckUserPermissionsAttribute : ActionFilterAttribute
{
Repository repository = new Repository();
public string Model { get; set; }
public string Action { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
string ADusername = filterContext.HttpContext.User.Identity.Name.Substring(filterContext.HttpContext.User.Identity.Name.IndexOf("\\") + 1);
if (!repository.can(ADusername,Model,Action))
{
filterContext.Result = new HttpUnauthorizedResult("You cannot access this page");
}
base.OnActionExecuting(filterContext);
}
}
The above class will call the following repository method:-
public bool can(string user, string Model, string Action)
{
bool result;
bool result2;
int size =tms.PermisionLevels.Where(a5 => a5.Name == Action).SingleOrDefault().PermisionSize;
var securityrole = tms.SecurityroleTypePermisions.Where(a => a.PermisionLevel.PermisionSize >= size && a.TechnologyType.Name == Model).Select(a => a.SecurityRole).Include(w=>w.Groups).Include(w2=>w2.SecurityRoleUsers).ToList();
foreach (var item in securityrole)
{
result = item.SecurityRoleUsers.Any(a => a.UserName.ToLower() == user.ToLower());
var no = item.Groups.Select(a=>a.TMSUserGroups.Where(a2=>a2.UserName.ToLower() == user.ToLower()));
result2 = no.Count() == 1;
if (result || result2) {
return true;
}}
return false;
}
But inside my repository method , I am doing the following:-
Query the database and include all the Groups & SecurityRoleUsers when executing the .tolist()
Then filter the returned records insdie the server, based on the foreach loop.
But this will cause the following drawbacks:-
If I have many Groups and SecurityRoleUsers, then I will be getting them all from the DB, and then filter the result on the server.
And since this code will be executed whenever an action method is called, as it Is a security attribute at the begging of the controller class. So this might not be very efficient.
So my question is whether I can join all the queries inside the repository method to be single query , and do all the work on the Database and just return true or false to the server ?
The associated tables looks as follow:-
Ideally remove this foreach.
Try riding with Linq to Sql.
You should be more comfortable because it resembles SQL.
This link has several examples.
http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b
Att
Julio Spader
wessolucoes.com.br
Use linq.
Ideally you should only have one line of code after you got the size value. e.g.
int size =tms.PermisionLevels.Where(a5 => a5.Name == Action).SingleOrDefault().PermisionSize;
var result = //One line of code to determine user authenticity
return result;
I think you should design you database in the way that join queries are easy to do. So you don't have to perform more than one select.
Try code-first EF, which links tables very easily.
You need to take care with Lazy Loading. If not used correctly, it will make a query to the database each object segmentation, especially in your foreach. With that already has a good improvement.
Take a look at this article. I think it will help you too.
http://www.sql-server-performance.com/2012/entity-framework-performance-optimization/
Att
Julio Spader
wessolucoes.com.br

Resources