Share code between projects in a solution in Visual Studio 2008, when building a common assembly is impossible - visual-studio

I create an add-on for the product Foo. There are different versions of Foo, namely version 1, 2, 3 and 4.
These versions have a mostly compatible API, but not fully.
I currently have 5 projects:
DotNetCommon - here are the common methods which could be used if I create an add-on or something other than the Foo product.
FooOne
FooTwo
FooThree
FooFour
The Foo*-projects contains the add-in for version 1-4 of Foo.
There are a lot of duplicated files in the Foo*-projects, as there are a lot of things in the API which are identical for all versions of Foo. It would be nice to separate out everything which is common for all Foo-versions.
Why not just create a common assembly for all versions of Foo called FooCommon?
If I would put all classes which are common for all versions of Foo into a new library project, I would still have to choose which version of Foo the new FooCommon should reference. As said, they are not identical.

Create an interface containing the common methods:
public interface IFoo
{
void CommonMethod1();
void CommonMethod2();
}
Create an abstract base class from IFoo:
public abstract class FooBase : IFoo
{
// Implement the common calls here
public void CommonMethod1()
{
// concrete shared code goes here
}
public void CommonMethod2()
{
// concrete shared code goes here
}
}
Create your one-off code from the FooBase:
public class FooOne : FooBase
{
// concrete code specific to FooOne goes here
}
public class FooTwo : FooBase
{
// concrete code specific to FooTwo goes here
}

Related

Error if the [AssemblyInitialize] already exists in the test project with Specflow

I've updated Specflow from the 3.0.225 to the 3.1.62 and I received the error Tests_Integration_MSTestAssemblyHooks: Cannot define more than one method with the AssemblyInitialize attribute inside an assembly.
The reason is obviously that I'd had the [AssemblyInitialize] attribute in my project already. How can I fix it?
The reason is that Specflow generates another file in the background which has the AssemblyInitialize/AssemblyCleanup hooks defined. In order to fix that one should use the hooks provided by Specflow, namely BeforeTestRun/AfterTestRun. Like this:
[Binding] // add the Binding attribute on the class with the assembly level hooks
public abstract class SeleniumTest
{
// it used to be [AssemblyInitialize]
[BeforeTestRun]
public static void AssemblyInitialize(/* note there is no TestContext parameter anymore */)
{
// ...
}
// it used to be [AssemblyCleanup]
[AfterTestRun]
public static void AssemblyCleanup()
{
// ...
}
}

Automapper in MVC Core 2.0 services.AddAutoMapper() behavior

I have a solution like this:
MVC Core 2.0 application <-> Business Class library <-> Domain class library
(ViewModel) <- P1 -> (Dto) <-P2-> (Domain entity)
I created Automapper profiles in each MVC and Business projects for mapping ViewModel<->Dto (P1) and Dto<->Domain entity (P2). P1 profile&map is in MVC project, P2 profile&map is in Business library.
I then made a xUnit test project which creates a Dto object and sends it to a Business Service, inside the unit test on init I call:
Business.App.AutoMapperConfiguration.Configure();
And this unit test works exactly as expected.
I then do the same (I even copy/pasted code from Unit test) in the MVC controller and I get an error in mapping Dto to Domain entity:
Unmapped members were found. Review the types and members below...
I configured Automapper maps in startup.cs like this:
services.AddAutoMapper();
If I understand correctly this is supposed to traverse all assemblies for classes inheriting Profile and adding them to configuration.
Example map:
public class StrankaMap : Profile
{
public override string ProfileName => nameof(StrankaMap);
public StrankaMap()
{
CreateMap<SomeDto, SomeDomainEntity>().ReverseMap()
CreateMap<AnotherDto, AnotherDomainEntity>().ReverseMap()
}
}
I don't know what is the cause of this error if my unit test works but not from MVC app - I even copied the code from unit test to MVC controller and ran that. I'm suspecting an error in configuration. Do I assume correctly that inside Startup.cs adding services.AddAutoMapper(); is enough for this to work?
Solution (edit)
Apparently I misunderstood that the service.AddAutoMapper() will traverse all assemblies and search for Profile inherited classes. There might be a better solution but I used the one below, with the help of a hint from the comment #LucianBargaoanu.
I solved it like this:
// Startup.cs
services.AddAutoMapper(
typeof(Business.App.AutoMapperConfiguration),
typeof(MvcApp.Infrastructure.Configuration.AutoMapperConfiguration));
//And the AutoMapperConfiguration class:
namespace MvcApp.Infrastructure.Configuration
{
using AutoMapper;
public class AutoMapperConfiguration
{
public static void Configure()
{
Mapper.Initialize(x =>
{
x.AddProfile<Models.Mapping.StrankaMap>();
});
}
}
}
Apparently I misunderstood that the service.AddAutoMapper() will traverse all assemblies and search for Profile inherited classes. There might be a better solution but I used the one below, with the help of a hint from the comment #LucianBargaoanu.
I solved it like this:
// Startup.cs
services.AddAutoMapper(
typeof(Business.App.AutoMapperConfiguration),
typeof(MvcApp.Infrastructure.Configuration.AutoMapperConfiguration));
//And the AutoMapperConfiguration class:
namespace MvcApp.Infrastructure.Configuration
{
using AutoMapper;
public class AutoMapperConfiguration
{
public static void Configure()
{
Mapper.Initialize(x =>
{
x.AddProfile<Models.Mapping.StrankaMap>();
});
}
}
}

Implementing IntelliSense support for custom language (C++)

I wan to implement IntelliSense support for custom language. Actually it is a customize version of C++. i.e the methods resides in separate files
So my main class is like followings and it has import file MyClassMethods which has all the methods.
public class MyClass {
#import MyClassMethods
// my code goes here
}
So my MyClassMethods fiel looks like following and it has two methods,
public void testMethod1() {
}
public void testMethod2() {
}
Then at the end I want to have IntelliSense features when I working on MyClass. Example when I put dot character on that class in a required place I want to have testMethod1() and testMethod2() in the IntelliSense menu.
Is this possible to achieve and if so how can I achieve this?

Mvvmcross Testing different view models fails when running together

I've come across an interesting error. I have two test files for my xamarin mobile application, both testing view models:
public class TestFirstViewModel : MvxIoCSupportingTest
{
public void AdditionalSetup() {
//Register services and dependencies here.
}
[Fact]
public TestMethod1() {
// Successful test code here.
}
}
That's in one file. In another file, I have:
public class TestSecondViewModel : MvxIoCSupportingTest
{
public void AdditionalSetup() {
//Register services and dependencies here, slightly different from first
}
[Fact]
public TestMethod2() {
// Successful test code here.
}
}
When I run these files individually (I'm using xunit), they work just fine. However, when I run them together, I get the following error on one of the test cases:
Result Message: Cirrious.CrossCore.Exceptions.MvxException : You cannot create more than one instance of MvxSingleton
Result StackTrace:
at Cirrious.CrossCore.Core.MvxSingleton`1..ctor()
at Cirrious.CrossCore.IoC.MvxSimpleIoCContainer..ctor(IMvxIocOptions options)
at Cirrious.CrossCore.IoC.MvxSimpleIoCContainer.Initialize(IMvxIocOptions options)
at Cirrious.MvvmCross.Test.Core.MvxIoCSupportingTest.ClearAll()
at Cirrious.MvvmCross.Test.Core.MvxIoCSupportingTest.Setup()
at Project.Test.TestFirstViewModel.TestMethod1() in ...
Can anyone tell me what's going on here?
The issue stems from the parallelization of XUnit without the option to do proper tear-down. You could diable parallelization in the AssemblyIndo.cs file in you test project by adding:
[assembly: CollectionBehavior(DisableTestParallelization = true)]
I ended up solving this question by changing testing frameworks. I had different ioc singleton initializations, because, well, they're different test cases and needed different inputs/mocks. Instead of using Xunit, I resorted to Nunit where their cache clearing was much more defined: Xunit doesn't exactly believe in setup and tear-down, so it made a test environment like this more difficult.
I fixed the issue by using the collection attribute.
[Collection("ViewModels")]
class ViewModelATest : BaseViewModelTest {
...
}
[Collection("ViewModels")]
class ViewModelBTest : BaseViewModelTest {
...
}
The base view model test class has the mock dispatcher and performs the singleton registrations in the additional setup method.
Each of my tests calls ClearAll() at the beginning.
I hade some success with setup things in a constructor and add this check:
public PaymentRepositoryTests()
{
if (MvxSingletonCache.Instance == null)
{
Setup();
}
//other registerings.
}`
Also I did implement the IDisposable Interface
public void Dispose()
{
ClearAll();
}
But tbh not sure how much impact that had..
It works ok with xunit
Copy MvxIocSupportingTest and Mvxtest in your xunit PCL project.
Modify MvxTest to remove the attributes and use a simple contructor:
public class MvxTest : MvxIoCSupportingTest
{
protected MockMvxViewDispatcher MockDispatcher { get; private set; }
public MvxTest()
{
Setup();
}
...
And in each of you test, derive from IClassFixture
public class TestRadiosApi : IClassFixture<MvxTest>
{
[Fact]
public async Task TestToken()
{
...
xunit will create the MvxTest class only once for all tests.

ninject 3 render out object context instances

Entity Framework 4, Ninject 3, MVC3
Currently in my web app i have been using a rather rudimentary approach to per request instantiation of an Object Context. So I am experimenting with Ninject, and some old sample code, but I am unsure how to proceed with the following..
Effectively I want to be able in the controller to do the equivalent of: DB_Entities.Current.Albums ... Should i be instantiating a StandardKernel every time?
The sample i was looking at was using the following: MvcApplication.Container.Get(); but in Ninject 3 with the App_Start hookup I dont have access to Container..
My attempt to replicate the above line, is failing at runtime.
using MusicStoreEntities;
using Ninject;
using TestMVC3WithIOC.App_Start;
using System.Data.Objects;
namespace TestMVC3WithIOC.Models
{
public partial class MusicStoreEntities
{
public static MusicStoreEntities Current
{
get
{
using (IKernel kernel = new StandardKernel())
{
return (MusicStoreEntities)kernel.Get<ObjectContext>();
}
}
}
}
}
Also, note, that in App_Start\NinjectWebCommon.cs I have the following modification:
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<ILogger>().To<NLogger>();
kernel.Bind<ObjectContext>().To<MusicStoreEntities>().InRequestScope();
}
Although a workable solution, it seems ill-advised to pass the entire Kernel into a class, because it tends to obscure the classes actual, specific dependencies. A better approach is to pass a factory dependency into your controller's constructor.
public partial class MusicStoreEntities
{
private readonly IEntitiesFactory _factory;
public MusicStoreEntities(IEntitiesFactory factory)
{
_factory = factory;
}
}
IEntitiesFactory has a simple implementation with a single method GetObjectContext().
(I believe also the "Unit of Work" pattern is popular at the moment, but I can't really speak to that as I haven't used it. Maybe worth looking into.)

Resources