I am trying to run a test to check that my mapping is correct however every time I run the debugger I get an AutoMapperMappingException.
My code:
public BB.LMS.Models.CaseExport ConvertStarsCaseExportToCaseExport(BB.LMS.Services.Core.Models.Stars.caseexport caseExport)
{
Mapper.CreateMap<BB.LMS.Services.Core.Models.Stars.caseexport, CaseExport>();
var ConvertedCase = Mapper.Map<BB.LMS.Services.Core.Models.Stars.caseexport, BB.LMS.Models.CaseExport>(caseExport);
return ConvertedCase;
}
and
[TestMethod()]
public void ConvertToCaseTest()
{
DTOService service = new DTOService();
caseexport export = xmlService.DeserializeStarsExport(testStarsFile);
CaseExport convertedCase = service.ConvertStarsCaseExportToCaseExport(export);
Exception:
{
"Missing type map configuration or unsupported mapping.\r\n\r\nMapping types:\r\ncase -> Case\r\nBB.LMS.Services.Core.Models.Stars.case -> BB.LMS.Models.Case\r\n\r\nDestination path:\r\nCaseExport.solicitor.solicitor.case.case\r\n\r\nSource value:\r\nBB.LMS.Services.Core.Models.Stars.case"
}
FIXED: As Sergey L correctly pointed out, I hadn't mapped case -> Case once that had been mapped my code worked a treat!
The error says automapper needs configuration in order to be able to map.
Here is one way to do it :
public BB.LMS.Models.CaseExport ConvertStarsCaseExportToCaseExport(BB.LMS.Services.Core.Models.Stars.caseexport caseExport)
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<BB.LMS.Services.Core.Models.Stars.caseexport, CaseExport>();
});
var mapper = config.CreateMapper();
var ConvertedCase = mapper.Map<BB.LMS.Services.Core.Models.Stars.caseexport, BB.LMS.Models.CaseExport>(caseExport);
return ConvertedCase;
}
Related
I've had to jump in to a complex project and am making unit tests for a particular repository in a WEB API service. The database CRUD is handled by the Entity Framework.
private class IntegrationScope : AutoRollbackTransactionTestScope<DocumentRepository>
{
public IntegrationScope()
{
DependencyResolverMock = MockDependencyResolverFor<IResourceUrlBuilder, ResourceUrlBuilder>(new ResourceUrlBuilder());
LoggingProviderMock = new Mock<ILoggingProvider>();
// use real document micro service AutoMapper & Unity configuration
AutoMapperConfig.RegisterMaps(Mapper.Configuration, DependencyResolverMock);
UnityConfig.RegisterTypes(TestScopeContainer);
//Set the DomainId
TestId = Guid.NewGuid();
TestDocument = BuildDocument(TestId);
// get the real object
DocumentStoreDbContext = TestScopeContainer.Resolve<IDocumentDbContext>();
InstanceUnderTest = new DocumentRepository(DocumentStoreDbContext);
}
public static Web.Service.DocumentStore.Domain.Document BuildDocument(Guid documentId)
{
// Invoke GetBytes method.
byte[] array = Encoding.ASCII.GetBytes("Byte Repository Test");
return Builder<Web.Service.DocumentStore.Domain.Document>
.CreateNew()
.With(t => t.Id = documentId)
.With(t => t.Data = array)
.Build();
}
When it gets to the DocumentStoreDbContext line, there is no compilation error but i get a run-time error saying that the object name is invalid:
After doing some research this error appears to be because the database/table doesn't exist, however I can see that it does exist:
What am I doing wrong and how do I fix it?
InnerException displays the table name as DocumentStore.Documents, but your SSMS screenshot shows dbo.Documents.
Could this be the cause?
The following code throws an exception on the session.Load<Employee>(order.Employee), but I have no problem querying an employee directly.
static void LoadRelatedData()
{
using (var session = mystore.OpenSession())
{
var employeeFromQuery = session.Query<Employee>().FirstOrDefault(); //works
var order = session.Include<Order>(o => o.Employee).Load("orders/819"); //works
var employeeRelatedToOrder = session.Load<Employee>(order.Employee); //EXCEPTION
var dynamicRelatedToOrder = session.Load<dynamic>(order.Employee); //works
}
}
private static IDocumentStore mystore = new DocumentStore()
{
Url = "http://localhost:4444/RavenDB",
DefaultDatabase = "Hello"
}.Initialize();
The exception I get is -
An unhandled exception of type 'System.InvalidCastException' occurred in Raven.Client.Lightweight.dll
Additional information: Unable to cast object of type 'Raven.Abstractions.Linq.DynamicJsonObject' to type 'RavenApp.Employee'
.
I'm basing my code on http://ravendb.net/docs/article-page/2.5/Csharp/client-api/querying/handling-document-relationships
The employee and order data are generated by the Raven Create Sample Data task.
As you've used Include, the order.Employee should be populated for you and not require a second load.
static void LoadRelatedData()
{
using (var session = mystore.OpenSession())
{
var employeeFromQuery = session.Query<Employee>().FirstOrDefault();
var order = session.Include<Order>(o => o.Employee).Load("orders/819");
// Access them directly, as they have been resolved
var employeeRelatedToOrder = order.Employee;
var dynamicRelatedToOrder = (dynamic)order.Employee;
}
}
I'm using fluent migrator to manage my database migrations, but what I'd like to do is have the migrations run at app start. The closest I have managed is this:
public static void MigrateToLatest(string connectionString)
{
using (var announcer = new TextWriterAnnouncer(Console.Out)
{
ShowElapsedTime = true,
ShowSql = true
})
{
var assembly = typeof(Runner).Assembly.GetName().Name;
var migrationContext = new RunnerContext(announcer)
{
Connection = connectionString,
Database = "SqlServer2008",
Target = assembly
};
var executor = new TaskExecutor(migrationContext);
executor.Execute();
}
}
I'm sure I had this working, but I've not looked at it for sometime (hobby project) and it's now throwing null reference exceptions when it gets to the Execute line. Sadly there are no docs for this and I've been banging my head on it for ages.
Has anyone managed to get this kind of thing working with FluentMigrator?
PM> Install-Package FluentMigrator.Tools
Manually add a reference to:
packages\FluentMigrator.Tools.1.6.1\tools\AnyCPU\40\FluentMigrator.Runner.dll
Note that the folder name will vary on version number, this illustration uses the current 1.6.1 release. If you need the .NET 3.5 runner use the \35\ directory.
public static class Runner
{
public class MigrationOptions : IMigrationProcessorOptions
{
public bool PreviewOnly { get; set; }
public string ProviderSwitches { get; set; }
public int Timeout { get; set; }
}
public static void MigrateToLatest(string connectionString)
{
// var announcer = new NullAnnouncer();
var announcer = new TextWriterAnnouncer(s => System.Diagnostics.Debug.WriteLine(s));
var assembly = Assembly.GetExecutingAssembly();
var migrationContext = new RunnerContext(announcer)
{
Namespace = "MyApp.Sql.Migrations"
};
var options = new MigrationOptions { PreviewOnly=false, Timeout=60 };
var factory =
new FluentMigrator.Runner.Processors.SqlServer.SqlServer2008ProcessorFactory();
using (var processor = factory.Create(connectionString, announcer, options))
{
var runner = new MigrationRunner(assembly, migrationContext, processor);
runner.MigrateUp(true);
}
}
}
Note the SqlServer2008ProcessorFactory this is configurable dependent upon your database, there is support for: 2000, 2005, 2008, 2012, and 2014.
I have actually accomplished running migrations in the application_start however it is hard to tell from that code what could be wrong... Since it is open source I would just grab the code and pull it into your solution and build it to find out what the Execute method is complaining about. I found that the source code for Fluent Migrator is organized pretty well.
One thing that you might have to be concerned about if this is a web app is making sure that no one uses the database while you are migrating. I used a strategy of establishing a connection, setting the database to single user mode, running the migrations, setting the database to multi user mode, then closing the connection. This also handles the scenario of a load balanced web application on multiple servers so 2 servers don't try to run migrations against the same database.
I want to be able to mock the object that is returned by SPServer.Local but I can't seem to do it in typemock. At the moment when I debug, I see that SPServer.Local returns a null object of type SPServer. Shouldn't typemock be swapping out this instance with my fake instance? Is there something I'm doing wrong? The code runs fine on the sharepoint server.
[TestInitialize]
public void Setup()
{
fakeSite = Isolate.Fake.Instance<SPSite>(Members.ReturnRecursiveFakes);
Isolate.Swap.NextInstance<SPSite>().With(fakeSite);
fakeServer = Isolate.Fake.Instance<SPServer>(Members.ReturnRecursiveFakes);
Isolate.Swap.NextInstance<SPServer>().With(fakeServer);
sharePointStorageRepository = new SharePointStorageRepository();
}
[TestMethod]
[Isolated]
public void CreateHRFolderMethodCreatesHRFolder()
{
// arrange
// some arrange logic here
// act
var actual = sharePointStorageRepository.Create();
// assert
Assert.AreEqual(expected, actual);
}
This is the bit of code that is being run:
internal static Guid GetSiteGuid(string serverRelativeUrl, string webApplicationName)
{
Guid? guid = null;
SPServer myServer = SPServer.Local;
foreach (var serviceInstance in myServer.ServiceInstances.Where(si => si.Service is SPWebService)){
var service = (SPWebService) serviceInstance.Service;
var webapp = service.WebApplications.SingleOrDefault(wa => wa.DisplayName == webApplicationName);
if (webapp != null){
var site = webapp.Sites.SingleOrDefault(wa => wa.ServerRelativeUrl == serverRelativeUrl);
if (site != null) guid = site.ID;
}
}
if (!guid.HasValue){
throw new FileNotFoundException(
String.Format(
"Cannot find Site Collection with WebApplication \"{1}\" and ServerRelativeUrl \"{2}\" running on \"{0}\"",
myServer.Address, webApplicationName, serverRelativeUrl));
}
return guid.Value;
}
Thanks all!
I don't work in SharePoint, but something I noticed: You're not actually mocking the return of SPServer.Local anywhere. I think that's the missing step. I'm also not entirely sure you need to SwapNextInstance since I don't see anywhere that is actually creating an SPServer object.
That would change your test code to:
[TestInitialize]
public void Setup()
{
// I don't see where you're using SPSite, so I assume it's in code
// not being shown; otherwise you can remove this.
fakeSite = Isolate.Fake.Instance<SPSite>(Members.ReturnRecursiveFakes);
Isolate.Swap.NextInstance<SPSite>().With(fakeSite);
fakeServer = Isolate.Fake.Instance<SPServer>(Members.ReturnRecursiveFakes);
// INSTEAD OF THIS: Isolate.Swap.NextInstance<SPServer>().With(fakeServer);
// DO THIS:
Isolate.WhenCalled(() => SPServer.Local).WillReturn(fakeServer);
sharePointStorageRepository = new SharePointStorageRepository();
}
That WhenCalled method will mean that any time anyone asks for SPServer.Local, it'll return your fake instance.
Note that I see in the code being tested that you get the ServerInstances property. I don't see any specific return values getting set up, so I assume you're controlling the rest of the stuff in the omitted "arrange" logic.
I've search control with which I'm trying to implement search as user types something. I'm using Linq to SQL to fire queries against the database. Though it works fine usually, when user types the queries really fast some random SqlException is thrown. These are the two different error message I stumbled across recently:
A severe error occurred on the current command. The results, if any, should be discarded.
Invalid attempt to call Read when reader is closed.
Edit: Included code
DataContextFactory class:
public DataContextFactory(IConnectionStringFactory connectionStringFactory)
{
this.dataContext = new RegionDataContext(connectionStringFactory.ConnectionString);
}
public DataContext Context
{
get { return this.dataContext; }
}
public void SaveAll()
{
this.dataContext.SubmitChanges();
}
Registering IDataContextFactory with Unity
// Get connection string from Application.Current settings
ConnectionInfo connectionInfo = Application.Current.Properties["ConnectionInfo"] as ConnectionInfo;
// Register ConnectionStringFactory with Unity container as a Singleton
this.container.RegisterType<IConnectionStringFactory, ConnectionStringFactory>(new ContainerControlledLifetimeManager(),
new InjectionConstructor(connectionInfo.ConnectionString));
// Register DataContextFactory with Unity container
this.container.RegisterType<IDataContextFactory, DataContextFactory>();
Connection string:
Data Source=.\SQLEXPRESS2008;User Instance=true;Integrated Security=true;AttachDbFilename=C:\client.mdf;MultipleActiveResultSets=true;
Using datacontext from a repository class:
// IDataContextFactory dependency is injected by Unity
public CompanyRepository(IDataContextFactory dataContextFactory)
{
this.dataContextFactory = dataContextFactory;
}
// return List<T> of companies
var results = this.dataContextFactory.Context.GetTable<CompanyEntity>()
.Join(this.dataContextFactory.Context.GetTable<RegionEntity>(),
c => c.regioncode,
r => r.regioncode,
(c, r) => new { c = c, r = r })
.Where(t => t.c.summary_region != null)
.Select(t => new { Id = t.c.compcode, Company = t.c.compname, Region = t.r.regionname }).ToList();
What is the work around?
It's not something that requires MARS in your connection string?
http://msdn.microsoft.com/en-us/library/h32h3abf(VS.80).aspx