Website Architecture - Control/Object Loading Based on Config? - c#

I am building a site which will need to change slightly in certain markets. For example, in a UK market, the signup form needs to perform address validation (already have this working), and on a Belgium site, we need to verify a person with a web service (already have this working). Otherwise, signup functionality is basically the same. We have these two sites working independently, but we'd like to merge them into a single codebase which can support either option based on config.
My initial thought was to use a configuration value to say "This is a UK site" or "This is a Belgium site" and display the pages based on this setting.
Ideas:
Dependency injection to load controls dynamically based on config
Factory pattern to use Reflection/Activator and load dynamically based on config
Config transforms to load different user controls by setting a tagname/tagprefix
Other?
Does anyone have any first thoughts on recommendations on where I can find inspiration for this type of design?

I would recommend to keep it as simple and minimal as possible.
Simply create something like IPersonValidator which has a .Validate(PersonDetails) method and returns an array of errors.
Edit:
On the config side, you could create a custom config section of the following structure:
<DomainSpecificSettings>
<Key name="validator">
<Value domain="www.yoursite.co.uk" value="firstValidator" />
<Value domain="www.yoursite.de" value="secondsValidator" />
</Key>
</DomainSpecificSettings>
One more thing - you don't need to use Activator. You could have a singleton Validators store which holds a single instance for each validator type and knows how to find the correct Validator according to the database config setting of the currently viewd market:
ValidatorsStore.GetValidator(string configValue).Validate(PersonDetails).
The design in this case may easily become a overkill for such a simple task. My approach is to first make it work good enough, and only then check if you need to make it more robust. Most chances are that you won't.

First, as you mention “loading user controls”, think it will be better to separate the presentational part of the implementation from the logic/validation itself. You could create(or refine) a generic user control that works for all the countries but calls logic that does the address validation in case of the UK or nothing in case of BE. Single responsibility principle or separation of concerns in the MVC world.
Also use same principles separate the different components of the page in different user controls with their logic. Every component with have their own validation before calling the final signup/register. This way you can notify the player of a validation error in the input data without having to require the full player information to do the signup. Once the full information for the player is provided and validated you can call the signup that just saves the player in the database.
About the StrategyProvider class to decide which logic to call, agree with Uri, we are going to have many places where the logic varies a between countries. But it is not something we could setup with IoC container? Don’t know much about IoC containers but if logic is “static” (when you are in website it does not change depending on request) could be possible to setup it at application start time.
Another possibility is to use the SOA pattern and call different services depending on the website you are in. (same servuces end points could be setup in config). Services for the different countries can have different logic but return a class that follows a common interface (use Adapter pattern).

Related

Handling code of multiple ASP.NET websites based on the same template

I am using ASP.NET MVC and have to develop and deploy multiple websites based on a first website.
There are variation in some controllers, some views, some scripts and some models, and the Database are different on each website (mainly columns are differents but table names remains the same).
Is there a way to handle such a thing in a single Visual Studio Project, in order to make maintaining easier, and be able to add common feature easily on every website ?
Currently, I copy the pilote project into a new VS project, and change all the variation. But I find it's not an ideal situation (because of maintaining/improving).
I have implemented something like that years ago and can give some general advice you might find useful.
First of all developing app with such "multitenancy" has nothing to do with MVC pattern itself. You can do that without MVC :D. Second, if the websites supposed to work with different business domains I am afraid there is no generic way to do what you want. In my case it was just a number of e-commerce platforms.
Anyway, consider next things.
1.Think about using sub-domain approach if you can. It will free you from stupid routing and cookies shenanigans. Basically you can map *.yourdomain.com to one app and handle the necessary logic related to tenant easily. So in my case it was an application that behaved differently depending on provided url, not route, but sub-domain, 'superclient.yourdomain.com' for example. Its not always possible or good idea, but think about it.
2.Dependency Injection everywhere. Well, its useful in general but in your case is absolute must have - try abstract any tenant specific logic in separate types and init them in one place. Its everything related to localization, timezone settings, app theme, branding info on the app header etc. Just initialize and inject where its needed. If you have something like
if (website1) {
showBlockOne();
} else if (website2) {
showBlockTwo();
} else if (website3) {
showBlockThree();
}
then you doing something wrong, its a road to insanity. It should be something like
_currentTenantViewContext.ShowBlock();
So its polymorphism over conditional operators in most cases.
3.In my case the requirement was to create an app which can work with any language so I had to handle that issue on database side as well. The problem is that if usually you have lets say for example ProductType table in database with Id and Name, in multitenant application its not that simple. My solution was to create two tables - ProductType with Id and Code fields and ProductTypeLocalization table with Id, ProductTypeId, LanguageId, Value fields to handle this problem. Requirement also was to make this values editable from admin panel...
I don't know is it the case for you, but if yes think about it before the shit hits the fan in future.
4.For situations where you need some specific fields in some database table only for one site its not a good idea to spawn them freely (in general). Consider using some generic format for that, like JSON or XML. If you have few additional text fields for specific website in some table just create one field (call it ExtraSettings or something) and store this strings as JSON in that one field. Of course you have to handle this data in separate way, but its about dependency injection again.
Also you can use NoSQL for that.
5.Provide feature toggling, different websites requires different blocks to be displayed, rules applied etc. You have to have some way to on/off them for particular website(tenant) without recompile/redeploy.
Hope it helps.

C# - Do EventSource Providers have to follow the Name-Product-Component naming pattern

I see in documentation that the proper naming convention for a event provider should be < CompanyName>/< ProductName>/< Component> as per documentation here:
Do use the EventSourceAttribute’s Name property to provide a descriptive, qualified name for the ETW event provider represented by your event source. The default is the short name of your event source type, which can easily lead to collisions, as ETW provider names share one machine-wide namespace. An example of a good provider name “--”. Following this 3-element convention will ensure Event Viewer displays your event logs in a logical folder hierarchy: “Application and Services
Logs/< CompanyName>/< Product>/< Component>”.
Is it possible to create a stucture containing a company and multiple products?
I am trying to understand the behavior as when I register two manifests in the format of "CompanyName-Product' they will show up in the logs as two separate logs and not nest them under the CompanyName root.
However if I include a component name with such as "CompanyName-Product-Compontent1" each then they will properly nest under the root. Is it not possible to create a log structure without components?
For example take Microsoft's logs:
Microsoft
--> Windows
-->.....
Microsoft
--> SQLServerDataTools
I can see that every component more or less goes under the Windows directory but it seems that the provider names that just have the company and product without a component such as "Microsoft-SQLServerDataTools" goes into its own log. Is there a way I can nest this under the same company name?
You don't have to follow this approach, but is the recommended way to make it more organized and easy to maintain, otherwise you would end up with random names like 'mycompany-product', 'mycompany.product', 'mycompanyproduct', 'product-mycompany' and would be painfull to manage, as they don't follow a pattern. The naming is just a recommendation in this case and you put the name you want.
Regarding the eventsources, each name is a different entity with their own guid, if you see them nested, is probably because the tooling you are using nest them based on this approach, but they don't depend on each other.
To manage them, you can follow two approaches:
Create one event source per component\service:
This approach, will generate one independent manifest for each of your event sources, and you will manage them isolated of each other. You can extend your service without fear of braking others. You can also filter them in isolation by their name or GUID.
Create one event source and share among all service:
This way, you will create a big event source with your product name and share among components, this approach is a bit delicate to maintain, as you have to keep the version in sync with your projects, and changes will propagate to all components, to separate internal event for specific components you can use Keywords. I wouldn't recommend this approach.

Need help avoiding the use of a Singleton

I'm not a hater of singletons, but I know they get abused and for that reason I want to learn to avoid using them when not needed.
I'm developing an application to be cross platform (Windows XP/Vista/7, Windows Mobile 6.x, Windows CE5, Windows CE6). As part of the process I am re-factoring out code into separate projects, to reduce code duplication, and hence a chance to fix the mistakes of the inital system.
One such part of the application that is being made separate is quite simple, its a profile manager. This project is responsible for storing Profiles. It has a Profile class that contains some configuration data that is used by all parts of the application. It has a ProfileManager class which contains Profiles. The ProfileManager will read/save Profiles as separate XML files on the harddrive, and allow the application to retrieve and set the "active" Profile. Simple.
On the first internal build, the GUI was the anti-pattern SmartGUI. It was a WinForms implementation without MVC/MVP done because we wanted it working sooner rather than being well engineered. This lead to ProfileManager being a singleton. This was so from anywhere in the application, the GUI could access the active Profile.
This meant I could just go ProfileManager.Instance.ActiveProfile to retrieve the configuration for different parts of the system as needed. Each GUI could also make changes to the profile, so each GUI had a save button, so they all had access to ProfileManager.Instance.SaveActiveProfile() method as well.
I see nothing wrong in using the singleton here, and because I see nothing wrong in it yet know singletons aren't ideal. Is there a better way this should be handled? Should an instance of ProfileManager be passed into every Controller/Presenter? When the ProfileManager is created, should other core components be made and register to events when profiles are changed. The example is quite simple, and probably a common feature in many systems so think this is a great place to learn how to avoid singletons.
P.s. I'm having to build the application against Compact Framework 3.5, which does limit alot of the normal .Net Framework classes which can be used.
One of the reasons singletons are maligned is that they often act as a container for global, shared, and sometimes mutable, state. Singletons are a great abstraction when your application really does need access to global, shared state: your mobile app that needs to access the microphone or audio playback needs to coordinate this, as there's only one set of speakers, for instance.
In the case of your application, you have a single, "active" profile, that different parts of the application need to be able to modify. I think you need to decide whether or not the user's profile truly fits into this abstraction. Given that the manifestation of a profile is a single XML file on disk, I think it's fine to have as a singleton.
I do think you should either use dependency injection or a factory pattern to get a hold of a profile manager, though. You only need to write a unit test for a class that requires the use of a profile to understand the need for this; you want to be able to pass in a programatically created profile at runtime, otherwise your code will have a tightly coupled dependency to some XML file on disk somewhere.
One thing to consider is to have an interface for your ProfileManager, and pass an instance of that to the constructor of each view (or anything) that uses it. This way, you can easily have a singleton, or an instance per thread / user / etc, or have an implementation that goes to a database / web service / etc.
Another option would be to have all the things that use the ProfileManager call a factory instead of accessing it directly. Then that factory could return an instance, again it could be a singleton or not (go to database or file or web service, etc, etc) and most of your code doesn't need to know.
Doesn't answer your direct question, but it does make the impact of a change in the future close to zero.
"Singletons" are really only bad if they're essentially used to replace "global" variables. In this case, and if that's what it's being used for, it's not necessarily Singleton anyway.
In the case you describe, it's fine, and in fact ideal so that your application can be sure that the Profile Manager is available to everyone that needs it, and that no other part of the application can instantiate an extra one that will conflict with the existing one. This reduces ugly extra parameters/fields everywhere too, where you're attempting to pass around the one instance, and then maintaining extra unnecessary references to it. As long as it's forced into one and only one instantiation, I see nothing wrong with it.
Singleton was designed to avoid multiple instantiations and single point of "entry". If that's what you want, then that's the way to go. Just make sure it's well documented.

Extensibility framework/pattern/good practice for Web services?

I'm currently working on a large real-time OLAP application. All data are hold in RAM (a few gigabytes) and the common tasks involve brute scanning over the large quantity of that data (which is fine). The results of processing are exposed via a Web service (singleton/multithreaded) and presented using Silverlight-based client.
The problem is that various customers need different functionality/algorithms and I don't know how to provide extensibility on the server-side. For the client side (Silverlight) I can use MEF/Prism, but I'm not sure what would be a good approach to tackle this problem on the server.
Please note that ideally other web-services should have a direct access (i.e. without marshaling) to the data of the main/current service which holds the large data model.
Are there any:
a) frameworks/libraries
b) patterns
c) good pracitces
which would help me to modularize the application and make the selection of desired modules and their deployment relatively easy?
Sounds to me like Dependency Inversion is required: isolate logical parts of the system (algorithms, etc) by defining interfaces, then use a DI / IoC framework to load the desired implementation at runtime (or on application start, etc).
I haven't used Ninject, but plenty of people love it, so you could try that; there's also Spring.Net.
Good Practices:
Ensure you have clear precise logging so you know what's being used and when.
Think about whether you want a 'default' implementation to load if the desired one fails, or whether you deliberately want to fail so that the wrong data isn't returned by mistake (such as the use of a different algorythm).
I've found that using attributes to decorate injectable modules is really helpful (especially in a web-based system that you don't have immeadiate access to) one reason for this is that you can build pages or controls that list all the known / available implementations at runtime.
You can also use the attribute approach to build a UI that lets users select which one they want; I use it for an open source web-application framework I built: http://www.morphological.geek.nz/Morphfolia/Capabilities/AttributeDriven.aspx

Proper way to Create/Update/Delete hierarchical data

So I have a structure like this:
Widget:
Component 1:
Component 2:
Component 3:
...
Component n:
I'm building an ASP.NET MVC web app that as part of its functionality will allow a user to create a Widget object and assign Component objects (which have a number of properties) as "children" of the Widget object. Users might have no Components or might add 50. In addition, they may edit a Widget object and arbitrarily remove or change Component properties.
Everything in the application is working but I'm not happy with the way this is structured. On Submit currently, I submit all Components with ALL their properties. I delete all components currently associated with this Widget and then enumerate over each Component and re-add it.
...But I'm not happy with this solution. For some Widgets with a massive amount of components (say 500) this process can be time consuming even if the user only changed one component. But the alternative (tracking Creates/Updates/Deletes on a per Componenent basis) seems really painful to build.
I'm sure that I can do this better, so I'm interested in knowing what sort of patterns can be applied to solve this problem (generally speaking) and particular in the context of web applications.
Why is tracking the Create/Update/Delete so much harder? Take a look at my response to a similar question about finding the differences between what is in your repository and what is being posted back. Provided each Component has a unique ID (which it sounds like it does), it shouldn't be that difficult. Also it should be somewhat quicker for larger Widgets with lots of Components as you're not rebuilding its list every time.

Categories

Resources