How to tell, in VS2010, that a class needs to be disposed? - visual-studio

Is there an easy way, in Visual Studio 2010, to know if a type needs to be disposed?
e.g. i write code:
Collection<Prize> prizes = new Collection<Prize>();
i don't know if i need to call dispose.
The way i handle it now is click on Collection and press F12, looking for IDisposable:
public class Collection<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable
then i recursively descend into each class, looking to see if any implement IDisposable:
public class Collection<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable
public interface IList<T> : ICollection<T>, IEnumerable<T>, IEnumerable
public interface ICollection<T> : IEnumerable<T>, IEnumerable
public interface IEnumerable<T> : IEnumerable
public interface IEnumerable
public interface IEnumerable
public interface IEnumerable<T> : IEnumerable
public interface IEnumerable
...
Note: Don't confuse the example with the question. i might have the code:
SqlConnection conn = new SqlConnection();
where i then recusively iterate into ancestor types:
public sealed class SqlConnection : DbConnection, ICloneable
public abstract class DbConnection : Component, IDbConnection, IDisposable
So i've found that this class needs me to call Dispose. But it would be easier if i didn't have to F12 descend into stuff

If you have the premium or ultimate edition code analysis rule CA1001:Types that own disposable fields should be disposable will find types that need to be disposed. To enable code analysis go to the project properties and select the code analysis tab, select Enable Code Analysis on Build, the Microsoft.Design ruleset must be included for the CA1001 rule to run.
Coderush from Devexpress includes similar functionality. This is the only option for the standard edition. There may other add-ins that offer similar functionality.
This cannot be done in the express edition.

Related

VB6 parameterized method with a return value over com interop

I can't believe I'm having such a hard time with this, but can someone give me a quick example of a COM interface in C# that is to be called from VB6? I want to pass parameters from VB6 to C#, and return a string to VB6.
Here's what I've got so far (not working):
[ComVisible(true)]
public interface IMonitor
{
string IPAddress(Int64 UserId, Enums.ClientTypes clientType);
}
I also tried:
[ComVisible(true)]
public interface IMonitor
{
void IPAddress(Int64 UserId, Enums.ClientTypes clientType, [Out] string ipAddress);
}
Same error - Function or interface marked as restricted, or the function uses an Automation type not supported in Visual Basic.
FWIW, the ClientTypes enum works great in other VB6 code, so I don't believe the enum to be an issue.

How IEnumerable<T> interface has ToList() Method

My Code:
internal DbSet<TEntity> DbSet;
public virtual IEnumerable<TEntity> Get()
{
IQueryable<TEntity> query = DbSet;
return query.ToList();
}
As you can see above we are calling ToList() method. When I go into IQueryable, I have seen that it gets inheritence from IEnumerable but in IEnumerable I can not see any ToList() method. Where and how this method comes from? Can you help me please.
The extension methods provided for IQueryable<T> and IEnumerable<T> are generally respectively found in the types Queryable and Enumerable.
Keep in mind that the former are interfaces. Interfaces can't have implementations defined. These are extension methods (with implementation) which means they need to be defined in a static class as static methods.
Queryable [MSDN]
Enumerable [MSDN]
Extension Methods [MSDN]

How to Moq a service in a controller which use unitofwork with generic repository

I am a newbie in TDD (Asp.net MVC3 environment) and trying to adopt TDD as our better better development approach.
In our production code,we have a following scenario
In web
//Autofac used to resolve Dependency
TestController(XService xSerivice,YSerivice yService)
{_xService =xService,_YService= yService}
[HTTPPost]
ActionResult Create(A1 a1)
{
_xService.XUnitOfWork.A1.add(a1)
_xService.XUnitOfwork.SaveChanges();
}
// where X, Y are different context,Concrete class, no interface implemented!
In Business Layer
Xservice(XUnitofWork) // no interface implemented!
In DAL Layer
'XUnitofWork:DataRepostory(Generic)...
{
GenericRepository<a1Entity> A1,
GenericRepository<a2Entity> A2
}
Now I realize that we should implement interface both in our BAL and Web layer.
My question is are there any way i can mock the services(XService,YService) in our controller to test some behavior (TDD) [for example save change exception occur while saving a entity via' _xService.XUnitOfwork.SaveChanges()'?
Please help.Thanks in Advance!
If you mark members (properties, methods) in your concrete class as virtual, I think you may be able to just mock those methods / properties individually. (I think the VB equivalent of virtual is Overridable..?)
Moq works by creating a new concrete implementation of something at runtime when your test runs. This is why it works so well with interfaces and abstract classes. But if there is no interface or abstract class, it needs to override a method or property.
Reply to question author's answer:
Since you are a self-proclaimed TDD newbie, I just wanted to point out that adding a parameterless constructor to a class just for the sake of making the class testable should not be an acceptable solution.
By giving your GenericRepository class a hard dependency on Entity Framework's DbSet / IDbSet, you are creating a tight coupling between your repository implementation and EF... note the using System.Data.Entity line at the top of that file.
Any time you decide to add a constructor dependency, you should seriously consider adding it as an interface or abstract class. If you need access to members of a library which you do not control (like EF's DbContext), follow Morten's answer and wrap the functionality in your own custom interface.
In the case of DbContext, this class does more than just provide you with a UnitOfWork implementation. It also provides you a way of querying out data and adding / replacing / removing items in your repository:
public interface IUnitOfWork
{
int SaveChanges();
}
public interface IQuery
{
IQueryable<TEntity> GetQueryable<TEntity>() where TEntity : class;
}
public interface ICommand : IQuery
{
void Add(object entity);
void Replace(object entity);
void Remove(object entity);
}
You can pretty easily wrap DbContext in these 3 interfaces like so:
public class MyCustomDbContext : DbContext, IUnitOfWork, ICommand
{
// DbContext already implements int SaveChanges()
public IQueryable<TEntity> GetQueryable<TEntity>() where TEntity : class
{
return this.Set<TEntity>();
}
public void Add(object entity)
{
this.Entry(entity).State = EntityState.Added;
}
public void Replace(object entity)
{
this.Entry(entity).State = EntityState.Modified;
}
public void Remove(object entity)
{
this.Entry(entity).State = EntityState.Deleted;
}
}
Note how your interfaces take no dependencies on System.Data.Entity. They use primitives and standard .NET types like object, IQueryable<T>, and int. This way, when you give your generic repository dependencies on the interfaces, you can remove the dependency on System.Data.Entity:
// using System.Data.Entity; // no need for this dependency any more
public class GenericRepository
{
private readonly ICommand _entities;
private readonly IQueryable<TEntity> _queryable;
public GenericRepository(ICommand entities)
{
this._entities = entities;
this._queryable = entities.GetQueryable<TEntity>();
}
//public GenericRepository()
//{
// no need for a parameterless constructor!
//}
}
...and your GenericRepository is now fully unit testable, since you can easily mock any of these interface methods.
Final Notes:
Also, after seeing your answer to your own question, it looks like you have CompanyRepository as a property of your UnitOfWork class. You then inject UnitOfWork as a dependency on your CompanyInformationController. This is backwards. Instead, you should be injecting the CompanyRepository (or its interface) into the controller's constructor. The UnitOfWork pattern has nothing to do with maintaining references for your known repositories. It is about tracking multiple changes made to related items so that they can all be pushed once as a single transaction. EF does this automatically, so as long as AutoFac is providing the same DbContext instance no matter whether your app requests an IQuery, ICommand, or IUnitOfWork implementation, then the only method UnitOfWork should be concerned with is SaveChanges().
thanks for your reply. The test I was trying to do was successful after spending few hours and changes my previous code.
Changes are follows:
1) Now using UnitofWork in my controller instead of a redundant service.
2) Added a parameter less constructor to the GenericRepository Class.(with out any DBContext!),because it will requied a DBContext as a parameter in Constructor,which can not be substituted by supplying a Mocked DBContext.
GenericRepository:
public class GenericRepository where TEntity : class
{
internal DbContext _context;
internal DbSet<TEntity> dbSet;
public GenericRepository(DbContext context)
{
this._context = context;
this.dbSet = context.Set<TEntity>();
}
public GenericRepository() //newly added!
{
}
...............
Complete Test
[TestMethod]
public void Index_Return_OneModel_WhenCalling()
{
//arrange
AutoMapperExtension automapper = new AutoMapperExtension();
var moqentities = new Mock<SetupEntities>();
List<CompanyInformation> list =new List<CompanyInformation>();
list.Add(new CompanyInformation{ CompanyName = "a", CompanyAddress = "aa", Id = 1});
list.Add(new CompanyInformation { CompanyName = "b", CompanyAddress = "b", Id = 2 });
var unitOfWork = new Mock<UnitOfWork>(moqentities.Object);
unitOfWork.Setup(d => d.CompanyRepository).Returns(new GenericRepository<CompanyInformation>());
unitOfWork.Setup(d => d.CompanyRepository.GetAll()).Returns(list.AsQueryable());
var controller = new CompanyInformationController(unitOfWork.Object);
//Act
var result =(ViewResult) controller.Index();
var model =(CompanyInformationViewModel) result.ViewData.Model;
//Assert
Assert.AreEqual(1, model.Id);
}
The best way is to create an interface for XService. If that is not possible for some reason (if XService is a third party class that doesn't implement an interface), then consider wrapping the functionality in a wrapperclass that does have an interface.

Compiled Linq with Generic Repository Design Pattern

I've been looking around the web but I've yet to found any information on this. As we know Linq gives us CompiledQuery which transform the expression into T-SQL before running it. I'm trying to design a generic repository to interact with my EF but with the exception the Linq queries is compiled. If anyone could shead some light on this that would be great :)
It is hardly possible because if you want to pre-compile query you must know it. With generic repository you usually have only this:
public interface IRepository<T>
{
IQueryable<T> GetQuery();
}
So the code using a repository instance is responsible for defining the query. Pre-compilation requires concrete repository which will contain methods like:
IEnumerable<Order> GetOrdersWithHeaderAndItemsByDate(DateTime date, int take, int skip);
IEnumerable<OrderHeader> GetOrderHeadersOrderedByCustomer(int take, int skip);
etc.
Obviously you can hardly prepare such queries in generic repository beacuse they are dependent on concrete entity.
You are looking for an implementation of the Specification pattern. Basically, this is creating a Specification object that contains the information needed to filter your query. By using Specifications, you can have a Generic Repository implementation, and put your custom query logic in the specification. The specification base class looks something like:
public class Specification<TEntity>
{
public Specification(Expression<Func<TEntity, bool>> predicate)
{
_predicate = predicate;
}
public bool IsSatisfiedBy(TEntity entity)
{
return _predicate.Compile().Invoke(entity);
}
public Expression<Func<TEntity,bool>> PredicateExpression{
get{ return _predicate; }
}
private Expression<Func<TEntity, bool>> _predicate;
}
A very helpful article about implementing the specification pattern with the Entity Framework can be found at http://huyrua.wordpress.com/2010/07/13/entity-framework-4-poco-repository-and-specification-pattern/

Why is generated override code for generic method incorrect?

I have an abstract generic class
public abstract class Foo<TType>
with an abstract method
public abstract object DoSomething(TType arg = default(TType)) {}
Now, the inherited class
public class BabyFoo : Foo<string>
when I want to override DoSomething and start typing "override " to get the intellisense/generator to write a method skeleton I expected
public override object DoSomething(string arg = default(string))
or even
public override object DoSomething(string arg = null)
but it literally comes up with
public override object DoSomething(string arg = default(TType))
My initial thought is it is a VS2010 bug since optional params are new to c#, but can anybody tell me if there is perhaps a real reason why (reference types vs value types??) the IDE generates this code?
Just to clarify:
public abstract class Foo<TType>
{
public abstract object DoSomething(TType arg = default(TType));
}
public class BabyFoo : Foo<string>
{
// Expected:
public override object DoSomething(string arg = default(string))
// Actual:
public override object DoSomething(string arg = default(TType));
}
Unless there's something I'm missing, it's quite simply a bug in the Visual Studio IDE / code-gen. Changing the method signature to the "expected" one results in code that will compile, as the "actual" one refuses to compile thanks to being clearly invalid.
Having tried a few different types for TType as well as things like the where TType : new() constraint, I couldn't get VS to generate valid code with your DoSomething method.
Congratulations - you've (probably) found a bug in Visual Studio =)
There are always edge cases when it comes to code generation, I logged one for Visual Basic 2005/2008 a long time ago that was resolved WONT FIX as it was a really obscure one comparatively. Hopefully this one'll be fixed though!

Resources