I am using angular ui grid. At first I implemented this in a controller and it works fine after all my customization. As I am using multiple grids I cannot write a long controller each time. So, I converted it to factory. I kept the common function in factory and column definition and data in controller. Now when I use this factory in more than 1 controllers, the last controller is overriding all others.
1) Is it correct to make this grid in a factory?
2) If yes how do I overcome this problem?
3) By using factory for this grid, my gridObj.gridApi.pagination.on is throwing error(gridObj is the singleton object that I am returning).
Any suggestion is welcome. Thanks a lot in advance.
You should use a Directive instead. Factories create a single Instant (see Angular Provider Documentation and wont create a private scope, which you need to not override your data.
Note: All services in Angular are singletons.
But Directives provide a private scope and create new instances every time they are called in HTML if you want them to.
//directive
scope: { // this option creates isolated scopes
something : '=',
},
I created a Plunkr showcasing a possible setup. For some more written details please see my answer from few days ago.
Your HTML might look like this afterwards
<my-grid options="all.firstOptions" class="grid"></my-grid>
Where my-grid is your directive and options="" are your special settings (and whatever else you wish to use in the directive). In your directive you declare the default settings and merge them with the special ones.
scope.gridOptions = {
data: scope.options.data, //private scoped from options : '=',
columnDefs: scope.options.colDef || defaultColDef, // optional setting or default setting
// ... some more default data
};
If you have any specific questions, let me know.
Related
In some cases, I would like to add contextual information to a message (for instance currently authenticated user), without having to include it in the message template.
I would like to accomplish this :
logger.Information("Doing stuff {Foo} with the thing {Bar}. {User}", foo, bar, user)
but without the {User} in the template.
I already know about LogContext but that seems overkill when adding contextual information to just one event.
I also know I can use the low-level API logger.Write(LogEvent evnt) to actually control which properties are included, but that seems like a bit too much code for what I am trying to accomplish.
I'm pretty sure there is a short and elegant way that is super obvious, but I haven't found it :)
UPDATE :
I found out only afterwards that this question is more or less similar : Add custom properties to Serilog
I could figure it out on my own!
You can use the fluent method .ForContext(propertyName, propertyValue) on a single call to one of the .LogXXX() methods.
For instance :
logger.ForContext("User", user)
.Information("Doing stuff {Foo} with the thing {Bar}", foo, bar)
The property added to the event only apply to the event, and they are no longer present on the next call to the logger.LogXXX() method
UPDATE
The article by Nicholas Blumhardt explains it quite well : Context and correlation – structured logging concepts in .NET (5)
If you're using the generic Microsoft ILogger you can use BeginScope;
using (_logger.BeginScope(new Dictionary<string, object> { { "LogEventType", logEventType }, { "UserName", userName } }))
{
_logger.LogInformation(message, args);
}
This is discussed here; https://blog.rsuter.com/logging-with-ilogger-recommendations-and-best-practices/
I'm relatively new to rails, but I've made a few basic CRUD apps. However, this time, I'm making something different, and I'm not sure how to organize it.
It's essentially a one page app. The user fills out a form, and the code does some calculations based on those values. I have all the code written, but it's all just sitting in the controller. I'm assuming that this isn't correct.
There are two parts:
Using an external API, 2 constant arrays are generated. I need these variables to be global, or at least accessible for the calculator function.
I have a function that takes some inputs from the form that also calls other functions. A simplified version is below. I could put all the code into one function if that's necessary. I have them separate just so that the code is more readable.
def calc(input)
func1(input)
func2(input)
# do more stuff
return answer #I need to show this in the view
end
def func1(a)
end
def func2(b)
end
So, where should I put each part of this code?
To make your controllers thin, you can keep business logic at Service Objects.
Just create "services" directory at "app", add there some class like "user_searcher.rb".
And call it in the controller, passing all necessary data.
Such technique will help you to isolate business logic and incapsulate it in separate class.
BTW read this article http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/
I think, from what I understand of you question, is this code should be placed in the helper classes. If you have dedicated class for this calculation, you can use class attributes to access array to access anywhere in the class or declare them constant, in case they are constant.
I don't think making global is a good practice, just because this is needed in some other function, instead return that variable and pass them as parameter where they are needed.
Is it possible to override the class file location of a framework class via classmap and autoloader? If yes, then how?
Example: I want to override Zend\Form\Fieldset, so that everywhere in the framework where Zend\Form\Fieldset is referenced, I want it to use my own class file instead of the original.
Motivation: When updating the framework, I want to keep my modifications safe from getting overwritten.
Known alternative: Modify the code in the framework.
Disadvantage: Modification gets lost when updating the framework.
writing the same class (FQCN) at another location is generally a bad idea. This causes two classes which are equally named to live in two separate locations. It's a much better idea to create your own Fielset in your own namespace. Say, Application\Form\Fieldset.
You can extend the ZF2 fieldset by your own. Then reference this new fieldset class and its all much more maintainable.
The downside of this method is you don't automatically use the new fieldset class. You have to reference the Application\Form namespace in every form you use. On the other hand, this makes it much more clear to other users of you code what exactly happens: there are no unexpected consequences using ZF2 code.
The only remark I have to make here is, for what do you need another fieldset? If you think you need that for view helpers, that's not true. You can modify the view helper to render fieldsets without modifying the Fieldset form class itself.
Think of the following:
I've got a table data grid webcomponent and another component providing a data feed. In the applications main acting as kind of controller, i'd like to wire and setup those two components. Therefore i need a reference to underlying table grid instance Dart class and call methods on the "Component API' (to provide the table grid's tablemodel with data).
How do I access the Dart Class instance of a webcomponent instance from outside ?
Probably I missed something fundamental or are polymer webcomponents meant to interact only using databinding and stringy attributes stuff ?
Follow up: Found it !!
RLTable table = querySelector("#apptable").xtag;
does the job
As zoechi pointed out, xtag is not necessary.
var component = $['myComp'];
var componentXtag = $['myComp'].xtag;
print(component == componentXtag);
prints true. Therefore both
component.method()
componentXtag.method()
work fine
You don't need xtag. Some weeks/months ago this was a workaround until the final solution was landed.
I've seen a lot of people talk about using base controllers in their ASP.NET MVC projects. The typical examples I've seen do this for logging or maybe CRUD scaffolding. What are some other good uses of a base controller class?
There are no good uses of a base controller class.
Now hear me out.
Asp.Net MVC, especially MVC 3 has tons of extensibility hooks that provide a more decoupled way to add functionality to all controllers. Since your controllers classes are very important and central to an application its really important to keep them light, agile and loosely coupled to everything else.
Logging infrastructure belongs in a
constructor and should be injected
via a DI framework.
CRUD scaffolding should be handled by
code generation or a custom
ModelMetadata provider.
Global exception handling should be
handled by an custom ActionInvoker.
Global view data and authorization
should be handled by action filters.
Even easier with Global action filters
in MVC3.
Constants can go in another class/file called ApplicationConstants or something.
Base Controllers are usually used by inexperienced MVC devs who don't know all the different extensibility pieces of MVC. Now don't get me wrong, I'm not judging and work with people who use them for all the wrong reasons. Its just experience that provides you with more tools to solve common problems.
I'm almost positive there isn't a single problem you can't solve with another extensibility hook than a base controller class. Don't take on the the tightest form of coupling ( inheritance ) unless there is a significant productivity reason and you don't violate Liskov. I'd much rather take the < 1 second to type out a property 20 times across my controllers like public ILogger Logger { get; set; } than introduce a tight coupling which affects the application in much more significant ways.
Even something like a userId or a multitenant key can go in a ControllerFactory instead of a base controller. The coupling cost of a base controller class is just not worth it.
I like to use base controller for the authorization.
Instead of decorating each action with "Authorize" attribute, I do authorization in the base controller. Authorized actions list is fetched from database for the logged in user.
please read below link for more information about authorization.
Good practice to do common authorization in a custom controller factory?
I use it for accessing the session, application data etc.
I also have an application object which holds things like the app name etc and i access that from the base class
Essentially i use it for things i repeat a lot
Oh, i should mention i don't use it for buisiness logic or database access. Constants are a pretty good bet for a base class too i guess.
I have used base controller in many of my projects and worked fantastic. I mostly used for
Exception logging
Notification (success, error, adding..)
Invoking HTTP404 error handling
From my experience most of the logic you'd want to put in a base controller would ideally go into an action filter. Action Filter's can only be initialized with constants, so in some cases you just can't do that. In some cases you need the action to apply to every action method in the system, in which case it may just make more sense to put your logic in a base as opposed to annotating every action method with a new actionFilter attribute.
I've also found it helpful to put properties referencing services (which are otherwise decoupled from the controller) into the base, making them easy to access and initialized consistently.
What i did was to use a generic controller base class to handle:
I created BaseCRUDController<Key,Model> which required a ICRUDService<TModel> object as constructor parameter so the base class will handle Create / Edit / Delete. and sure in virtual mode to handle in custom situations
The ICRUDService<TModel> has methods like Save / Update / Delete / Find / ResetChache /... and i implement it for each repository I create so i can add more functionality to it.
using this structure i could add some general functionality like PagedList / AutoComplete / ResetCache / IncOrder&DecOrder (if the model is IOrderable)
Error / Notification messages handling: a part in Layout with #TempData["MHError"] code and a Property in base Controller like
public Notification Error
{
set { TempData["MHError"] = value; }
get { return (Notification) TempData.Peek("MHError"); }
}
With this Abstract classes i could easily handle methods i had to write each time or create with Code Generator.
But this approach has it's weakness too.
We use the BaseController for two things:
Attributes that should be applied to all Controllers.
An override of Redirect, which protects against open redirection attacks by checking that the redirect URL is a local URL. That way all Controllers that call Redirect are protected.
I'm using a base controller now for internationalization using the i18N library. It provides a method I can use to localize any strings within the controller.
Filter is not thread safe, the condition of database accessing and dependency injection, database connections might be closed by other thread when using it.
We used base controller:
to override the .User property because we use our own User object that should have our own custom properties.
to add global OnActionExecuted logic and add some global action-filters