Odd bug in C#4 compiler? Alias namespaces getting mixed up - visual-studio-2010

Here's my issue,
I'm using a namespace to remove ambiguity from a factory class which is creating domain objects from entity framework entity objects (a POCO factory,.. if that makes sense!). Call me old fashioned but I like things this way :-)
The namespaces I'm working with are aliased as such -
using Entities = DataAccess.Models.AccessControl;
using Cases = DomainModel.BusinessObjects.Implimentations.Cases;
Now, the DomainModel.BusinessObjects.Implimentations.Cases namespace only has one type so far called CaseType. However whilst I was working on another type which consumes the CaseType class I noticed that when I 'dot' into the Cases alias, it points to a totally different namespace in my DataAccess assembly and gives me the CaseTypeFactory in intellisense.
So I checked the CaseType and CaseTypeFactory classes and they are namespaced correctly. What in god's name is going on? I really can't work this one out.
Here's the code for the CaseType and CaseTypeFactory if it helps.
CaseTypeFactory
using Domain = DomainModel.BusinessObjects.Implimentations.Cases;
using Entities = DataAccess.Models.AccessControl;
using Interfaces.DataAccess;
namespace DataAccess.Factories.Cases
{
public class CaseTypeFactory :
IEntityPOCOFactory<Domain.CaseType, Entities.CaseType>
{
#region IEntityPOCOFactory<CaseType,CaseType> Members
public Domain.CaseType CreatePOCO(Entities.CaseType entity)
{
return new Domain.CaseType(entity.Id, entity.Name, entity.LastChanged);
}
public IList<Domain.CaseType> CreatePOCOs(
IEnumerable<Entities.CaseType> entities)
{
var toReturn = new List<Domain.CaseType>();
foreach (var entity in entities)
{
toReturn.Add(CreatePOCO(entity));
}
return toReturn;
}
#endregion
}
}
CaseType
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DomainModel.BusinessObjects.Base;
namespace DomainModel.BusinessObjects.Implimentations.Cases
{
public class CaseType : NamedNumberedAndVersioned
{
public CaseType(string name, DateTime lastChanged)
: this(0, name, lastChanged) { }
public CaseType(int id, string name, DateTime lastChanged)
: base(id, name, lastChanged) { }
public void Update(string name)
{
this.Name = name;
}
}
}
It's probably worth mentioning I'm working with .Net 4.0 / VS2010
Any help would be massively appreciated.
Thanks in advance.

Is the code you're writing in the DataAccess.Factories namespace? If so, then Cases will indeed resolve to DataAccess.Factories.Cases first.
Two options:
Use an alias which isn't also the name of another namespace, e.g.
using DomainCases = ...
Use :: instead of . to force it to use the alias:
IEntityPOCOFactory<Cases::CaseType, Whatever>
I'd personally go for the first option to make things clearer... or try to avoid requiring namespace aliases to start with.

Related

IQueryable Extension Behavior Differing For Automapper Polymorphic Collection

Using Automapper 3.3.1.0 there is a different mapping behavior between the usage of Mapper.Map<IEnumerable<TDestination>>(someEnumerable) compared to someEnumerable.AsQueryable().Project().To<TDestination>()
This does not appear to be a limitation of a SQL LINQ provider or other as this is witnessed in an in-memory collection.
As with many things this is best explained by example:
Note: the following code can be found at https://gist.github.com/kmoormann/b3949d006f4083ab6ee4
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using FluentAssertions;
using NUnit.Framework;
namespace Automapper.PolymorphicList.Tests
{
[TestFixture]
class AutomapperQueryableExtensionPolymorphism
{
//taking the class structure from: https://github.com/AutoMapper/AutoMapper/wiki/Mapping-inheritance
public class Order { }
public class OnlineOrder : Order
{
public string Referrer { get; set; }
}
public class MailOrder : Order { }
//Dtos
public class OrderDto
{
public string Referrer { get; set; }
}
[Test(Description = "Does the same mapping behavior exist for a polymorphic list when doing the project querable extension as when doing the static mapper map method()")]
public void IsSameBehaviorForQueryableExtensionAndStaticMap()
{
Mapper.Reset();
//Mappings
Mapper.CreateMap<Order, OrderDto>()
.Include<OnlineOrder, OrderDto>()
.Include<MailOrder, OrderDto>()
.ForMember(o => o.Referrer, m => m.Ignore());
Mapper.CreateMap<OnlineOrder, OrderDto>();
Mapper.CreateMap<MailOrder, OrderDto>();
//build lists
var onlineOrders = new List<OnlineOrder>() { new OnlineOrder() { Referrer = "one" }, new OnlineOrder() { Referrer = "two" } };
var mailOrders = new List<MailOrder>() { new MailOrder() };
//single typed list mapping
var mappedOnlineOrderDtos = Mapper.Map<IEnumerable<OrderDto>>(onlineOrders);
var projectedOnlineOrderDtos = onlineOrders.AsQueryable().Project().To<OrderDto>();
//using FluentAssertions for collection assertions
projectedOnlineOrderDtos.ShouldBeEquivalentTo(mappedOnlineOrderDtos, "automapper can handle singly typed lists");
//other single typed list mapping
var mappedMailOrderDtos = Mapper.Map<IEnumerable<OrderDto>>(mailOrders);
var projectedMailOrderDtos = mailOrders.AsQueryable().Project().To<OrderDto>();
projectedMailOrderDtos.ShouldBeEquivalentTo(mappedMailOrderDtos, "automapper can handle singly typed lists");
//build a polymorphic list
var orders = new List<Order>();
orders.AddRange(onlineOrders);
orders.AddRange(mailOrders);
// Perform Mapping and Projection
var mappedPolymorhpicOrders = Mapper.Map<IEnumerable<OrderDto>>(orders);
var projectedPolymorphicOrders = orders.AsQueryable().Project().To<OrderDto>();
projectedPolymorphicOrders.ShouldBeEquivalentTo(mappedPolymorhpicOrders, "automapper can handle polymorphic typed lists?");
}
}
}
I understand there are limitations to the .Project().To<TDestination> IQueryable extensions but what I am unaware of is:
which limitation is causing this behavior?
is this a Automapper limitation or a LINQ limitation
is there a work around to still use the queryable extensions and not revert Mapper.Map<TDestination>(obj) exclusively?
for posterity: link discussion thread topic
This is a LINQ limitation. AutoMapper does not inherit base mappings for LINQ. What would be the Select expression to do polymorphic Select projections? Trying to do that leads you to where you can't do this. LINQ query providers don't support it.

Strange: Entity framework (code first) slower and behave strangly with generic repository

We have a generic repository done with code-first technique. As the code is in testing we realized that the generic repository is relatively slower than that of directly accessing the DBContext and loading data. In order to simulate the issue for you all, we simplify the generic repository wrote a new code and that code is pasted below..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DemoTest.Bll.Models;
using DemoTest.Bll.DB;
using MasIt.Common.BackEnd;
using System.Data.Entity;
namespace DemoTest.Bll.Handlers
{
public abstract class MyHandlerBase<E, T>
where E : DbSet<T>
where T : class, IBaseObject
{
public MyHandlerBase(E mySet)
{
dbSet = mySet;
}
public E dbSet;
protected IEnumerable<T> GetAllNew(Func<T, bool> predicate)
{
try
{
return dbSet.Where(predicate).AsEnumerable();
}
catch { return null; }
}
}
public class StudentHandler : MyHandlerBase<DbSet<Student>, Student>
{
public StudentHandler()
:base(DemoDBContext.GetContext().Students)
{
//_entitySet = new DemoDBContext().Students;
}
public List<Student> getList(bool option1)
{
if (option1)
{
// Option 1 this is very fast and hit the Student Constructor only once
IEnumerable<Student> response1 = this.dbSet.Where(x => x.StudentId == 10).AsEnumerable();
return response1.ToList();
}
else
{
// Option 2 this is very slow and hit the Student Constructor the student record count of the table
IEnumerable<Student> response2 = this.GetAllNew(x => x.StudentId == 10);
return response2.ToList();
}
}
}
}
Can anybody say why Option 2 is slower.. it is not just slow, it hits the Student class constructor many times, while option 1 hits the constructor only once.. So it seems to us that option 1 load only the matching record, where as option 2 load all the records and match them in memory to filter records..
Generic Repository is a must.. Any fix is highly appreciated...
Got the fix...
Replacing
"Func<T, bool> predicate" with
"Expression<Func<E, Boolean>>" predicate did the trick..
Man .. a horrible nightmare is just over..

Getting a reference to the AsCached property in the ObjectContext for Entity Framework 4.1

I have my ObjectContext exposed as a public property and am able to access it via my DBContext.
I want to enable caching for a drop down list. It requires the AsCached property. However, I can't get it to display in the intellisense. Do I need to include a specific namespace for it?
Here is my existing LINQ statement that I want cached.
IQueryable<Category> category = DbContext.Categories.Where(p => p.CategoryID > 0);
I'm tying to do something like this. Note though, that there is no intellisense when placing the "." after Objectcontext.
IQueryable<Category> category = DbContext.Objectcontext.Categories.AsCached.Where(p => p.CategoryID > 0);
The ObjectContext pops up in the intellisense, but not the AsCached property.
How can I get the AsCached property to appear?
Are you referring to the AsCached property described here Getting a reference to the AsCached property? In which case it seems to be an extension to the EF called linqtocache.
EDIT
I do not think you need to expose ObjectContext. Say you have a DbContext that looks like this:
public class DatabaseContext : DbContext
{
public DatabaseContext(string name) : base(name)
{
As = Set<A>();
}
public DbSet<A> As { get; private set; }
}
AsCached, in the context of linqtocache, is an extension method on IQueryable so in your code that calls it you can get access to the AsCached property by doing this:
using LinqToCache;
namespace MyApplication
{
class Program
{
static void Main()
{
var ctx = new DatabaseContext("ScalabilityTestEntities");
ctx.As.AsCached("Key").Where(p => p.CategoryID > 0);
}
}
}

Import does not resolve needed type in asp.net mvc 3 with mef

I used an example on extensible asp.net mvc 3 to build my plug-able application, but I encountered a problem. In a plug-in I declared and implmemented an interface.
But, in plug-in controller when I want to use this class, the application throws an error and it seems that EntityConfig was not initialized. How can this be fixed?
[Export(typeof(IController)), ExportMetadata("controllerName", "Concept")]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class ConceptController : Controller
{
[Import(typeof(IEntityConfig))]
private IEntityConfig EntityConfig;
public ActionResult Index()
{
var obs = EntityConfig.EntityName;
return View("~/Bin/Views/Concept/Index.cshtml",obs );
}
}
public interface IEntityConfig
{
string EntityName { get;}
}
[Export(typeof(IEntityConfig))]
public class TestEntity : IEntityConfig
{
public string EntityName
{
get{return "Test";}
}
}
Edited :
In other side, when I is use this example, there is no problem in resolving EntityConfig, but in the view, when I want to load model as follows :
#using Concepts
#model Concepts.Models.TestModel
the application throws an error and tells me 'The type or namespace name 'Concepts' could not be found', although when I check container after it was initiated, I can see Concepts in in loaded assemblies.
Would you please help me ?
Thanks.
Edited :
I uploaded the samples :
First one
Second one
Edited (2011/22/09):
I tested the above code on other sample that #Matthew Abbott provided in his blog, and it worked, although this sample has been built against mvc 2.0.
Looking over your code, can you be sure that the part is actually being imported? Your constructor code for your composition container is such like:
var discoverableControllerFactory = new DiscoverableControllerFactory(
new CompositionContainer(
new DirectoryCatalog(extensionsPath))
);
You're only including your extensions path as a catalog. Can you guaruntee that you're also including your base application path, e.g.:
var discoverableControllerFactory = new DiscoverableControllerFactory(
new CompositionContainer(
new AggregateCatalog(
new DirectoryCatalog("bin"),
new DirectoryCatalog(extensionsPath)))
);
If the parts actually exist in your Unity container, you could add an export provider that grabs those parts from that container and allows them to be composed by MEF.
As for your second problem, you will need to subclass the System.Web.WebPages.Razor.RazorBuildProvider to ensure it includes assemblies in your extensions directory:
namespace ExtensibleMvcApplication
{
public class CustomRazorBuildProvider : RazorBuildProvider
{
public static IEnumerable<Assembly> _assemblies;
static CustomRazorBuildProvider()
{
string extensionsPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Extensions");
_assemblies = Directory.GetFiles(extensionsPath, "*.dll")
.Select(Assembly.Load);
}
public override void GenerateCode(System.Web.Compilation.AssemblyBuilder assemblyBuilder)
{
foreach (var assembly in _assemblies)
assemblyBuilder.AddAssemblyReference(assembly);
base.GenerateCode(assemblyBuilder);
}
}
}
Which you'd need to register in your config:
<buildProviders>
<remove extension=".cshtml" />
<add extension=".cshtml" type="ExtensibleMvcApplication.CustomRazorBuildProvider, ExtensibleMvcApplication"/>
</buildProviders>

Telerik RadGrid and RadComboBox filtering with a separate data class?

I'm trying to implement a GridBoundColumn for filtering as described in this Telerik demo.
The example queries the database directly using SqlDataAdapter, but I want to use an existing class elsewhere in my project, and configure the DataSource of the filter RadComboBox in the RadGrid to use the LINQ data context common to the rest of my project.
namespace MyProject.DataLib
{
// Data context lives here.
}
namespace MyProject.UI
{
public partial class MyUI : PageBase
{
public class rgcFilterColumn : GridBoundColumn
{
...
protected void list_ItemsRequested(object o, RadComboBoxItemsRequestedEventArgs e)
{
using (MyProject.DataLib = new DataLib(CurrentUser)) // error CurrentUser
{
((RadComboBox)o).DataTextField = DataField;
((RadComboBox)o).DataValueField = DataField;
((RadComboBox)o).DataSource = ???; // LINQ would go here...?
((RadComboBox)o).DataBind();
}
}
}
}
}
The user defined by CurrentUser has the necessary credentials, however when I try to do this (which I know is wrong):
Cannot access non-static property 'CurrentUser' in static context.
What would be the best way to accomplish what I want here, as well as clarify my incomplete understanding of why I can't simply talk to my existing data context?
Found the solution, should've just looked around more closely.

Resources