Using ApplicationDbContext in an extension method - asp.net-core-mvc

I am currently working on an ASP.NET Core application for internal use. This application should list dates and depending on the date some operations are permitted while others are not. I can perfectly use the scaffolded views and they display exactely what I want with one exception:
If an operation is not permitted I want to display them greyed out.
My idea was to add an extension method named IsSpecialOperationPermitted to DateTime so I can easily use dateTimeInstance.IsSpecialOperationPermitted.
The method "IsSpecialOperationPermitted" depends on some calculations and another table in the database. Now, to use my extension method I would like to access that table. Usually I'd create an instance of ApplicationDbContext and query that table.
For ASP.NET Core I have a feeling this is not the correct approach but that I should request an already existing ApplicationDbContext. Usually this ApplicationDbContext is injected more or less automatically but I don't have an ApplicationDbContext in my extension method.
What would be the "correct" way to request an ApplicationDbContext in my extension method?

You are trying to build an abstraction above a DateTime type which is perfectly fine. However, if you require a db context to perform your operation, you should explicitly take a DbContext as argument to signal that your method needs at least to read from it.
You could write something like this
public static class DateTimeExtensions
{
public static bool IsSpecialOperationPermitted(this DateTime value, ApplicationDbContext context)
{
// do here your computation
}
}
On the other hand, you could reverse it, and extend the DbContext:
public static class DbContentExtensions
{
public static bool IsSpecialOperationPermitted(this ApplicationDbContext context, DateTime value)
{
// do here your computation
}
}
The latter, in my opinion, is clearer.
Keep in mind that extension methods are designed to work with documented side effects and certain operations that theoretically could be "nice to have" as extension methods, could result too cryptic in the long run.
Also, you should be aware that if the caller has pending changes to the context, your method won't see them unless you inspect the Local property.

Related

Mocking objects instantiated inside a class to be tested

So I am learning TDD using the many resources here on SO, but I just cant seem to figure out what I do with private/protected objects instantiated inside a given method/constructor. Lets say I have a connection string. That connection string is used to construct a Sqlcommand or Sqlhelper. Well I want to mock that Sqlhelper so that when I test other methods I don't have to rely on the results coming from my database. But I cant access the Sqlhelper.
How do I work around this?
Its generally best (except for a very few rare occasions) to test only the public interface of the class as a whole. Try not to use one of the workaround methods (such as private objects) unless you really have to. Accessing private members of classes in tests tends to look good at first as theres less code to write to test an object, however when things start to change (and they will) anything accessing the internals of a class makes it more difficult to change its implementation, this can be crippling to a project if most of the tests are written in this way.
In this particular case you are interacting with an external dependency outside of your control (i.e. SqlHelper), I'd recommend wrapping the SqlHelper object in your own object that implements an ISqlHelper interface (or a more reasonably named interface for your scenario).
e.g.
public interface ISqlHelperWrapper
{
void ExecuteQuery();
}
Then inject this in through the constructor of you're object under test:
public class SqlConsumer
{
private ISqlHelperWrapper _sqlHelper;
public SqlConsumer(ISqlHelperWrapper helper)
{
this._sqlHelper = helper;
}
public void QuerySomething()
{
this._sqlHelper.ExecuteQuery();
}
}
Not only is this a better design (you've isolated the sql implementation specific stuff from the SqlConsumer, and given it fewer reasons to change). But you can now mock the ISqlHelper instance using a mocking framework as well as switch the implementation on construction.
Given your connectionstring scenario above, you could initialise the sqlhelperwrapper (There are better names for this) with the connectionstring and your SqlConsumer object doesn't need to know about it.

How can I modify the fixture my custom theory data attribute creates for AutoFixture?

I'm really appreciating the power of AutoFixture coupled with XUnit's theories. I've recently adopted the use of encapsulating customizations and providing them to my tests via an attribute.
On certain occasions, I need a one-off scenario to run my test with. When I use an AutoDomainDataAttribute, like above, can I ask for an IFixture and expect to get the same instance created by the attribute?
In my scenario, I'm using MultipleCustomization by default for collections, etc. However, in this one case, I want only a single item sent to my SUT's constructor. So, I've defined my test method like so:
[Theory, AutoDomainData]
public void SomeTest(IFixture fixture) {
fixture.RepeatCount = 1;
var sut = fixture.CreateAnonymous<Product>();
...
}
Unfortunately, I'm getting an exception when creating the anonymous Product. Other tests work just fine, if I ask for a Product as a method parameter with those attributes. It's only an issue in this particular case, where I'm hoping that the fixture parameter is the same one created by my AutoDomainDataAttribute.
Product's constructor expects an IEnumerable that normally gets populate with 3 items, due to the customizations I have in-place via AutoDomainData. Currently, my DomainCustomization is a CompositeCustomization made up of MultipleCustomization and AutMoqCustomization, in that order.
The exception is: "InvalidCastException: Unable to cast object of type 'Castle.Proxies.ObjectProxy' to type 'Product'."
If you need the same Fixture instance as the one active in the attribute, you can inject the Fixture into itself in a Customization, like this:
public class InjectFixtureIntoItself : ICustomization
{
public void Customize(IFixture fixture)
{
fixture.Inject(fixture);
}
}
Just remember to add this to your CompositeCustomization before AutoMoqCustomization, since IFixture is an interface, and if AutoMoqCustomization comes first, you'll get a Mock instance instead - AFAICT, that's what's currently happening with the dynamic Castle proxy.
However, if you really need a Fixture instance, why not just write a regular, imperative test method:
[Fact]
public void SomeTest()
{
var fixture = new Fixture().Customize(new DomainCustomization());
fixture.RepeatCount = 1;
var sut = fixture.CreateAnonymous<Product>();
// ...
}
That seems to me to be much easier... I occasionally do this myself too...
Still, I wonder if you couldn't phrase your API or test case in a different way to make the whole issue go away. I very rarely find that I have to manipulate the RepeatCount property these days, so I wonder why you would want to do that?
That's probably the subject of a separate Stack Overflow question, though...

Command Pattern in .NET MVC 3 (removing junk from the controller)

I am trying to implement this Command Pattern on my .NET MVC 3 application, specifically for saving edits to a Thing. I am undecided on how to proceed. Before I get to the actual question, here is the simplified code:
public class ThingController
{
private readonly ICommandHandler<EditThingCommand> handler;
public ThingController(ICommandHandler<EditThingCommand> handler)
{
this.handler = handler;
}
public ActionMethod EditThing(int id)
{
...build EditThingViewModel and return with View...
}
[HttpPost]
public ActionMethod EditThing(int id, EditThingViewModel vm)
{
var command = new EditThingCommand
{
...not sure yet...
};
this.handler.Handle(command);
...redirect somewhere...
}
}
My EditThingViewModel is wholly disconnected from my domain, which consists of POCO classes. It seems like my EditThingCommand should look like this:
public class EditThingCommand
{
Thing ModifiedThing;
}
However, building ModifiedThing would then still be happening in my controller. That's the majority of the work in this case. By the time ModifiedThing is built (and the "old" timestamp applied to it for optimistic concurrency checking), all that's left is for command to call Update on my data context.
Clearly there is value in being able to easily decorate it with other commands, but I'd also like to be able to move the construction of ModifiedThing outside of my controller. (Perhaps this question is really just about that.) EditThingCommand is in my domain and doesn't have a reference to EditThingViewModel, so it can't go there. Does it make sense to have another command in my presentation layer for mapping my viewmodel to my poco entity?
I created an EditThingPostCommand outside of my domain, which takes the EditThingViewModel as a parameter. The EditThingPostCommandHandler is responsible for creating the EditThingCommand and calling its handler.
It works, but I'm not going to assume that's the best answer to my question. Arguably most of what the EditThingPostCommandHandler is doing could be done in a custom AutoMapper configuration, which would still serve the purpose of cleaning up the controller action method.
After several months of using this pattern on other projects, it is apparent to me that the commands on this particular project were simply too general and therefore too complex, requiring too much setup. It would have been better to create, for example, an EditThingTitleCommand and a MoveThingPiecesCommand and so on, and call them from their own ActionMethods.
In other words, when using the command pattern, don't just use the commands as replacements for typical CRUD operations. With more specificity comes more benefit.

Static methods, non static members - Data Access Layer/Business Layer

OK, i am creating a web application. I am using MVC3. I have ViewModel for every view and also I have Data Model that supports viewModel and does the actuall CRUD operation in my sql table, while my viewModel validates and alters data as necessary.
Here is a question. The way I have been coding is
public class MyClassViewModel
{
public string member1{get;set;}
public int member2{get;set;}
public static GetAllMembers(MyClassViewModel obj, out string strErrMsg)
{
// code goes here, read operation
}
public static UpdateMyClass(MyClassViewModel obj, out string strErrMsg)
{
// code goes here, write operation.
}
}
Both My ViewModel and DataModels have been coded this way, My Controller on HttpPost just do something like this..
MyClassViewModel.UpdateMember(obj,out strErrMsg)
Since its mvc on every post it creates on a strongly typed view, a new object of my ViewModel, hence non static members are different and are not shared between sessions.
I am using Linq and therefore on each static method of my DataModel i use
var db = new MyApplicationDataContext()
to get my linq classes and work on them. This solves my open/close reader problems.
My question is, are there any issues regarding concurrency with this design? I know I might have problems in changing my data layer if it is not designed via interface, but I highly doubt that is necessary based on my application.
You are essentially using the factory design pattern. That's OK pattern to use for this; each static method has its own context, and that's OK too. You always have to worry about concurrency; however, the LINQ to SQL architecture has concurrency detection built in and throws a ChangeConflictException when a concurrent change has been made in reaction to this.
I would also highly recommend that you are disposing your contexts properly at the end of each static method call, because you could leave open connections to the database which can cause performance problems.
Also, another problem you may run into is interlinking data; you cannot link two objects together by reference that were created from different contexts. And in LINQ to SQL, there is no way to explicitly detach an object...

Serialize VM vs state class

After my wonderings on the events registration (you can find here ViewModel Event Registration and ViewModel Lifetime), now I'm thinking about viewmodel tombstoning:
In case of Tombstoning, is the ViewModel serialization a good approach ?
I'm thinking about the case in which different viewmodels have a reference to the same class. In case of Viewmodels serialization and deserialization the referenced class instance could have duplicated instance, isn't it ?
Wouldn't be better to have specialized state classes whose unique purpose in to contain all the app data, everyviewmodel get data (i mean reference to the data) from there and update the data in there and the app think only to serialize those specialized class ?
Any experience on this subject is appreciated.
Regards
SkyG
Caliburn Micro has a lot of this built in to the framwork allowing you to save properties of a view model or the entire graph to both phone state and app settings. You just need to create a class and inherit from StorageHandler.
public class PivotPageModelStorage : StorageHandler<PivotPageViewModel>
{
public override void Configure()
{
this.ActiveItemIndex().InPhoneState().RestoreAfterViewLoad();
}
}
And to your other posted question. CM has a nice way of handling the forced view first approach on the phone. It allows you to do page navigation by specifying the VM and it will handle the rest. And as a bonus, if you specify parameters to pass CM will pull them off the query string and populate properties on the target VM.
public void GotoPageTwo()
{
navigationService.UriFor<PivotPageViewModel>().WithParam(x => x.NumberOfTabs, 5).Navigate();
}

Resources