Initiate Properties automatically using StructureMap - asp.net

If i have N numbers of classes on each of them i am declaring for example property which contains some app setting values from config file.
public static IAppSettings AppSettings { get; set; }
I want to populate this property automatically when class is created.
I am thinking to achieve this goal using StructureMap.
I want to "say" somehow only in one place, that if class contain this property populate it.
May be some one came across this and have any ideas?
ASP.NET/ASP.NET MVC, ConsoleApp/WinForms

If i have N numbers of classes on each
of them i am declaring for example
property which contains some app
setting values from config file.
You should consider having those N classes derive from a base class which contains this property:
public abstract Base
{
public IAppSettings AppSettings { get; set; }
}
then if you want to have this property automatically populated by StructureMap you should no longer instantiate them manually but always ask the container for a value.
For example in a ASP.NET MVC application I would use constructor injection to pass the value of IAppSettings to all the controllers that need it.

It sounds like you want a variation of the SettingsScanner described in this post: http://lostechies.com/joshuaflanagan/2009/07/13/how-we-handle-application-configuration/
You can get the full code for the scanner and ISettingsProvider from The FubuMVC source code:
https://github.com/DarthFubuMVC/fubumvc/blob/2e7ea30391eac0053300ec0f6f63136503b16cca/src/FubuMVC.StructureMap/SettingsScanner.cs

Related

How to make changes in POCO file in Entity Framework so changes are retained

I am using Database First approach in Entity Framework. I have a table which contain one field called CustomerName and it is NOT NULL.
The generated POCO is given below.
public partial class Customers
{
public string CustomerName {get; set;}
}
I have two questions.
How can I make this a required field so my code would become like this (shown below). As you know POCO is automatically generated so after I do this and update model from database, all my code is removed.
public partial class Customers
{
[Required]
public string CustomerName {get; set;}
}
Second question is why EF automatically doesn't apply [Required] with this field when generating code? The field is NOT NULL in database so shouldn't this be done automatically without having to manually write [Required]?
Here's the answer if you're using EF6:
Notice that the generated Customers class is partial, we're going to leverage that. First, we'll need to create a new Customers partial class with the exact same name within the exact same namespace:
namespace WebApp.TheSameNamespaceAsTheGeneratedCustomersClass
{
public partial class Customers
{
}
}
Now both of these partials make up the same class it's just that the source code of this class is now split in different files, one of which is generated by the tool and one that you wrote by hand. The difference of course is that you can change the latter without it getting rewritten all the time.
Note that the namespace has to match but the folder that contains the class file doesn't.
Now we need to create the metadata class that contains all the necessary attributes and decorate our Customers partial with it, like so:
namespace WebApp.TheSameNamespaceAsTheGeneratedCustomersClass
{
[MetadataType(typeof(CustomersMetadata))] //decorating the entity with the metadata
public partial class Customers
{
}
public class CustomersMetadata //metadata class
{
[Required] //your data annotations
public string CustomerName { get; set; } //the property name has to match
}
}
and that's it.
Is it verbose? Yeah, but that decision was made when db first was chosen.
A word of caution:
If you're doing this to use entity classes as data models in MVC, generally speaking, that's considered a bad practice. The recommended way is to create separate model classes and map data from and to entities. There are some security reasons for that, which you should research before you make the final decision.
If you are using ef core then try adding --data-annotations flag in your scaffold command.
Please refer for more info: https://learn.microsoft.com/en-us/ef/core/managing-schemas/scaffolding?tabs=dotnet-core-cli#fluent-api-or-data-annotations
EF doesn't have any means of validating your data in your POCO classes when it generates sql. That is why it is recommended that we should have a corresponding model object layer (corresponding model classes for your entities) that your application can manipulate. You can use something like AutoMapper for mapping between models and entities. In this way you can modify your model classes without impacting your EF entities.

ASP.NET Core MVC application dependency injection issue when using BaseController

Recently i tried to create a MVC application using ASP.NET Core 2.0 and i had some values defined in appsettings.json,
"MySettings": {
"WebApiBaseUrl": "http://localhost:6846/api/"
}
In order to read these values i have added
services.Configure<MySettingsModel>(Configuration.GetSection("MySettings"));
above line in ConfigureServices method in Startup.cs
and in my home controller i have added
private readonly IOptions<MySettingsModel> appSettings;
public HomeController(IOptions<MySettingsModel> app)
{
appSettings = app;
}
MySettingsModel class is just a model with property same as key define in appsettings.json.
by this method i'm able to read the value of this key.
Now my issue is that i want to use this key in many controllers so i don't want to repeat this code in every controller so what i did was i created a BaseConntroller, added its constructor and i got my values there. But when i inherit other controllers with my BaseController , it throws me an error and tells me to generate it's constructor, so basically it tells me to add constructor in every controller which is what i wanted to avoid.
How can i achieve this?
You can see the image for the error
And these are the potential fixes that it shows me.
This is just basic C# inheritance. Derived classes must re-implement constructors on base classes (at least the ones you want or need). The only exception is the empty constructor, which is implicit. In other words, you simply need:
public class HomeController : BaseController
{
public HomeController(IOptions<MySettingsModel> app)
: base(app)
{
}
And, of course, you need to change the accessibility of the base class field to protected instead of private. Otherwise, derived classes will not be able to access it.
Of course, this doesn't really save you that much. However, there's no free lunch here. Like I said, this is a limitation of C#, itself, so you have no choice. Although, it's worth mentioning, that while this can sometimes be annoying, it's actually a kind of useful feature of C#. You can look at any class and see exactly what constructors it has available, without having to trace down all its ancestors.
Actually, there is a good solution here:
https://stackoverflow.com/a/48886242/2060975
I am mostly using this method.
[Authorize]
[ApiController]
public abstract class ApiControllerBase : ControllerBase
{
private IOptions<AppSettings> _appSettings;
protected IOptions<AppSettings> appSettings => _appSettings ?? (_appSettings = (IOptions<AppSettings>)this.HttpContext.RequestServices.GetService(typeof(IOptions<AppSettings>)));
...
}
I hope it helps someone:)

How can I improve our CM.AppSettings references

ASP.NET 3.5
Classes throughout our solution referenced ConfigurationManater.AppSettings[""] to get appSettings (from web.config).
We decided we weren't happy with that. Folks were mistyping appSetting key names in code (which compiled fine), and it was cumbersome to track usages. And then there's the duplicated strings throughout the codebase as you reference the same appSettings all over the place.
So, we decided that only one class would be allowed to reference the ConfigurationManager, and the rest of the solution would reference that class when it needed the value of a certain appSetting. ConfigurationManater.AppSettings[""] was static, so we exposed a bunch of static read-only properties off of our single Settings class.
public class Settings {
public static string Foo {
get {
return ConfigurationManager.AppSettings["Foo"];
}
}
}
That worked pretty well, until we needed to mock the settings in our tests. We created an interface to enable our mocking (was this a mistake of any kind?).
public interface ISettings {
string Foo {
get;
set;
}
}
public class Settings : ISettings {
public string Foo {
get {
return ConfigurationManager.AppSettings["Foo"];
}
}
}
And now we're injecting the ISettings instance as a dependency of the objects which use settings values (the class/interface are in a project that everyone can reference without problems).
In places where we can't inject an existing instance (e.g. Global.asax), we construct a new instance into a static field.
Given all of that, what would you recommend we change, and why?
Using an interface to represent configuration is a good idea. But your implementation looks a little off.
Joshua Flanagan wrote about writing application configuration code in a way that specific configuration sections can be injected into your code. This is a good idea, as it really decouples your code from worrying about details behind configuration. Have a read.
I think this will address the issue you are having re. testability.

Remove field in wsdl in Asp.net webservice

I'm generating dto classes with a template engine and would like to exclude some properties in an asmx webservice, what, if possible, is the best way to do this?
Ex:
[WebMethod]
public ProductPackages GetPackages()
{
ProductPackages packages = new ProductPackages();
packages.Packages.add(new PackageDTO());
return packages;
}
The PackageDTO contains some properties that's not relevant for this service.
But as the class can be regenerated any time i can't apply [XmlIgnore] to the fields.
So I'm looking for a way to apply a "exclude list" without touching the actual class.
Above is just an example, the template engine generates dto's for all tables in a given project, and I would like to be able to use them in services without needing to maintain a big bunch of nearly identical classes.
Just hit the same problem. You can exclude fields by marking them as internal.
public class Order
{
public double OrderPrice;
internal double ProfitMargin;
internal string TheTruthAboutThisCustomer;
}
If you don't want to return a field or property, then don't have it in the object you return! It's as simple as that.

Adding new methods to LINQ to SQL generated classes

I am new to LINQ. I just dragged all my database tables onto the designer in a LINQ to SQL dbml. All my relationships are correct and look nice in the designer. I am able to pull data using simple LINQ code. I want to add my own methods now but don't want to blow away my changes if (when) I need to regenerate my dbml. I am guessing I just create a new class file and setup partial classes of the generated classes. Is this correct? For example, I have a generated class called SystemUser which contains the columns SystemUserId, Username, Password, PersonId, SecurityQuestionId, SecurityQuestionResponse. I want to add a method called void Authenticate() and a new property called bool Authenticated. Basically I want to pass in a username and password to Authenticate() and set the Authenticated property based on finding a matching user, etc. Where and how would I do this?
The LINQ-generated classes are partial classes, meaning you can extend them by creating your own partial classes or partial methods.
In your case, you can create a partial class for your SystemUser, and then add your method(s) in there. They will not be overwritten if the DBML file is regenerated.
Something like:
public partial class SystemUser
{
public bool Authenticated { get; set; }
void Authenticate()
{
//Perform custom logic here.
}
}
Take a look at using a Partial class... it might fit your situation very nicely.
If you just want your class to have a new method you are correct create a new file and use partial class.

Resources