What is the best way to manage Global variable in asp.net? - asp.net

Currently i have a NotInheritable class in App_Code that hold some variables that need to be access thur-out the application but i don't think it's a good way to manage global variables.

Usually, this kind of thing calls for a Singleton. However, I'd recommend never coding a singleton yourself, and using a Dependency Injection/IoC framework to handle the life-cycle of services.
The other thing you have to remember with ASP.NET is that the ASP.NET process automatically recycles itself every now-and-then, so you'll need to persist changes to permenant storage (such as file-system or database)

You should use the Application Settings. Just go to the Application property window, choose the settings tab and add your variables. Than on the code just use the strong typed class. For instance, if I've created a Global variable named PortalName I just use: Settings.Default.PortalName

I believe the Application object is a built-in way to use global variables where you can store various values in the object as needed.

As an alternative to Application state, consider just making your variable static. It is basically going to amount to the same thing, with the added benefit of being strongly typed.
Personally, I'd go with what David suggested and use a singleton scoped service that is managed by an IoC container.

Related

global settings in sailsjs

What would be a proper way to handle global "settings" in my sailsjs application? The user will want to change those settings via the web front of my app.
I imagine I could use a new model "GlobalSettings" with only one item, but I don't really know if it's a good "MVC" practice.
Since it is based on user input, it has to be stored in a database and therefore storing it in model seems like a right choice to me.
Having just 1 row/collection is completely ok in my opinion, especially in the no-SQL field. But for more reusability and scalability, you might want to consider to actually store each setting in invididual row, that might give you space to expand the usability of it in the future.
In my own opinion, I always find as a web app develops, you will start to realize there are more and more fields that you want the user to setup as their preference, as a good practice to relax the application.
For me I usually setup a meta_data model with name, value, criteria, and some other fields.
For example, when viewing your web page, 'Alice' may want a background color of black, 'Bob' may want a background color of green. Then you can let them modify or insert row into this meta_data collection. Then in your database, you will have
name value criteria
background_color black user_name='Alice'
background_color green user_name='Bob'
and it can be all kinds of values.
of course if you just have one value that can be changed by all of your users, it is probably a good idea to know who updated them. For this you would want to create a trigger, (if you are using a sql database)see trigger in mysql, so that every update on the table will trigger a function that stores what was changed and who changed it in another table
So yes, to answer your question, it is totally ok to have a model to store a value, and don't worry about only have one row, you will have more as you develop your app.
The config/globals.js file seems to be a good place to place a global configuration setting.
For convenience, Sails exposes a handful of global variables. By
default, your app's models, services, and the global sails object are
all available on the global scope; meaning you can refer to them by
name anywhere in your backend code (as long as Sails has been loaded).
Nothing in Sails core relies on these global variables - each and
every global exposed in Sails may be disabled in sails.config.globals
(conventionally configured in config/globals.js.)
Sailsjs.org Documentation - Globals
Alternatively you can use the sails.config object.
Custom Configuration
Sails recognizes many different settings, namespaced under different top level keys (e.g. sails.config.sockets and
sails.config.blueprints). However you can also use sails.config for
your own custom configuration (e.g.
sails.config.someProprietaryAPI.secret).
From the docs
There is also services which is global by default.
Overview
Services can be thought of as libraries which contain functions that you might want to use in many places of your application. For example,
you might have an EmailService which wraps some default email message
boilerplate code that you would want to use in many parts of your
application. The main benefit of using services in Sails is that they
are globalized--you don't have to use require() to access them.
It really depends on what kind of global you are wanting.

Ninject - define mapping in web.config file

I'm using Ninject as the IoC container for my ASP.NET MVC app. What I'm currently doing is I have The following layers in my project:
Core
Factory
Infrastructure
Logic
UI (ASP.NET MVC)
Infrastructure, Logic and UI all have references to Core and Factory has references to all.
When my ASP.NET application loads, I call a method in my Factory and pass it an enum value that tells it who runs it (UI or any other UI equivalent layer - for instance, I would like UI to work against Cache classes and Backoffice project to skip the Cache implementation of an interface and work directly against the database). The method then checks the enum and does the mapping in Ninject accordingly.
First off, is what I'm doing here is good practice? each layer doesn't know the layer next to it, and therefor loosely coupled. But on the other hand, the factory has references to all layers - which makes it tightly coupled.
Second, my mappings are hard coded in my Factory layer - what I would like to have is the mappings in a .config file (web.config) - is this possible?
Thanks
Inevitably, your solution will always have at least one project that everything else depends on. Otherwise, you could just break things out into separate solutions, because you'd have entirely separate applications. The goal is to remove duplication and create areas of responsibility; dependencies are a given.
As far as Ninject configuration goes, there is support for XML configuration. Unfortunately the docs are poorly designed and don't allow deep-linking, so I can't just simply give you a URL to go to. However, if you head over to http://www.ninject.org/wiki.html, and on the left, expand the "Ninject" heading, then "Using Ninject", and finally "Xml Configuration", you'll get the info you need.
Usually one should work with composition roots. The composition root (usually the UI) defines which bindings (mappings) are used and instanciates the object-graph in one go (well.. not always feasible but the goal is to be as close to this ideal as possible).
If i understand you correctly, you have replaced having multiple composition roots by having a factory with "enum" parameters. Probably so there's on single instance/layer responsible for mappings. The (preferred?!) alternative is to move this to the composition root, where you won't need an "switch(enum)". To reduce code duplication, put the shared bindings into a separate assembly or config file which you reuse. You might also want to look into NinjectModule's which can help you with that.
As far as ninject configuration by XML goes, i would recommend against that. It's far more brittle (renamings and the like). Only do it if you have mappings which you need to be able to modify after implementation. However, for most configuration issues it's entirely possible (and recommended) to do it differently. For example:
config file:
DatabaseProvider = MicrosoftSQL // OracleSQL if you want to use Oracle DB...
ninject binding:
Bind<IDatabaseProvider>().To<MicrosoftSqlDatabaseProvider>()
.When(x => config.DatabaseProvier == "MicrosoftSQL");
Bind<IDatabaseProvider>().To<OracleSqlDtabaseProvider>()
.When(x => config.DatabaseProvier == "OracleSQL");

Using multiple ObjectContexts in Entity Framework 4 with the repository/uow pattern

i am using EF4 and StructureMap in an asp.net web application. I am using the repository/unit of work patterns as detailed in this post. In the code, there is a line that delegates the setup of an ObjectContext in global.asax.
EntityUnitOfWorkFactory.SetObjectContext(() => new MyObjectContext());
On the web page code-behind, you can create a generic repository interface like so ...
IRepository<MyPocoObject> ds = ObjectFactory.GetInstance<IRepository<MyPocoObject>>();
My question is what is a good approach to refactoring this code so that I can use more than one ObjectContext and differentiate between them in the code-behind? Basically i have two databases/entity models in my application and need to query them both on the same page.
The Unit of Work is used to manage persistence across multiple repositories, not multiple object contexts.
You're not going to be able to persist changes across multiple contexts using a unit of work, as the UoW is simply implemented as a wrapper for a ObjectContext. Therefore, you'll need two unit of works.
Overall, things are going to get messy. You're going to have two OCs newed up and disposed each HTTP request, not to mention transaction management is going to be a nightmare.
Must you have two ObjectContexts? What is the reasoning for this? If it's for scalability, don't bother; it's going to be too painful for other things like your repository, unit of work and http scope management.
It's hard to provide good advice without seeing how you have your repositories set up.
Try creating wrapper classes for each object context, each implementing IUnitOfWork and a secondary unique interface (IEfSqlContext1, etc which represents one of your models/contexts).
Then you can inject whichever context you want.
As I said though, try and avoid having two EDMX/Contexts. It's more trouble than it's worth.

What are the advantages of a custom MembershipProvider in ASP.NET?

If I need to implement my own MembershipProvider class, I have to implement all the services I require myself, so what advantage do I gain by implementing a MembershipProvider derived class versus just writing my own MySecurity class?
Getting an authentication system right is hard, because it's so easy to build something that only appears to work. You don't want to find yourself in a situation where a year after deployment you finally discover your system was cracked six months previously.
Building your system using the MembershipProvider model helps you do it right by giving you a skeleton that lends itself to being implemented correctly. You only need to accurately fill in a set of methods, and you can rely on the high-level architecture provided to make sure you are using the right methods in the right places.
Getting individual method implementations done right is comparatively easy. You can put those into your unit test and have confidence that they do what they are supposed to.
Put another way, you don't have to worry about whether you check your authentication token in the right places. The parts of ASP.Net that call into the membership provider know when to do that. All you have to do is correctly implement the check, and that normally comes down to a simple comparison.
Additionally, you may not need to start from scratch. You have to option to inherit from an existing provider and only add the functionality you want that it doesn't already provide.
If you just need something a "little" different from one of the default membership providers then you should probably just consider inheriting from one of the built-in providers or one of the better 3rd party providers and extend it with the additional functionality that you need or override the functionality that you want to change.
The main advantage of writing your own MembershipProvider class is that it's considered by the ASP.NET as a first-class component and you can use the standard interfaces for authentication and authorization and only have to change the config file afterwards if you want to use a different provider.
Technically, you should gain some level of portability - by using the existing model, you should be able to drop your provider into other web applications, to replace their membership system with very little effort.
Unfortunately, the number of 3rd parties out there who seem to have gone their own way when it comes to membership/profiles is quite impressive, and also rather depressing, especailly when you've put all the effort into writing something based on it.
That being said, by using the membership provider model, all the other controls that use membership "just work" (i.e. Login, LoginStatus, LoginName, etc) without having to write custom versions of those as well.
Well, it depends... I found it very useful because I had to add the concept of functions, so that every role had functions associated to them, and so forth.
In that case I implemented my own Membership and RoleProvider classes which contained the AddFunctionToRole method... IsFunctionAssignedToUser method... etc etc
A little more info on that here

Where do you put program scope variables in UI driven application?

Ok, so I know that global variables are considered bad, and the singleton pattern is overused. And I have read in many places that a class should do only one task and contain only those variables that allow it to accomplish that one task. However, while working on my latest project, I actually thought about these rules before writing any code and have noticed that I tend to break them at the very beginning of the program.
I'm currently working on an MFC dialog based application, but this question could be applied to any UI driven application. I have separate classes that handle state machines, file reading/writing, and hardware interfacing. All of these objects will need some type of UI control or property display/editing. In the MFC dialog applications, the dialog is the program, so it must exist until the program is closed. I've usually just put the objects in the main dialog class for the application and had the dialog class serve double duty; as both the main UI and the home for all other objects in the application. In other applications, I've created these objects globally and referenced them from wherever they were needed. Neither of these ways seem correct. The first option breaks the one class, one task rule, and the second relies on globals and also creates hidden dependencies. I could institute some type of dependency injection, but where would all these variables that I would inject reside?
I'm just wondering what others do to organize their programs without breaking the rules?
I find that storing singletons as public data attributes of the main dialog class of an MFC dialog application works OK for a quick and dirty program. However, as the program becomes larger and more complex, things begin to get untidy.
The point where storing singletons in the dialog class needs to be refactored is probably when you start passing pointers to the dialog around, so that other classes can access the singletons it contains.
The singletons can be moved into the global namespace. This is still a bit untidy, especially when there are a large number of them. Since you have to write a separate extern for each one in a header file then define each one somewhere, you soon end up with something that looks a lot like an old fashioned C program.
A neat thing to do is to make use of the singleton that the framework has already defined for you.- the application object which is always called theApp, a specialization of CWinApp. If you place your singletons as public data members of this, then any code can get easily get access to them .
Suppose that you called your application “solver”. The dialog application creation wizard will create a class CsolverApp. Now suppose you have a singleton called ‘theData’ an instance of the class ‘cData’.
Place your singleton in the theApp
class CsolverApp : public CWinApp
{
public:
cData theData;
…
Now to access this from anywhere in your code
#include “solver.h”
theApp.theData.somepublicmethod();
It does make sense to look at this from the MVC (Model - View - Controller) viewpoint. (That the naming of MFC is an homage to MVC is another sick joke on Microsoft's part; it is hard and unintuitive (but by no means impossible) to manage the types of abstractions that are necessary in "true" MVC within MFC.)
Specifically, it sounds like you've thought out the basis for MVC design; you have the classes that do the underlying business logic work (the Model), and you know they should be separated from the UI components (the View). The issue that comes in now is the third part of the MVC trinity; the Controller.
MFC makes this stuff tough by apparently purposefully obfuscating the MVC process, by making you start with a Dialog. In your instance, the Dialog that MFC is starting you off with should be the Controller, and NOT the View. What your Dialog (Controller) is doing for you is managing your UI components (View) and allowing them to interact with your "work" classes (Model). What makes this tough again is that your UI components, to be visible, most likely need to be attached to your Dialog to be visible.
To get this sort of thing right, you really have to basically implement your Controller as a high-level object that gets instantiated from your Dialog; your Dialog is where the initial control flow comes in, your Controller gets control flow, and from there, it should treat the Dialog as just another UI component (albeit one with special status).
This allows you to have the proper level of encapsulation; your Controller invokes your business logic (Model) classes, which can communicate with each other or with the Controller as appropriate; they are segregated from the View by the Controller, instead of being embedded in the UI components and (likely) taking the "easy way" of over-privileged access to UI elements ("Hmm, I need this object to get some input from the user; I could refactor, but it'll be so much easier to just throw a dialog box up, since I have the top-level window handle...").
Once your Controller object is the home to all of the business logic objects, things become easier; you can use the Controller to provide cross-object access for any objects that need other objects. Think about which classes need to be Singletons, and use them sparingly. Resources that need contention management (such as hardware resources) are great examples of "natural singletons"; things which lend themselves to a singleton approach. You may also choose to make your Controller a singleton; depending on the requirements for access to it. Specifically, in your Dependency Injection scenario, the Controller is where you'd instantiate the objects and manage the dependencies.
This is the basic MVC approach; but, like I say, MFC makes it unusually hard and unintuitive, because of the fundamental design of MFC. I learned MUCH more about MVC AFTER an initial VERY negative impression about it due to MFC; if you can, I recommend looking into what MVC implementations look like in other languages.
Good luck!
If I am understanding you correctly, it sounds like the lifetime of your dialog objects is too long. Rather than maintaining the dialogs for the duration of your program, you should consider creating and destroying them as they are needed.
Also, global variables (or singletons) are OK so long as the thing that the variable represents is truly a global thing that persists for the lifetime of the program, rather than just a place-holder for an object of lesser duration. Using globals for the wrong things for simplicity sake will come back to bite you eventually, even if the globals are stored on the main dialog.

Resources