Entity framework asp.net MVC3 .NET 4 - asp.net-mvc-3

I Have a little snag. With my asp.net mvc3 application.
When I trying to compile my app I obtain this Error
Error 2 'Blog.Domain.Concrete.EFEntryRepository' does not implement interface member 'Blog.Domain.Abstract.IEntryRepository.SaveEntry(Blog.Domain.Entities.Entry)' D:\dokumenty\Visual Studio 2010\Projects\MVC3\Blog\Blog.Domain\Concrete\EFEntryRepository.cs 10 19 Blog.Domain
This is my Interface.
namespace Blog.Domain.Abstract
{
public interface IEntryRepository
{
IQueryable<Entry> Entries { get; }
void SaveEntry(Entry entry);
void DeleteEntry(Entry entry);
}
}
And this is my implementation of it.
public class EFEntryRepository : IEntryRepository
{
private EFDbContext context = new EFDbContext();
public IQueryable<Entry> Entries
{
get { return context.Entries; }
}
public void SaveEntry(Entry entry)
{
if (entry.EntryID == 0)
context.Entries.Add(entry);
context.SaveChanges();
}
public void DeleteEntry(Entry entry)
{
context.Entries.Remove(entry);
context.SaveChanges();
}
}
This is link to my project. http://sigma.ug.edu.pl/~kkubacki/Blog.zip //NEW
Now I is compiling.
What I Do Wrong ?
I have new Information about the bug. Now the solution is compiling but the application crashes with the bug information
"{"The type 'Blog.Domain.Concrete.Entry' was not mapped. Check that the type has not been explicitly excluded by using the Ignore method or NotMappedAttribute data annotation. Verify that the type was defined as a class, is not primitive, nested or generic, and does not inherit from EntityObject."} " Visual studio shows bug in the EFEntryRepository class.
I don't know what to do please help.
OK Problem IS Solved.

You have two different Entry classes in different namespaces.
Blog.Domain.Entities.Entry
Blog.Domain.Concrete.Entry
The interface is referring to one and the implementation is referring to the other.

Related

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.

Unity not registering

I'm using unity in my MVC app
I have the following RegisterTypes method within my Bootstapper.cs file:
public static void RegisterTypes(IUnityContainer container)
{
container.RegisterType<AccountController>(new InjectionConstructor());
container.RegisterType<IModelContext, ModelContext>();
container.RegisterType<IModelRepository, ModelRepository>();
}
I have the following controller:
public class APIScoresController : ApiController
{
private IModelRepository _repo;
public APIScoresController(IModelRepository repo)
{
_repo = repo;
}
public IEnumerable<Result> Get()
{
return _repo.GetResults();
}
}
I have the following Model Repo:
public class ModelRepository : IModelRepository
{
ModelContext _ctx;
public ModelRepository(ModelContext ctx)
{
_ctx = ctx;
}
public IQueryable<DomainClasses.Result> GetResults()
{
return _ctx.Results;
}
}
When I try to execute the GET on the APIScoresController I get the following exception:
An error occurred when trying to create a controller of type 'APIScoresController'. Make sure that the controller has a parameterless public constructor
I would have expected unity to create the required ModelContext and ModelRepository objects. Any ideas why it's not doing this?
Problem caused by web api registration needing a different version of system.web.http. I was trying to add web api to an existing mvc5 app - bad idea! I entered a form of dll hell that I hadn't experienced since days of VB6 COM. In the end my solution was to create a new solution with a web api project then retro fit the mvc project.

How to link RDLC report viewer to data repository using unit of work pattern

I've created an MVC.net application using EF and the Unit of work pattern. I followed this tutorial to create the unit of work classes:
http://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application
I'm trying to create a report using the report viewer control. I understand MVC pages don't currently support the report viewer control so I've created a standard aspx page with the report viewer control. I'm new to reports and I've been following this tutorial:
http://weblogs.asp.net/rajbk/archive/2010/05/09/creating-an-asp-net-report-using-visual-studio-2010-part-1.aspx
However when I add the object data source to the page and try to select the repository, my repository is not listed. The unit of work class is listed but has no methods available
Figured I'd post my progress in case it helps anybody else.
First I created a stored procedure in the SOL database to get the records for the report with optional parameters for filtering.
Then I updated the edmx diagram to import the stored procedure and create a new complex class for the returned records.
Finally I created new report repository that sits outside the unit of work, like so:
namespace Project.DAL
{
public class ReportRepository : IDisposable
{
internal ProjectEntities context;
public ReportRepository()
{
this.context = new ProjectEntities();
}
public ReportRepository(ProjectEntities context)
{
this.context = context;
}
public List<Report_001_Result> Report001(string Status, DateTime? dateOpenedFrom, DateTime? dateOpenedTo, string caseTypeD, string subCaseType)
{
return this.context.Report_001(caseStatusID, dateOpenedFrom, dateOpenedTo, caseTypeID, subCaseTypeID).ToList();
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
Once the project has been built the Report repository shows up the data selection lists for object datasources and in the report designer.
For each report i just add another method to this repository.
Not sure if this is the prefered approach but works for me.

Entity Framework, Ninject dependency injection, and ASP.NET MVC 3, with existing .MDF file as database

I'm making a long and detailed post here, but I sincerely believe it's better to provide as much info up front. If any further clarification is needed, please ask. My heartfelt thanks to you for reading my query.
I'm using the book Pro ASP.NET MVC3 Framework by Adam Freeman and Steven Sanderson (Apress, Third Edition), and working through the Sports Store example beginning with Chapter VII. Note that the project entails the use of DI through the use of Ninject, and this is the main reason I wanted to take the time for this walkthrough. Another impressive contribution in this tutorial is the fact that it shows you how to develop an MVC 3 solution into separate projects the way it might be done in in a real world implementation--a thing I've found to be lacking in just about every other book I've ever looked at. (BTW I think the Apress books are just about the best ones out there, generally speaking.)
OK, so I've worked through Chapter 7 and well into Chapter 8, which means that I've successfully created and populated a database and retrieved its contents to appear in my List view. I've also gotten the formatting to work through the .css file. However, there's a catch here: When going through this the first time, I created the database from the IDE itself, which was no problem because there's only one small table (Products) to worry about. Everything was working fine. But then, for reasons I will shortly make clear, I decided to start over. This time, I wanted to follow through the same walkthrough with the exception that I would access the data by attaching to an existing .MDF file rather than creating a new DB from scratch as I coded the project. All this is to pave the way for me to use a similar pattern for my real project, for which I already have built a complex DB, replete with tables, FK relationships, views, functions--and data. I hardly need to say that I want to use my existing database in my "real" project, because recreating all that from scratch would be virtually impossible.
OK, now let's return to the Sports Store example. Try as I might, I cannot get the data from the database to my UI view. There are no error messages at compile time or run time, but instead of seeing the data in the List view, I see nothing but a blank page. Note that in this case it's correct in that there are no column headings or panes because there isn't any scaffolding here.
As far as I can see I have all the parts I need. Let's begin with the Ninject controller factory:
NinjectControllerFactory : DefaultControllerFactory
{
private IKernel ninjectKernel;
public NinjectControllerFactory()
{
ninjectKernel = new StandardKernel();
AddBindings();
}
protected override
IController GetControllerInstance
(RequestContext requestContext, Type controllerType)
{
return controllerType == null ? null
: (IController)ninjectKernel.Get(controllerType);
}
private void AddBindings()
{
//Had the mockup here before, which worked fine.
ninjectKernel.Bind<IProductRepository>().To<SportsStore2.Domain.Concrete.EFProductRepository>();
} ...
}
IProductRepository is as follows:
namespace SportsStore2.Domain.Abstract
{
public interface IProductRepository
{
IQueryable<Product> Products { get; }
}
}
And EFProductRepository is implemented thus:
namespace SportsStore2.Domain.Concrete
{
public class EFProductRepository:IProductRepository
{
private EFDbContext context = new EFDbContext();
public IQueryable<Product> Products
{
get { return context.Products; }
}
}
}
Why yes, of course EFDbContext is defined; viz the declaration:
namespace SportsStore2.Domain.Concrete
{
class EFDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
}
}
And the connection string in Web.config file; this is supposed to wire up the context object definition with the actual database in the .MDF file, at least as I understand it.
<connectionStrings>
<add name="EFDbContext"
connectionString="Data Source=Owner-PC\SQLEXPRESS;Initial Catalog = SportsStore20130205; Integrated security=SSPI"
providerName="System.Data.SqlClient" />
</connectionStrings>
Last and almost certainly least, I have the Product controller defined as follows. I say "least" because I'm almost positive the problem isn't here. In Debug mode, I can tell that the productRepository object isn't being populated. I can see some SQL code in there which is supposed to be run, or have been run by this point. But the invocation of repository.Products returns nothing.
namespace SportsStore2.WebUI.Controllers
{
public class ProductController : Controller
{
private IProductRepository repository;
public ProductController(IProductRepository productRepository)
{
repository = productRepository;
}
public ViewResult List()
{
return View(repository.Products);
}
public ViewResult Count()
{
int counter = repository.Products.Count();
return View(repository.Products.Count());
}
}
}
namespace SportsStore2.WebUI.Controllers
{
public class ProductController : Controller
{
private IProductRepository repository;
public ProductController(IProductRepository productRepository)
{
repository = productRepository;
}
public ViewResult List()
{
return View(repository.Products);
}
}
}

Visual Studio 2010/2012/2013, Class Diagram: how to show interface as base class, not as "lillypop"?

Since the interface is already on the diagram I would like to show inheritance reference explicitly. But I can't find how...
There is a bug in VS 2005 up to 2012 that won't allow it to work.
I have a work arround that might trick it into drawing the inheritance for interfaces.
Say your interface is called IMyInterface. You have to replace it with an abstract class implementing that interface and use it instead of your interface. The code would make use of the conditional compilation and will look like this:
//to generate class diagram, add 'CLSDIAGRAM' to the conditional symbols on the Build tab,
// or add '#define CLSDIAGRAM' at the top of this file
#if CLSDIAGRAM
#warning CLSDIAGRAM is defined and this build should be used only in the context of class diagram generation
//rename your interface by adding _
public interface IMyInterface_
{
int MyProperty { get; }
void MyMethod();
}
//this class will act as an interface in the class diagram ;)
public abstract class IMyInterface : IMyInterface_ // tricks other code into using the class instead
{
//fake implementation
public int MyProperty {
get { throw new NotImplementedException(); }
}
public void MyMethod()
{
throw new NotImplementedException();
}
}
#else
// this is the original interface
public interface IMyInterface {
int MyProperty { get; }
void MyMethod();
}
#endif
That's likely to show it as you wish.
In your case IMyInterface will become IMedicine.

Resources