Implementation of feature flags in C# - c#

Feature flags are something I often use but never really gave much thought about it until this new project I'm working on started.
I usually implement it with lots of keys in my web.config file but this approach has two major drawbacks:
When changing a value inside web.config the application pool is restarted - This can be a problem in a heavy access environment
Having too many keys in the web.config file is confusing and can get pretty messy
What's the best way to overcome these problems?

I would suggest using IoC to abstract away the implementation of your feature flags - all your code needs to access is something along the lines of IFeatures.IsEnabled("FeatureA"). Once you've done this, you can choose the most sensible implementation - some suggestions below:
web.config implementation (compatible with what you have now)
Database implementation (with cached values, possibly using SqlDependency if you want to work on a web farm)
Separate configuration file implementation (cached, but using a FileSystemWatcher to check for changes to the config file and load them without needing to restart the app pool). This allows for the case when you need features defined before you need your DB.

You don't have to store feature flags in web.config.
An option is to store them in a database - this has the added benefit of working well in a web farm.
Note that with feature flags, once you are in a position that a feature will be either permanently on or off (say when transitioning from widgetA to widgetB, and you will no longer need any widgetA code), you should be removing the feature and associated flag. This will help with managing the feature set.

If you want add feature flags to your C# applications I would not recommend creating your own feature flag solution but rather to use one of the several feature-flag-as-a-service providers which are out there that can directly integrate with C# right out of the box.
One such solution is Floodgate which has an SDK for .Net which you can install and be up and running with using feature flags in your application in next to no time.
Disclaimer, my name is Eugene and I'm the founder of Floodgate. That being said my advice is the same no matter what feature flag provider you decide to use.

Related

Need help to Secure an ASP.NET Web Application

I'm working on a internal web application (only employees can log in) and need some help figuring out a good approach to handling an individual users permissions to the system.
The system itself is in C# / ASP.NET (4.0 / Webforms / Forms Authentication) / SQL Server 2008 and has several different areas which will have varying sets of permissions. You can think of it in a basic crud scenario (create, view, update, delete) though those would apply to different aspects of the system.
(I do want to mention this isn't a type of CMS system, so I can't pick an Open Source Project like DotNetNuke or anything. This is being developed from scratch. I can use open source libraries if they are available though.)
What would be a good approach to designing the User Permission system for a complex system with probably 5-6 different sections that have a good 10-15 different view/update/deletes contained in each section?
The goal here is to make it:
Understandable for Users (Admins) to use / set up.
Easy to Maintain Code Wise.
Easy to adapt as new permissions are needed (different types or in different spots).
There are two approaches that come to mind:
Approach 1:
Try to use the built in ASP.NET Roles system to define the different permissions and manage it from there. I could build custom pages to handle the different areas and assign permission sets to users. I believe that would also allow me to use the current session object by default to contain all of the permissions in the system for a user. (HttpContext.User.IsInRole() etc...).
Now, while I think that method would work, I'm not sure it's going to be easy to maintain or adapt to future needs. It seems like it'd be the quicker way to get it up off the ground and working but not the best long term.
Approach 2:
Roll my own. In this scenerio, I'd set up database tables to store true/false style permissions for each section of the application. Then I'd retrieve that information and place it in the session and basically access it anytime I need to check if someone has permissions to do something. I'd then build the custom pages to manage the lists, etc..
It seems this approach might be the more maintainable long term solution. It gives me more power in the set up and how it is handled. However, I'm basically still doing the work that the Roles system abstracts away for me in approach 1. I favor this over approach 1 still however.
In the end, I'm not sure if either approach is the best way to handle this. Can anyone help explain to me why either of the above would be good / bad? Or even to suggest a different alternative as to the "best" way to handle it in general would actually be. This is my first major undertaking in this area, so I don't have a great deal of experience in trying to "secure" an application like this by permissions. Any and all help is appreciated!
Use the built in approach, unless you've a specific architectural need not to. If you don't use the built in one, you can choose to roll your own provider implementations, but you should follow the same templates as the build in system, as it covers a lot of the security caveats that you should think about.
There's even the built in configuration page for quick and dirty user maintenance.
I would stick with the built in approach, you can always write a custom RoleProvider to match the roles and permission you need for your user base see (Implementing a RoleProvider)

ASP.NET: Creating versions of the same website

My new assignment at work is to create a second version of our existing web application. Currently, our application supports only full time brokers, but now we our launching a second site specifically for part time brokers.
The new site will be almost identical to our existing site with the following exceptions:
It will have it's own branding.
A couple of the user controls used for displaying information will be different (but none of the pages will be different).
Our existing users should not have access to the new site and vice versa.
It needs to be easy to test both versions of the website from within Visual Studio easily.
We want to reuse as much our existing code as possible.
I have 2 weeks to do this.
I'm hoping that this is a common scenario and someone out there has some advice for how to accomplish this.
I really, really don't recommend branching projects or other routes which involve copying what is essentially identical code with the exception of branding and authorization. It will certainly be easier in the short run but, as you said, will become a nightmare very quickly trying to maintain almost-identical code bases.
Your pages can make the decision on what controls to show based who is logged in or even set globally to indicate this is the part-time broker version of the application. You could have a set of views and light logic to handle part time vs. full time brokers. Since the sites are deployed separately, a config setting would be straightforward. If you have other versions of the same site, you may have to give this some thought to ensure it would scale with your other variations.
I would even use the same database as long as you can separate the data appropriate using claims-based (preferred) or role-based authorization or similar.
All this said, there does not seem to be any great reason why you'd want to deviate from using the same code base.
I would create a branch of your code and then work against that. This is of course assuming that you are using version control. You are aren't you?
My first thought would be to
copy the entire source code to another IIS website
script the database over to another database (fresh start for new website)
make necessary adjustments to usercontrols and branding
roll out the new site (as Beta)
In Visual Studio, you can create a new project inside the same solution so that you have access to both projects at the same time.
If you're using Version Control... create a branch, and start customizing from there.
what this will do for you is give definitive separation between the two sites... no users have access across sites, all future customizations will be on a per-site basis, etc.
While I really like the idea CaptainTom posted another solution would be to break off the display layer of your application from the rest of the logic and create a new project that implements the new user experience while sharing the rest of the code
i.e. a FillTimeBrokers project and a PartTimeBrokers project with both implementing their logic from a common Brokers project.

What Java/Scala or .NET web frameworks support modify source code and instantly run workflow e.i. without long rebiuld/redeploy procedures?

As far as I can see the key advantage of dynamic languages like Ruby or Python over Java/Scala/C# etc is "hot" applying of your changes to source code to the running application. What are the frameworks for JVM or .NET that support the same workflow - apply changes to configuration and source code on the fly? Can they also watch changes to custom configurations and notify application?
Note: Frameworks for dynamic languages on JVM/.NET like Grails or Compojure are out of scope here.
EDIT: I mean not only modification of a method body, but adding/deleting methods, fields and classes. What is average time between finishing of editing and observing changes in your browser?
NICE SOLUTIONS:
Play framework
Great question! In the java world:
In all java frameworks, the JVM hotswap functionality allows your debugger to make some changes in place, however you are somewhat limited - e.g.: you cannot change class hierarchies, add methods, etc.
There is a commercial product, JRebel, which advertises itself as allowing you to make almost any code change dynamically - I have never been able to get it to work properly myself, but you may be have better luck.
Outside that, I know GWT's dev mode allows arbitrary changes without needing to recompile, I don't think GWT would be a viable competitor to directly writing javascript if it didn't have that feature. However, keep in mind that GWT isn't a traditional web framework, it all runs on the client side.
Finally, there is the Play framework, on the server side, which will also automatically reload java classes with arbitrary chages, when you refresh your browser.
I have used Lift with JRebel without problem. You just have to configure it correctly, start the web server in one terminal, and keep another terminal with maven scala::cc. That will recompile everything automatically (everything necessary if you use the configuration here), and JRebel will instantly make the changes available on the web server.
Apache's Tomcat server for Java servlets has a configuration option to "watch" resources. If a watched servlet or web application is changed (i.e., new code is uploaded to the server), Tomcat automagically reloads it.
From my experience, this feature is somewhat broken when mixed with other advanced features (e.g., user-dirs), but otherwise works as advertised.
You don't need a framework for that. When you run a Java application from eclipse, and modify the source, eclipse will attempt to patch the new code into the running VM. This even works if the methods being replaced are currently executing (method execution will start over at the beginning of the method in such a case). Certain changes can not be hot-deployed, for instance deleting a public method, or changing subtype relationships.
Of course, if your application caches stuff (for instance, setting read during startup), those cache will not be recomputed, though you could probably invoke the parsing method manually in the debugger.

Is it ok to roll your own localization layer in a .NET application?

Is it ok to roll your own localization framework? I would be ok using the default .NET localization behavior (i.e., putting text in resource files named a certain way in the assembly), except that we have localized images and text that need to be rendered in DirectX in addition to WinForms and WPF.
I could put form-specific strings in one place and other strings somewhere else, but I think that it makes more sense to keep everything in one place, not to mention it will help to avoid duplicates (for domain values like Yes/No, etc.). It's also possible we may be moving this tool to another platform in the future, so it would be nice to have all the localization information in one platform-agnostic area.
I realize this is a little subjective, but I'm looking for a best practice here...I've worked on projects that take both approaches. Any thoughts?
I have developed systems in which localisation is implemented via database-stored data and metadata. If your app is already making intense use of a fast database backend, you could create a database-backed localisation layer and use it to store localised information, including textual and non-textual data. It has worked great for us in a few ocasions.
Edit. The details won't fit in here, but basically we mirrored the logic of the key/value resource manager that the Windows API or .NET use. We extended that by allowing resources to be grouped into groups, which can be nested arbitrarily. Resource names can be given as, for example, "ClientManagement.MainForm.StatusBar.ReadyMsg", meaning the ready message text to display on the status bar of the main form in the client management user interface. On app startup, a locale setting is read from a config file and a resource manager initialised with it; all the subsequent calls to the resource manager will be using such a locale setting until explicitly changed. We also built an administrative user interface that allowed us to edit the resources stored in the database, and even add new languages. A final comment: data to be localised is not only labels and icons on screen. Option values in combo boxes, for example, also need to be localised.
We implemented a localization using DB backend. We were able to create a great resource editor which allows "translator" end users to dynamically update translations (cannot do that with a resx!). We were also able to support an approval process and group translations by module such that an entire module could be approved for use in a language, or not.
We also decided to implement the localization provider for Asp.Net, which basically does 'automatic' localization with no code by the developer. This was actually the only difficult part of the project as the interface is not well documented. It was hard to debug because it actually runs within Visual Studio host process. We used a web service to decouple the implementation which greatly simplified things. Another good thing is that the translations are automatically cached so the DB is not working as hard. A bad thing is that when your translation service/back end is down and if you do not precompile your asp.net web site, when the user launches a 'new' page, the compiler might decided NOT to translate the page. This behaviour remains (even after the translation service starts up again) until you force a recompile of the site.

Logging Framework, a good idea?

First of all, apologies for the subjective sounding title. This is intended as a direct question.
At present I am working on a suite of tools:
A C# Windows Service, to primarily
maintain an Oracle database.
A C# Windows Service, (which will be
used on multiple node sites) to
process content of the database.
An ASP.NET web interface to
facilitate management of the overall
"system"
Currently the tho Windows Services have been developed as Console Applications (to ease debugging/development) and I am in the midst of converting these to Services. After testing for a couple days now with these services, I'm finding that I would like to increase the granularity of my logging. I'm finding that I miss Console.WriteLine() and I would like to provide an alternate log source like a flat-file for this type of output. This has lead me to think, "Should I be using a framework, or have I got enough?"
The reason I have mentioned the aspects I am developing is to provide insight to my situation. A "Core" DLL has been created, common across all components, abstracting the interaction layer between the applications and database. It is within this DLL that a class has been created which will attempt to "log to a table in the database" else on fail "log to local Event Log". This is it, that's the extent of logging.
Throughout the aforementioned tools, there are multiple instances of logging not dissimilar to:
Log.LogError("Code", e.Message + "\n" + e.StackTrace);
Although quite basic, this method does make use of reflection to Identify the source of the error.
My Question
Looking at my current logging solution it appears "sufficient" in terms of what it does and how it is integrated with all my solutions. However, I've been looking at logging frameworks (Notably log4net) and their features impress me. The ability to, if needed in the future, add another output format (such as an SMTP server) sounds kind of cool to me! :)
What I would like to know are the benefits of moving to a framework (like log4net)? The extent of how much I will have to adapt my code? Whether or not I am just looking at the greener grass on the other side? And finally, but probably most importantly, am I doing the right thing? Should I just add the ability to my Log class to "LogDebug" and be done with it? The last thing I would want to do is completely overhaul my suite, just for a "basic" feature, but if there are other benefits (to design, reliance, good practice? etc.) I'm interested.
Thanks,
Yes. Using an existing, proven logging framework (such as Log4net) is a good idea.
Log4Net is configurable at runtime (great for tracking down issues in production code).
As a commenter pointed out, it's also very simple to use.
Proper logging is especially beneficial when running code on multiple remote systems, as far as I recall, log4net will let you send your logs to a remote syslog server without much coding overhead (meaning you can view your logs from all machines in one centralized place) doing this will massively reduce the time it takes you to get information relating to a bug or problem with the system, and should also give you an indication of how prevalent the issue is.
As mentioned in other posts, log4net also allows for multiple appenders and multiple log levels, so determining where you want certain log information (i.e. in a database or in a local flat file, hey log4net even lets you spit logs out over telnet) to be stored is an absolute doddle.
As for implementing it, there are several good sites talking you through the setup. How you actually make use of the logging objects that log4net gives you is an architectural choice, but you could simply change the constructor of an object to take a log4net object and from within this object, just use the log4net object as you would Console.WriteLine.
I find the tutorial series here particularly useful, and it'll also go in to more depth than I can here about the benefits and the different ways of configuring log4net.
Yes, you definitely want to use a logging framework. A logging framework will allow you to:
Set the logging levels for the different logger instances.
Set the "appenders" or output for each of the different logger instances.
Perhaps, more importantly, if you use a logging framework, it is very easy to swap out one implementation of the logging framework for another (perhaps a null implementation that simply discards messages); whereas, if you write all your logging statements, directly, swapping out the implementation will be a nightmare.
I think you should use Log4net, simply because it's always better to reuse than to build your own thing. log4net has been used by a lot of developers and are pretty matured.
Think about your maintenance prospect; one or two months down the road, you might need to tweak your custom logging class a bit, to add some multithreading support etc. And when you are fixing the bugs arose from your logging class, you will miss Log4net.
Well one of the bigger benefits is not having to maintain the code yourself. Most of the time, logging frameworks have a lot more functionality than your own solution. Because they are so focused on logging, those frameworks usually are pretty complete in the both functionality and ways to implement it. And then there's reliability; there's nothing worse than a logging framework that's not logging anything because it's bugged. ;)
Take for example ELMAH for ASP.net applications. It also includes notifications, exports to various target formats, etc. Things that are pretty handy but you'll never build yourself unless you really need it.
How many changes to your code are needed obviously depends on both your code and the framework of choice. It's hard to say anything about that.
I am going to give a shout out to NLog (http://nlog-project.org/home) as it doesn't suffer from the 'Straight Java Port - then rewrite' syndrome of most oss .Net libs.
Some key benefits for us were the very fast Logger.IsFooEnabled (volatile read) and the overall performance of the system.
To each its own though, but I personally prefer NLog for my projects (and some of my clients too).
Cheers,
Florian
The advantage of using a good logging framework like Log4Net is that they have a small impact upon your code in terms of lines of code that you have to alter (in other words you only have to alter each existing logging line).
Also, if you are concerned about altering your code if you change frameworks, or if you feel you want to roll your own, then you could always create your own interface to a logging framework. Then you only ever have to change your code in one place after that.
I think sysadmins expect services to log to the application event log in windows.
Look up System.Diagnostics.EventLog, although log4net will write to that too..
The initial statement in the log4j website might help in some of your questions, the underlying principles are the same of log4net:
With log4j it is possible to enable
logging at runtime without modifying
the application binary. The log4j
package is designed so that these
statements can remain in shipped code
without incurring a heavy performance
cost. Logging behavior can be
controlled by editing a configuration
file, without touching the application
binary.
Using a logger hierarchy it is
possible to control which log
statements are output at arbitrarily
fine granularity but also great ease.
This helps reduce the volume of logged
output and minimize the cost of
logging.
In this case there's clearly no need to reinvent the wheel. Most Logging frameworks are somewhat straightforward, so the extend of changes will most likely depend on the size of your existing programs.
if you write your logger class properly it will be easily expendable to any of your needs. Any framework could impress you with many features but another framework is another variable in your debugging process as it can give you an error that does not exists or can make an error by itself in combination with your application. If you are ready to make beta testing for open source software project this is fine...
In your place i would write log class with ability to extend it features you find interesting to you project based on the list of features known frameworks have. I don't see any problem to log something to file and then send it over smpt, just one small function does the job.
Moreover, you can write your own class which will be pretty abstract and put your basic code in there, if you will ever need to use external framework for testing you class would be able to use it with minimal impact on code. Just take a look how there frameworks are implemented on the code level.
think of that you will need to learn how to properly use these frameworks when your only needs for now to log very small part of it...

Categories

Resources