Web.api Get method to show only selected properties from entity - entity-framework

Let's say I have 3 entities: Advert, User and UserRole. And in Web.Api project GetAllAdverts method.
public IEnumerable<Advert> GetAllAdverts()
{
return repository.GetAll<Advert>();
}
When i enter url ../api/advert I get JSON with all Adverts and data about adverts, but I get all data about user and user role too.
How can I get for example all advert data and only UserName form entity User ?
Is this done by creating DTOs ?
Thanks in advance !

Using DTO's is usually a good idea. It is more work, but it gives you full control and it abstracts out peculiarities of a specific data layer.
In your case, if you really only want UserName you even have to use a DTO, because it is impossible to partly load the User as navigation property from Advert.
If it does not matter that you see all properties of User except its navigation properties (like role), you may also consider to (temporarily) turn off lazy loading for the context in the repository and eager load Advert.User by using Include.

Related

Breeze EFContextProvider per request and based on parameter?

I have a multi-tenant app in which user can select "current company" after they log in.
There is a DB per company but the model is the same, the workflow is the same, and the controller actions are same....The user can switch companies while being logged in and all actions need to be 'directed' to proper DB.
I know it is possible to customize context creation in EFContextProvider<T> by overriding CreateContext() but how do I pass the extra info (parameter, e.g. CompanyId) that would allow me to create context with correct connection string?
Is this possible?
I find the easiest way is to include the tenant id in a custom HTTP header.
Because the tenant id changes during the session, you probably want to create a custom Breeze ajax adapter (wrap the one you're using now) that sets this header dynamically during its implementation of the ajax method.
On the server you fish the header out of the request.
MAKE SURE YOU ARE VALIDATING USER AND HEADER ON THE SERVER

Replacing MVC's built in User objects with Facebook Connect

I have an ASP.NET MVC 3 project where I have NO local user management. I have intergratred Facebook Connect successfully. While this works, it makes my Controllers and Views messy and verbose.
I'd like to replace the default objects such as the User object exposed by Controllers and Views to return my FacebookUser object instead.
Anyone have a better solution than having my Controllers digging around in FacebookWebContex.? It just feels dirty.
Not quite sure which facebook library you are using. But if you impliment IPrincipal and IIdentity in your FacebookUser object, you will be able to set HttpContext.Current.User to that FacebookUser which will allow you to pull that FacebookUser instance from the User property in the controller.

How to create multiple login views using Zend Framework?

I'm new to ZF and need to create multiple login views for each of my 3 user types, employees, employers and admins. Should I use the indexcontroller to serve up the login for the employees and create separate controller classes to handle the employer and admin login pages? How might I utilize JQuery to direct my employer and admin users to the correct login page from the index view?
Thanks much:)
I can give you 2 options.
Modules
Split your Application into logical segments called modules, for those 3 groups each group will receive its own Module.
Each module mimics the well known standard "Application" structure:
module
Controllers
Models
etc
ACL
http://framework.zend.com/manual/en/zend.acl.html
You check which type of user is currently logged and decid via "if()" statements which view should be rendered.
Custom view rendering is done as described by "Lobo":
via
$this->_helper->viewRenderer->setRender('view-name');
If you don't have any user session data, I mean, if you absolutely do not know of which kind the user visiting your page is you simply have to serve 3 links to either a different module or different controller or to one and the same controller but passing the user type as param.
Examples:
Link to module: /modulename/controllername/actionname/
Link to certain controller: /emplyeecontroller/login
Link to general controller handling different params: /logincontroller/login/type/emplyee
There are many possible solutions to achieve your desired aim.
You have to decide which one fits the most into your project.
I would say that this is a bit to open ended to answer in a good way, but I'll try to fill in the blanks with my imagination and give you an answer. I don't use JQuery so I can't give you an answer there unfortunately.
If this is just to handle login I would guess that the logic is more or less the same (and even if it isn't the logic should be in models anyway), and you just want to change the visual appearance, so then you could use the code
$this->_helper->viewRenderer->setRender('view-name');
This code will render the view called /application/views/scripts/controller/*view-name*.phtml by default. Thus you can get whatever variable you use to distinguish the different users and give them the right view.
If there's more differences than just the visual I would probably use different actions within a loginController or something like that.
Then I would use standard indexAction (and thus the view index.phtml as default) for the normal employees, and on that page show some kind of text like "Not an employee? Go to the employers login instead". Employers are then directed to login/employer or something like that which by default will call the employerAction and use the employer view. And then you do something similar with the admin login. the controller will then look something like this
<?php
class LoginController
{
public function indexAction()
{
/*Do login stuff here*/
}
public function employerAction()
{
/*Do login stuff here*/
}
public function adminAction()
{
/*Do login stuff here*/
}
}
Lastly, if there are major differences between how the different users interact with your page, you might consider looking into modules.
You can find all this information at http://framework.zend.com/manual/en/manual.html

ASP.NET MVC passing data between forms

Im pretty new to ASP.NET MVC, trying to figure out my way around.
Currently i return a ViewModel which has a IEnumeable Events as its only property. This ViewModel is StronglyTyped to a UserControl which dislays the IEnumable Events in tabular form.
One of the properties of the Event Model is an XElement, which contains some XML loaded from the DB.
Now i've added a link to the end of the tablular data to be able to view the XML in a separate page. How do i pass this data to another page for viewing?
I would post a request back to the server with some sort of Id for the Event-object and have the receiving end send back the XML related to that Id.
if you're looping through the Event objects in your IEnumerable, you can do something like:
<%= Html.ActionLink("GetXml", "Events", new { id = currentEvent.Id }) %>;
Now create an Action on your EventsController (given that you have one) like so:
public ActionResult GetXml(int id)
and retrieve the XML to pass back to the View
There are basically two ways of bringing data from one page to another using ASP.NET MVC (or any other language/framework which follows the HTTP protocol):
Sessions: Use a session to store the data you need, and load it back up at the next page.
Post the needed data back to the server. This way, the server can hold it and display it on the next page. Posted data usually comes from input or textarea elements. If you use input type="hidden" you can give it a value which represents your data. This way, you can post it back and forth till you arrive where you want.
Besides what Arve is advising, you could also consider TempData.
If you use the Get-Post-Redirect/Forward concept for you app, you could do something like:
GET - Initial Request comes in, Server responds with View and model data. User selects an item which leads to ...
POST - User selects one of the items from #1, triggering a post. That particular item can be fetched from repository, placed in TempData and then...
REDIRECT/FORWARD - The redirect collects the information out of TenpData and uses it as the model for the new View.
here is an example http://www.eworldui.net/blog/post/2008/05/08/ASPNET-MVC-Using-Post2c-Redirect2c-Get-Pattern.aspx

Question regarding fine-grained authorization and MVC2

Background: Completely new to MVC2. Has C# experience, but limited web experience.
I need more fine grained access than simply assigning a Role to a user. The user may have the role at 0+ points in a tree.
/
/Europe
/England
/France
/USA
For example, a user might be moderator of all forums under "Europe" and have access to posting news in France.
The two example controllers have actions as these:
ForumController:
public ActionResult DeletePost(int id) { ... }
NewsController:
[HttpPost]
public ActionResult Post(int treeID, ...) { ... }
How should I approach this? From what I gather Membership+RoleProvider cannot do this level of fine-grained control.
Previously I have written custom user/role/auth system which supported all this, but it was incompatible with "the standard" controls such as LoginView.
The goal would be to have roles allowing access like so:
NewsAdmin
Add news
Edit news
Delete news
NewsPoster
Add news
Therefore, the Post action of News controler should check: Does user have "Add news"-access where he is trying to post?
I would really like to somehow specify this using attributes, so the actual action code could be cleaner and just assume that the caller has appropirate access.
Hope the question makes sense, and I can get some pointers on where to read.
(Oh, and I'm sure this question has been answered in some variant before. I just can't seem to find it. I won't mind single-link replies, if you feel they might be helpful to read)
I think you're being too quick to dismiss the role provider. If a user had a role called NewsAdmin_Europe_AddNews that would pretty much answer the question, wouldn't it?
Once you've made your authentication scheme work with the role provider, you need to tie that into MVC. Subtype AuthorizeAttribute and override AuthorizeCore. Warning: Your code here must be thread-safe and re-entrant. Call base.AuthorizeCore and then test for the specific role based on the URI/query (you won't get route values since this can be served from cache, bypassing MVC altogether).
This is some work, but will be more secure in the end than trying to reinvent membership.