I've been working on a project now for while which is devied between something we call "webs" (bad name, I know) and "buildings". Each web can have 1 or more buildings, and when you log in you log in to a particular web. Traditionally this was set up as separate vhosts in IIS, thus they were actually separate webs, except for the fact that they all ran the same code-base, however the new system that's being written moves away from this pattern.
Also, in the old system; what building you were currently viewing was stored in a session-variable, in other words one couldn't direct link to anything. Say for instance that you log in to web 01 on building 01 and navigate to the ao_list.asp (the old web was classic asp), you'd end up with an url looking something along the lines of web01.domain.com/ao/ao_list.asp, however in the new system you would have a url like this: domain.com/web-01/building-01/ao/. This ofcause takes you to the Index-method of the AOViewController.
All this work currently, and there is no problem with the navigation at all. In addition to said URL; there is a API-url that closely match the web-url given by domain.com/api/web-01/buildin-01/ao/. This also works great.
But from here comes the problem. Decorating every Controller in the project is the custom AuthorizeAttribute I wrote, that takes into consideration what building/web you are browsing while checking the user right. For instance; no user should have access to web's that isn't their respective user-web. And users can have different rights on different buildings.
The attribute works by getting the building and web-number off from the route-dictionary, then using that when calculating the user-rights, and this works as one would suspect. However, there has been proven a need for API-methods that can aggregate API-calls over several buildings, and I'm struggling trying to figure out how I can implement these.
For instance; whenever a user goes to the start-page of the application; a ajax-requests is made to get a list over outstanding AO's in every building the user has access to. This is currently made one request per building, which might result in hundreds of requests in the worst case scenario. This of-cause is unacceptable, so what I would like would be to be able to do something like calling GET /api/web-01/ao/?buildings=01,02,03,04,06 then loop over the buildings on the server-side and return something like this:
[
{"building":"01","data":<result of calling /api/web-01/building-01/ao>},
{"building":"02","data":<result of calling /api/web-01/building-02/ao>},
{"building":"03","data":<result of calling /api/web-01/building-03/ao>},
etc...
]
And of cause, I would like to simply get an error if any permissions were attempted violated along the way.
Is there a good way I can implement this without having to change the actual implementation of the Index-method on the API.AOController?
Currently I implement buildings by adding a simple look-up in the route-dictionary during OnActionExecuting in a base Controller that all my controllers extend, so what I was thinking was that I could check for the existence of a buildings-querystring-parameter and if it was present create several instances of the current controller, set the building-variable on the "child" controller and call the method in question, but I don't know if this is a good way to do it, and I don't know how to invoke the AutorizeAttribute on the "child" either, so what I'm asking (after writing all this) is a good way to orchestrate this problem in a good way :).
[Edit]
TLDR;
I have a mvc3 page setup with urls like:
domain.com/api/web-01/buildin-01/ao/
domain.com/api/web-01/buildin-02/ao/
etc.
These are all API calls that returns JSON-data after running a custom Autorize-attribute.
What I would like is to be able to do something like domain.com/api/web-01/ao/?buildings=01,02 which would result in getting the accumulated response of the two calls above (grouped by their respective building ofcause) while still running the Autorize-attribute for each building. And if that Autorize-attribute would fail for one of the buildings it the whole request should fail. And also; I would like to be able to do this without having to change the implementation of the Index-method of the AOController, but instead having it called multiple times. I think sort of what I want to achieve is to have a single request "act" as if it was actually several requests, without ofcause creating several requestcontexts (which would spawn database-connections etc.). Is this possible?
Related
For starters, please forgive me and please correct me on my terminology. I am quite sure of the correct words to use for what I am trying to accomplish.
I have been given the task of building an ASP.Net Razor web site. It is something new to me. I am very proficient in PHP and ASP Classic. What I need to be able to figure out is how to declare a variable that is accessible everywhere. I do not know if in the .net world you call it a global variable or application variable or something else. But, here is how I would do this in Classic ASP.
In Classic ASP, I would have a file named VarFunct.asp. It would be the file that I declare my variables and have various functions I would access from anywhere. I would include the VarFunct.asp file on all of my pages. Anyway this is what I am really trying to do (written in how I would do it in Classic ASP)…
SelLoc = Request("SelLoc")
If Len(Trim(SelLoc)) = 0 Then
SelLoc = "All"
End If
In this case, Request("SelLoc") could be Request.QueryString or Request.Form. Then anywhere in my website I could use the variable SelLoc. So, in short... I need to be able to set a variable. Check to see if it is set by Request.Form, if not, check Request.QueryString, if not set the value to “All”. How do I write this? And where do I put it?
When I created the website using Visual Studio 2012, I selected ASP.NET Web Site (Razor V2).
This seems like it should be such a basic fundamental task of any website that has any kind of server side programming, but trying to find information and documentation online is near impossible, but probably because I am not using the correct terms for my question. I have not found any Razor tutorials that talk about setting variables that can be used globally across the website.
If someone could please help me out here by either telling me what I need to do or point me to a good tutorial, that would be great.
what you are looking for is called Static Class/Member
This will allow you to store and share data for the whole application.
BUT! since web server is multi-threaded, you wouldn't want to do this or else you might run into the case where the data is overwritten by another request before you finished the current one.
If you need to pass data from controller to your View you can use ViewBag dynamic object
If you need to use the data anywhere else (for example in a helper class) then do
HttpContext.Current.Application["VariableName"] = something
It is basically a dictionary and each request will have a different Application object
There are several ways of doing this.
For your example I would assume that this particular variable can be different for different users that are using the application at the same time. This is more of a Session scope than Application scope.
In this case you could simply use inheritance and make a base controller and/or base view model class that all your other controllers and/or view models inherit from. This way you can pass it back and forth between the view and controller and read/update it whenever you need to.
You could also use the Request and HttpContext and Session objects that are built into asp.net, if they fit your need. A brief overview of some of their functionality can be found here: https://learn.microsoft.com/en-us/aspnet/web-pages/overview/api-reference/asp-net-web-pages-api-reference --- google searching specific ones yields tons of results.
If you truly want Application scope, you can of course use a static class for you utilize static methods. Then you don't need to include the class in every other class, but you would need to fully name qualify the method when you call it.
I would not recommend static variables at this level though. I can't imagine very many things that would need to change for every single user that you would change while the application instance is running. Most of these sorts of items that we use are caches (generally db lookups and such, that we don't want to retrieve from the db each time, and RARELY get updated). If you utilize caches, be very aware of your thread safety when updating them. Here is an msdn on caching: https://msdn.microsoft.com/en-us/library/aa478965.aspx --- Or application configuration settings, like the application environment. We pull most of those from a config file, and they are read only, we don't change them within a running instance of the application.
I'm trying to build REST API based on existing database model. I have already one built but I want to make it simpler and clear before I start coding client app. I've decided to use ASP.NET Core as back-end technology and WPF front end (also there will be Angular/Ionic frontend). The database model is very simple, it contains around 30 tables (different documents with related resources and collections).
So far API use flat URL - this way sometimes I have to post/put child object with its parent. Should I go with nested URL (API/Document/{id}/Item) to make sending object simpler or even use the only id which makes this object flat?
The second problem I have when I need data from child object for data needed to data grid source - should I add new method/controller to get ViewModel with all properties needed for data grid or should I get parent object collection first and then get child objects and construct view in client app?
Ultimately, this choice depends on many parameters and also on your team preferences. You didn't give enough details to give a absolute advice, but even though you did give them, there might not be any absolute answer anyway.
When in doubt, for both of your problems, I would recommend to go for the flat, simple, complete data transfer objects. (EDIT : of course won't be flat if you have linked collections, but still it would be simple and complete)
This has the advantage of reducing the number of connections / calls to the API, which have some overhead for all the network infrastructure, and for the client too.
Second, I think this simplifies development (but I admit this is debatable)
And also, about the second problem, it helps separate the concerns between your API and your client app. Building a ViewModel is often necessary (you maybe don't want to expose some informations, for security or performance reasons), but don't make it too complicated just for the client app; you want your API to be easily used by a new client / new version later.
To show you why it's usually worse to do many individual calls :
Imagine if you want to retrieve 40 documents.
If each document has Item1 and Item2, that would be 80 more calls if you have to retrieve Documents/1/Item1, Documents/1/Item2, etc.. !
Also, for your front-end development, you have to manage the callbacks (first call the document, once it's done get item1 and item2) which seems more complicated than getting the whole lot in one go (since ultimately you need to wait for everything to be there).
Worse, maybe some of the object has changed, and his children too, in between the call. You might end with Version A of your parent object, but with version B of it's children items !
Of course, there are some situations that could make the decomposed children items calls interesting.
If you often have to get only the item part of a document, without needing to reload the whole, that would be a good argument for that.
Or if the overall document is large, and you want to be able to display parts of the loaded documents before the complete loading is finished.
A last drawback I can see, when you have linked collection of related objects, is that you can have many repetition of linked objects. In this case it could make sense to do something more tricky if you need to avoid too many repetition, and have a few separate calls for main object, relations, and load related objects only once even if some are used multiple times can be beneficial.
I have a WebApi Controller for an application under development which is almost complete. There's one method remaining though and I'm not entirely sure which approach to take (decision making by testing input/output is not possible at this very moment due to various reasons unfortunately, therefore all I'm left with is theorycrafting).
Anyway, back to the point. My controller takes a complex model entity, transforms it into a DTO one, with only the values I need taken and then sends it to a smartphone client. That's working fine. My issue is though, I need to create a reverse method as well - something that returns the data gained from the DTO object that's processed client-side and uses it to update the complex entity inside a database. I'm new to both ASP.net and http requests in general.
I'm considering two options : one would be a Post method, although I'm not entirely sure if that could work. Another idea of mine would be a void that simply takes the data and returns it to the database (sounds good on paper, compiles just fine, but I can't test it at this stage as already mentioned, therefore hopefully someone with a deep understanding of the subjects will be willing to help).
(I think putting [HttpGet] above my void method should work, although I might be wrong)
Pardon me if the request isn't clear enough, English is not my native language. (The edit button's here though, so if you can't seem to understand something, let me know)
I think you should be using a PUT/PATCH method; however, I am assuming that you want to update entities, not create them. Using Put/Patch would help to make your application RESTful.
REST is a very popular model for web api's
EDIT :
For reference
POST is CREATE,
GET is READ,
PUT/PATCH is UPDATE,
DELETE is DELETE
That is the making of CRUD to RESTful Web Api's in general
I'm building a web app using ASP.NET MVC 4, with data storage provided by T-SQL database via Entity Framework. I'm integrating audit logging as I go, and I'd like to provide a nice human-readable summary of the action, so that I can present a friendly logs view with clear statements like "User Bob logged in", "User Alice updated article 'Foo'", etc.
An audit record currently consists of:
GUID
timestamp
user ID
action category (controller name)
action (action method name)
IsError (boolean; true means either this is a record of an error, or this action did not complete successfully)
blob of serialised details
At the moment, my logging uses a custom attribute which implements IActionFIlter; the OnActionExecuting() method logs the attempted action (serialising things like URL, parameters etc to the detail blob) and the OnActionExecuted() method goes back and sets IsError to true if there are no errors, and appends either the returned result or exception with error message and stack trace etc to the details. I want to add another column for description strings, but I can't see a tidy way to do it.
The furthest I got was to pass a string to the attribute, something like "User $user logged in" and then have the log method scan the string for the $ character and replace that word with anything from the parameters dictionary whose key value matches that word (minus the $ character). This is a little limited; for example, if articles are stored by ID number, then the best you can manage is "User 18 edited article 37". There's no real way to get at the username or article title; you can't pass instance data to the attribute because it's baked in at compile time, and I don't really want my logging method to be making all sorts of database calls to get that sort of data, not least because it then becomes impossible (or at least a real pain) to have a single generic logging method.
The alternative to all this is to have a static audit logging class and call something like AuditRecord.WriteLog(foo); all over the place, perhaps with some kind of descriptor class I can use (or inherit from) to describe different types of action, storing all the parameters and generating a description string as needed, but seems less elegant to me; I really like being able to just tag [AuditLog] on top of a method and know that it'll be recorded.
I'd like to avoid huge amounts of conditional logic, like using the controller and action names in some big switch statement to select the correct string template. If I could just get hold of things like article titles in the logging method then it'd be fine. Is there a neat, simple way to do this?
We recently had a similar discussion at work regarding both logging audit history and applying more complex security rules across our new MVC project.
In the end the most "elegant" solution that we came up with was to have the method calls within the controller actions (Your alternative method).
For example:
[HttpPost]
public ActionResult CreateItem(Item item)
{
//Simplified
CheckSecurity(SecurityTypes.ItemCreation);
LogActivity("Created an item");
//Rest of action code
}
This gave us the flexibility to account for all possible use cases, and allowed us to wrap up the logic into simple to use methods to reduce code repetition.
It may be late to answer, but I think there is a good alternative to keep using action filter attributes and to be able to access per-request lifecycle objects.
As anaximander noted it above, the underlying problem is that attributes are resolved by the CLR, so their lifetime cannot be controlled and they don't mix very well with an IoC container (to make them transient, per request instance, etc.).
Usually, in .NET a new instance of attribute is created each time it is resolved by reflection (GetCustomAttribute method).
Furthermore, in the case of MVC/webapi, action filter attributes are cached, so they normally are created just once.
The conclusion is that attributes are designed to annotate only, in other word, they should contain only metadata (they are DTO). Unfortunately, my understanding is MVC and WebApi frameworks are not designed in this way. To restrict action filter attributes to simple DTOs and to be able to manage lifecycle of the logic part around them, special means must be taken.
I think your use case fits perfectly to the solution provided in a Steven van Deursen's great article. It demonstrates how to separate attributes data from logic and it is based on an action filter registered globally, the so called "dispatcher", with the ioc container as a dependency.
The container is not resolved statically. It is provided in the constructor of the global filter when it is registered at the application initialization.
So each time it is executed, it looks for any attribute marker on the action being executed and it resolves a generic interface where the attribute is the generic parameter. Instead of having an action filter attribute which merge data and behavior, you end up using two classes: a plain old attribute - the marker - and the corresponding implementation of the generic interface for its logic counterpart. The container is used to resolve the generic interface. If your filter depends on per-request components, you can create an implementation of the generic interface with the services you need. If it does not depend on other services but you need a per-request lifetime (to measure time between the beginning and the end of an action for example), it also does the job, thank to the use of the container to resolve the generic interface. The aforementioned article contains code examples for WebApi, MVC and ASP.NET 5.
Also, Mark Seemann has made an article on the same approach.
I think it does not provide a good solution for all cases, like authorizations filters and perhaps exception filters, but to me it is the most elegant way for many action filters.
The better way would be to format this data when you view it, rather than build these things during the logging process.
If the action is "login", and the recorded user is available (which you should do) then you build that message in the viewer.
So you log all the raw events, then build the "view model" or "read model" based on this data that is more descriptive. this can allow you to even re-parse all the raw data if you want to change it's description. You could log a lot of data that isn't used yet so you could implement it later within the description.
IMO, sprinkling methods this way inside actions doesn't seem like a good idea and an Action Filter on the controller or base controller is cleaner. if you wanted to do that you could use an AOP (aspect oriented programming) framework to avoid cross cutting...
I have an application that needs to load data via web service calls and perform various permission and data checks. Fairly typical. I'm currently doing this in the background when the application starts, however it is a wizard type application and so the user can't do much until all of this has completed. If any issues come up when doing this I want to present the user a helpful message (you are "missing permission x" or "failed to retrieve y").
For the following, understand that I can change how I'm going about doing something, but I can't change what steps I need to perform. This has been simplified down as well.
A typical item might go like this. I need to retrieve a list of groups the user belongs to. However, first I need to check if the user has permission to view this list of groups otherwise the other call will fail. Once I have the list, I then need to check whether they have certain permissions within each item and discard those that don't apply. If they don't have permission in any of the groups, inform the user.
Initially I had everything in a LoadAndCheck() type call to work out all the various items I needed. Obviously this is large an clunky.
I then moved to a breaking each step up into pattern where each item was in a class behind an interface
interface IInitialize {
bool InitializeAction();
void OnFailure();
}
(i.e. CheckThisPermission, LoadThisList, CheckThatPermission). Each class performed a small action and if that action failed (loading data) or was false (permission check) it contained the step to perform to inform the user of the issue.
I can then loop through these classes and on failure of one step, not perform the following steps and have things configured to inform the user. This also lends itself to DI down the road if I settle on this pattern.
However, something just doesn't feel right about this pattern, though it is better than everything in one big call. Maybe it's just the name I'm giving to things. However my brain is wiped out and I'm not coming up with anything better.
So do you have any good patterns for doing something similar when starting up your application?
I personally have a SecurityManager static class that i call methods on for checking certain types(groups/items/users/etc) with methods such as
HasTradePermission(PermissionType type, User user, Trade trade);
HasInvoicePermission(PermissionType type, User user, Invoice invoice);
Only inside this method do I start calling the is part of group/what group/ does this group have this and this permission etc, so as far as the application is aware, all it interacts with is 'HasPermission' objects, therefore in my app i just iterate over e.g. Trades, and call the HasTradePermission.
Inside these has permission object, i would get the list of groups that the user is part of and check if there is a match with one of the groups inside the TradePermissionGroups etc..