Must implement Sub Dispose() for interface 'System.IDisposable' - dispose

I am trying to follow the following tutorial and convert this from C# to Vb.net
http://www.asp.net/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application
I converted the Generic repository as follows:
Imports System.Collections.Generic
Imports System.Linq
Imports System.Data
Imports System.Data.Entity
Imports MarketMessages.Data
Imports System.Linq.Expressions
Public Class GenericRepository(Of TEntity As Class)
Friend context As ComplaintsDemoContext
Friend dbSet As DbSet(Of TEntity)
Public Sub New(context As ComplaintsDemoContext)
Me.context = context
Me.dbSet = context.[Set](Of TEntity)()
End Sub
Public Overridable Function [Get](Optional filter As Expression(Of Func(Of TEntity, Boolean)) = Nothing, Optional orderBy As Func(Of IQueryable(Of TEntity), IOrderedQueryable(Of TEntity)) = Nothing, Optional includeProperties As String = "") As IEnumerable(Of TEntity)
Dim query As IQueryable(Of TEntity) = dbSet
If filter IsNot Nothing Then
query = query.Where(filter)
End If
For Each includeProperty As String In includeProperties.Split(New Char() {","c}, StringSplitOptions.RemoveEmptyEntries)
query = query.Include(includeProperty)
Next
If orderBy IsNot Nothing Then
Return orderBy(query).ToList()
Else
Return query.ToList()
End If
End Function
Public Overridable Function GetByID(id As Object) As TEntity
Return dbSet.Find(id)
End Function
Public Overridable Sub Insert(entity As TEntity)
dbSet.Add(entity)
End Sub
Public Overridable Sub Delete(id As Object)
Dim entityToDelete As TEntity = dbSet.Find(id)
Delete(entityToDelete)
End Sub
Public Overridable Sub Delete(entityToDelete As TEntity)
If context.Entry(entityToDelete).State = EntityState.Detached Then
dbSet.Attach(entityToDelete)
End If
dbSet.Remove(entityToDelete)
End Sub
Public Overridable Sub Update(entityToUpdate As TEntity)
dbSet.Attach(entityToUpdate)
context.Entry(entityToUpdate).State = EntityState.Modified
End Sub
End Class
But I am getting the error Must implement Sub Dispose() for interface 'System.IDisposable' when trying to convert the UnitOfWork class here is my code:
Public Class UnitOfWork
Implements IDisposable
Private context As New ComplaintsDemoContext()
Private m_marketMessageRepository As GenericRepository(Of MarketMessage)
Private m_marketMessageTypeRepository As GenericRepository(Of MarketMessageType)
Public ReadOnly Property MarketMessageRepository() As GenericRepository(Of MarketMessage)
Get
If Me.m_marketMessageRepository Is Nothing Then
Me.m_marketMessageRepository = New GenericRepository(Of MarketMessage)(context)
End If
Return m_marketMessageRepository
End Get
End Property
Public ReadOnly Property CourseRepository() As GenericRepository(Of MarketMessageType)
Get
If Me.m_marketMessageTypeRepository Is Nothing Then
Me.m_marketMessageTypeRepository = New GenericRepository(Of MarketMessageType)(context)
End If
Return m_marketMessageTypeRepository
End Get
End Property
Public Sub Save()
context.SaveChanges()
End Sub
Private disposed As Boolean = False
Protected Overridable Sub Dispose(disposing As Boolean)
If Not Me.disposed Then
If disposing Then
context.Dispose()
End If
End If
Me.disposed = True
End Sub
Public Sub Dispose()
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
End Class

This happens when you have copied the code over to your project.
Place the cursor in front of
Implements IDisposable
Then press Enter.
The IDE will generate all interface members for the class. Learnt from
here

Found the answer changed to:
Protected Overridable Overloads Sub Dispose(ByVal disposing As Boolean)
If Not disposed Then
If disposing Then
context.Dispose()
End If
End If
disposed = True
End Sub
Public Overloads Sub Dispose() Implements System.IDisposable.Dispose
Dispose(True)
GC.SuppressFinalize(Me)
End Sub

Related

Mapstruct: aftermapping with parameters

Here my code:
#Mapping(target = "auditoriaMetas", qualifiedByName = "sdf")
public abstract Auditoria mapToModificacio(QdCF qdcf, QdCFPresenter qdcfPresenter, Integer idInstrument);
#Named("sdf")
public List<AuditoriaMeta> mapToMetas(QdCF current, #Context QdCFPresenter incoming) {
return null;
}
I want that after mapToModificatio is performed, mapToMetas is also executed.
Above code doesn't perform.
Any ideas?
Mapstruct will not consider putting a normal value into one that is annotated with #Context. Therefor if you mark something with #Context, then it should be marked like that through the entire chain of calls.
For example:
#Mapping(target = "auditoriaMetas", source=".", qualifiedByName = "sdf")
public abstract Auditoria mapToModificacio(QdCF qdcf, #Context QdCFPresenter qdcfPresenter, Integer idInstrument);
#Named("sdf")
public List<AuditoriaMeta> mapToMetas(QdCF current, #Context QdCFPresenter incoming) {
return null;
}

Mockito fails for Spring data JPA Page interface

#SpringBootTest
public class TestClass {
#Mock
private Page<Customer> pagedResult;
#Mock
private Pageable paging = PageRequest.of(0, 1);
#Mock
private CustomerRepository cutomerRepository;
#InjectMocks
private CustomerServiceImpl service;
#Test
void testss() {
Set<Integer> set = new HashSet<>();
set.add(1);
Pageable paging1 = PageRequest.of(0, 1);
Page<Customer> pa = new PageImpl<>(Arrays.asList(customer));
when(cutomerRepository.findByIdIn(set, paging1)).thenReturn(pa);
when(service.test(set)).thenReturn(Arrays.asList(customer));
assertEquals(customer.getName(), service.test(set).get(0).getgetName());
}
}
Implementation class
public class CustomerServiceImpl {
private CustomerRepository customerRepository ;
public CustomerServiceImpl(CustomerRepository customerRepository ) {
super();
this.customerRepository = customerRepository ;
}
#Override
public List<Customer> test(Set<Integer> ids) {
Pageable paging = PageRequest.of(0, 1);
Page<Customer> pagedResult = customerRepository.findByIdIn(ids, paging);
return pagedResult.toList();
}
}
I am trying to write the Junit test case for my pagination code using mockito but it fails as it is expecting the return type for method as Page.but I am returning List of Customers.When I return Page from method it works fine but if I return List is fails with below mentioned error
I am getting below error
org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
ArrayList cannot be returned by findByIdIn()
findByIdIn() should return Page
If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
This exception might occur in wrongly written multi-threaded tests.
Please refer to Mockito FAQ on limitations of concurrency testing.
A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies -
with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.
I think something is messed with your code.
In Your code you have doctorRepository.findByIdIn Method bt in your test class it is cutomerRepository.findByIdIn.
I have added the below code as a reference with respect to your CustomerServiceImpl.
You can try the same way to execute your test.
SpringBootTest
public class TestClass {
#Mock
private Pageable paging;
#Mock
private CustomerRepository cutomerRepository;
#Mock
private DoctorRepository doctorRepository;
#InjectMocks
private CustomerServiceImpl service;
#Test
void testss() {
Doctor doctor = new Doctor();
doctor.setName("test name");
Set<Integer> set = new HashSet<>();
set.add(1);
PageImpl<Doctor> page = new PageImpl<>(Arrays.asList(doctor));
when(doctorRepository.findByIdIn(Mockito.any(), Mockito.any())).thenReturn(page);
List<Doctor> doctors= service.test(set);
assertEquals(doctor.getName(), doctors.get(0).getgetName());
}
}

C# issue with class instantiation

I'm running a C# project on VS2019 with the following code structure:
In the Class1.cs file:
public class Class1
{
public class MyClass2 : Class2
{
...
}
private void RunAlgorithm<T>() where T : Class2, new()
{
T argInstance = new T();
...
}
static void Main(string[] args)
{
RunAlgorithm<MyClass2>();
}
}
In the Class2.cs file:
public class Class2
{
public Class2() { }
public string setParameters { get; set; }
}
I'm getting the following error for the line RunAlgorithm<MyClass2>();
'Class1.MyClass2' must be a non-abstract type with a public
parameterless constructor in order to use it as parameter 'T' in the
generic type or method 'Class1.RunAlgorithm()'
even if I change it to Public, the error persists
Well, minimally, it'll have to be protected so that MyClass can access it..
https://dotnetfiddle.net/XFeEdQ
public class Class1
{
class MyClass2 : Class2
{
}
private void RunAlgorithm<T>() where T : Class2, new()
{
T argInstance = new T();
}
public static void Main(string[] args)
{
new Class1().RunAlgorithm<MyClass2>();
}
}
public class Class2
{
protected Class2() { }
public string setParameters { get; set; }
}
So your "Class1.MyClass2
must have a public parameterless constructor" message is saying that your MyClass needs a constructor. Mine above has such a constructor even though it's not in the code; in the absence of the developer providing a constructor the compiler provides one that does nothing other than call the base parameterless constructor...
...which leads me to the next point; your MyClass2 extends Class2, and hence Class2's constructor needs to be accessible to it. While Class2's constructor is private, MyClass2's constructor can't call it. Every constructor on c# has to either call another constructor or a base constructor. If you don't specify which, the compiler will insert a call to base() for you, which will fail if the base constructor is inaccessible
For this all to work out you need a public parameterless constructor in MyClass2:
public MyClass2():base(){}
or without the base(compiler will add the base call)
or blank (compiler will add all of it)
and you need something that makes Class2's constructor accessible to MyClass2, ie declaring Class2's constructor as public or protected

Autofac - InstancePerLifetimeScope vs InstancePerRequest in Application_Start in ASP.NET Web Forms

I am using Autofac With ASP.NET Webforms. I would like to understand the difference between InstancePerLifetimeScope and InstancePerRequest when i register dependencies in the App_Start method of the global.asx.
It look like that for both of them a new instance of the dependency is created just once at Every HttpRequest (verified with a breakpoint into the constructor of the dependency and with the HashCode of the object).
Any ideas?
Thank you
#Travis gave good link to the documentation describing how it works. However, I prefer to give examples additionally to illustrate the theory better. So, let's take a look at simple example.
Suppose you have two classes ClassA and ClassB implementing some simple interfaces IClassA and IClassB.
public class ClassA : IClassA
{
public ClassA() {
}
}
public class ClassB : IClassB
{
public ClassB() {
}
}
Now, let's see what happens when we register them in different ways.
Example A
builder = new ContainerBuilder();
builder.RegisterType<ClassA>().As<IClassA>().InstancePerLifetimeScope();
builder.RegisterType<ClassB>().As<IClassB>().InstancePerLifetimeScope();
Then, in the controller, you do this:
public class HomeController : Controller
{
private readonly IClassA _classA;
private readonly IClassB _classB;
private readonly IComponentContext _ctx;
public HomeController(IClassA classA, IClassB classB, IComponentContext ctx) {
_classA = classA;
_classB = classB;
_ctx = ctx;
}
public string Get() {
using (var scope = _ctx.BeginLifetimeScope()) {
var newClassA = scope.Resolve<IClassA>(); // Object.ReferenceEquals(newClassA, _classA) == false
var newClassB = scope.Resolve<IClassB>(); // Object.ReferenceEquals(newClassB, _classB) == false
return "Ok";
}
}
}
In this example both 'new' variables in Get() method will receive new instances since they are both registered to be unique per lifetime scope. We began new lifetime scope - we got new instances.
Now, let's take a look at another example.
Example B
builder = new ContainerBuilder();
builder.RegisterType<ClassA>().As<IClassA>().InstancePerLifetimeScope();
builder.RegisterType<ClassB>().As<IClassB>().InstancePerRequest(); // now they have different life time!
// controller:
public class HomeController : Controller
{
private readonly IClassA _classA;
private readonly IClassB _classB;
private readonly IComponentContext _ctx;
public HomeController(IClassA classA, IClassB classB, IComponentContext ctx) {
_classA = classA;
_classB = classB;
_ctx = ctx;
}
public string Get() {
using (var scope = _ctx.BeginLifetimeScope()) {
var newClassA = scope.Resolve<IClassA>(); // Object.ReferenceEquals(newClassA, _classA) == false
var newClassB = scope.Resolve<IClassB>(); // Object.ReferenceEquals(newClassB, _classB) == true
return "Ok";
}
}
}
See what happened here? Even though we began new lifetime scope - ClassB still gets resolved from request scope and not from our new one. This is the difference between InstancePerLifetimeScope() and InstancePerRequest().
And as documentation suggests, internally it is based on another Autofac concept - InstancePerMatchingLifetimeScope().
In many cases it amounts to the same thing. This is an FAQ on the Autofac doc site.

Way to find all affected locations by variable

I want to find code lines, where a certain property can get.
Consider I have property holder class and in java editor look to some setter method. In code is property readed and setted to entity. And before save to database, do validation on server side. So I want see from client.propertyHolder.setter to server.entityValidator.getter
Simple example
public class Main{
public static void main(String[] args) {
Holder h = new Holder();
h.setHolder("Something"); // Here i want use plugin
Entity e = new Entity();
e.setName(h.getHolder());
// Consider this is on server side in validator and call only if annotation validation is OK
Assert.assertTrue(e.getName().length() > 0)
}
}
public class Holder{
public String holder = null;
public void setHolder(String holder){this.holder = holder}
public void getHolder(){return holder}
}
public class Entity{
#javax.validation.constraints.NotNull
private String name = null;
public void setName(String name){this.name = name}
public void getName(){return name}
}
So i should get lines
e.setName(h.getHolder());
Assert.assertTrue(e.getName().length() > 0)
and be nice if NotNull anotations too
Is there a way, how to achive this? Some good free eclipse-plugin maybye?
Thanks for help. Pavel