Onion Architecture Unit Of Work Transaction Not getting Connection String - asp.net

I am using Onion Architecture with Autofac. In my Dependency Injection Code, I am using:
[assembly: WebActivatorEx.PostApplicationStartMethod(typeof(IocConfig), "RegisterDependencies")]
namespace AppMVC.Infrastructure.Bootstrapper
{
public class IocConfig
{
public static void RegisterDependencies()
{
var builder = new ContainerBuilder();
builder.RegisterType(typeof(UnitOfWork)).As(typeof(IUnitOfWork)).InstancePerHttpRequest();
builder.Register<IEntitiesContext>(b =>
{
var context = new MyContext("My Connection String");
return context;
}).InstancePerHttpRequest();
}
}
}
Unit Of Work Code:
public class UnitOfWork : IUnitOfWork
{
private readonly IEntitiesContext _context;
private bool _disposed;
private Hashtable _repositories;
public UnitOfWork(IEntitiesContext context)
{
_context = context;
}
public int SaveChanges()
{
return _context.SaveChanges();
}
public IRepository<TEntity> Repository<TEntity>() where TEntity : BaseEntity
{
if (_repositories == null)
{
_repositories = new Hashtable();
}
var type = typeof(TEntity).Name;
if (_repositories.ContainsKey(type))
{
return (IRepository<TEntity>)_repositories[type];
}
var repositoryType = typeof(EntityRepository<>);
_repositories.Add(type, Activator.CreateInstance(repositoryType.MakeGenericType(typeof(TEntity)), _context));
return (IRepository<TEntity>)_repositories[type];
}
public void BeginTransaction()
{
_context.BeginTransaction();
}
public int Commit()
{
return _context.Commit();
}
public void Rollback()
{
_context.Rollback();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public virtual void Dispose(bool disposing)
{
if (!_disposed && disposing)
{
_context.Dispose();
foreach (IDisposable repository in _repositories.Values)
{
repository.Dispose();// dispose all repositries
}
}
_disposed = true;
}
}
MyContext Code:
public class MyContext : DbContext, IEntitiesContext
{
private ObjectContext _objectContext;
private DbTransaction _transaction;
public MyContext(string nameOrConnectionString)
: base(nameOrConnectionString)
{
}
public void BeginTransaction()
{
_objectContext = ((IObjectContextAdapter)this).ObjectContext;
if (_objectContext.Connection.State == ConnectionState.Open)
{
if (_transaction == null)
{
_transaction = _objectContext.Connection.BeginTransaction();
}
return;
}
_objectContext.Connection.Open(); // At this Line, I am getting Exception
if (_transaction == null)
{
_transaction = _objectContext.Connection.BeginTransaction();
}
}
public int Commit()
{
var saveChanges = SaveChanges();
_transaction.Commit();
return saveChanges;
}
public void Rollback()
{
_transaction.Rollback();
}
}
My problem is, On _objectContext.Connection.Open();, I am getting Connection String missing error.
Below is the screenshot of the Exception:

Related

Switch Toggling Event Using MVVM

I realized recently that a switch doesn't have a command. And i need to bind the toggling event to my view model. How do i go about it?
I tried to bind the command to Toggled event but the code is running into error
You can use EventToCommandBehavior to convert the event to command
create the EventToCommandBehavior class
using System;
using Xamarin.Forms;
namespace xxx
{
public class BehaviorBase<T> : Behavior<T> where T : BindableObject
{
public T AssociatedObject { get; private set; }
protected override void OnAttachedTo(T bindable)
{
base.OnAttachedTo(bindable);
AssociatedObject = bindable;
if (bindable.BindingContext != null)
{
BindingContext = bindable.BindingContext;
}
bindable.BindingContextChanged += OnBindingContextChanged;
}
protected override void OnDetachingFrom(T bindable)
{
base.OnDetachingFrom(bindable);
bindable.BindingContextChanged -= OnBindingContextChanged;
AssociatedObject = null;
}
void OnBindingContextChanged(object sender, EventArgs e)
{
OnBindingContextChanged();
}
protected override void OnBindingContextChanged()
{
base.OnBindingContextChanged();
BindingContext = AssociatedObject.BindingContext;
}
}
}
using System;
using System.Reflection;
using System.Windows.Input;
using Xamarin.Forms;
namespace xxx
{
public class EventToCommandBehavior : BehaviorBase<View>
{
Delegate eventHandler;
public static readonly BindableProperty EventNameProperty = BindableProperty.Create("EventName", typeof(string), typeof(EventToCommandBehavior), null, propertyChanged: OnEventNameChanged);
public static readonly BindableProperty CommandProperty = BindableProperty.Create("Command", typeof(ICommand), typeof(EventToCommandBehavior), null);
public static readonly BindableProperty CommandParameterProperty = BindableProperty.Create("CommandParameter", typeof(object), typeof(EventToCommandBehavior), null);
public static readonly BindableProperty InputConverterProperty = BindableProperty.Create("Converter", typeof(IValueConverter), typeof(EventToCommandBehavior), null);
public string EventName
{
get { return (string)GetValue(EventNameProperty); }
set { SetValue(EventNameProperty, value); }
}
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
public object CommandParameter
{
get { return GetValue(CommandParameterProperty); }
set { SetValue(CommandParameterProperty, value); }
}
public IValueConverter Converter
{
get { return (IValueConverter)GetValue(InputConverterProperty); }
set { SetValue(InputConverterProperty, value); }
}
protected override void OnAttachedTo(View bindable)
{
base.OnAttachedTo(bindable);
RegisterEvent(EventName);
}
protected override void OnDetachingFrom(View bindable)
{
DeregisterEvent(EventName);
base.OnDetachingFrom(bindable);
}
void RegisterEvent(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return;
}
EventInfo eventInfo = AssociatedObject.GetType().GetRuntimeEvent(name);
if (eventInfo == null)
{
throw new ArgumentException(string.Format("EventToCommandBehavior: Can't register the '{0}' event.", EventName));
}
MethodInfo methodInfo = typeof(EventToCommandBehavior).GetTypeInfo().GetDeclaredMethod("OnEvent");
eventHandler = methodInfo.CreateDelegate(eventInfo.EventHandlerType, this);
eventInfo.AddEventHandler(AssociatedObject, eventHandler);
}
void DeregisterEvent(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return;
}
if (eventHandler == null)
{
return;
}
EventInfo eventInfo = AssociatedObject.GetType().GetRuntimeEvent(name);
if (eventInfo == null)
{
throw new ArgumentException(string.Format("EventToCommandBehavior: Can't de-register the '{0}' event.", EventName));
}
eventInfo.RemoveEventHandler(AssociatedObject, eventHandler);
eventHandler = null;
}
void OnEvent(object sender, object eventArgs)
{
if (Command == null)
{
return;
}
object resolvedParameter;
if (CommandParameter != null)
{
resolvedParameter = CommandParameter;
}
else if (Converter != null)
{
resolvedParameter = Converter.Convert(eventArgs, typeof(object), null, null);
}
else
{
resolvedParameter = eventArgs;
}
if (Command.CanExecute(resolvedParameter))
{
Command.Execute(resolvedParameter);
}
}
static void OnEventNameChanged(BindableObject bindable, object oldValue, object newValue)
{
var behavior = (EventToCommandBehavior)bindable;
if (behavior.AssociatedObject == null)
{
return;
}
string oldEventName = (string)oldValue;
string newEventName = (string)newValue;
behavior.DeregisterEvent(oldEventName);
behavior.RegisterEvent(newEventName);
}
}
}
in your xaml
<Switch >
<Switch.Behaviors>
<local:EventToCommandBehavior EventName="Toggled" Command="{Binding ToggledCommand}"/>
</Switch.Behaviors>
</Switch>
And in your ViewModel
public class MyViewModel
{
public ICommand ToggledCommand { get; private set; }
public MyViewModel()
{
ToggledCommand = new Command(() => {
// do some thing you want
});
}
}
I bind a bool property on my viewmodel to the IsToggled property on the switch, then handle when this changes in the viewmodel.

Xamarin Forms Custom GridView Tap and Long Tap Not Working Together

I want to use tap and long tap together with Custom Gridview.
Tap is working but long tap not working.
it also works when one tap turns off the long tap.
Please help me.
Thank you.
public class GridView : Grid
{
public static readonly BindableProperty ItemsSourceProperty = BindableProperty.Create(nameof(ItemsSource), typeof(IList), typeof(GridView), default(IList), BindingMode.TwoWay);
public static readonly BindableProperty ItemTappedCommandProperty = BindableProperty.Create(nameof(ItemTappedCommand), typeof(ICommand), typeof(GridView), null);
public static readonly BindableProperty ItemLongTappedCommandProperty = BindableProperty.Create(nameof(ItemLongTappedCommand), typeof(ICommand), typeof(GridView), null);
public static readonly BindableProperty ItemTemplateProperty = BindableProperty.Create(nameof(ItemTemplate), typeof(DataTemplate), typeof(GridView), default(DataTemplate));
public static readonly BindableProperty MaxColumnsProperty = BindableProperty.Create(nameof(MaxColumns), typeof(int), typeof(GridView), 2);
public static readonly BindableProperty TileHeightProperty = BindableProperty.Create(nameof(TileHeight), typeof(float), typeof(GridView), 220f);//adjusted here reuired height
public GridView()
{
PropertyChanged += GridView_PropertyChanged;
PropertyChanging += GridView_PropertyChanging;
}
public IList ItemsSource
{
get { return (IList)GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
public ICommand ItemTappedCommand
{
get { return (ICommand)GetValue(ItemTappedCommandProperty); }
set { SetValue(ItemTappedCommandProperty, value); }
}
public ICommand ItemLongTappedCommand
{
get { return (ICommand)GetValue(ItemLongTappedCommandProperty); }
set { SetValue(ItemLongTappedCommandProperty, value); }
}
public DataTemplate ItemTemplate
{
get { return (DataTemplate)GetValue(ItemTemplateProperty); }
set { SetValue(ItemTemplateProperty, value); }
}
public int MaxColumns
{
get { return (int)GetValue(MaxColumnsProperty); }
set { SetValue(MaxColumnsProperty, value); }
}
public float TileHeight
{
get { return (float)GetValue(TileHeightProperty); }
set { SetValue(TileHeightProperty, value); }
}
private void BuildColumns()
{
ColumnDefinitions.Clear();
for (var i = 0; i < MaxColumns; i++)
{
ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
}
}
private View BuildTile(object item1)
{
var template = ItemTemplate.CreateContent() as View;
template.BindingContext = item1;
if (ItemTappedCommand != null)
{
var tapGestureRecognizer = new TapGestureRecognizer
{
Command = ItemTappedCommand,
CommandParameter = item1,
};
template.GestureRecognizers.Add(tapGestureRecognizer);
}
// Tap komutu eziyor.
if (ItemLongTappedCommand != null)
{
template.Effects.Add(new LongPressedEffect());
LongPressedEffect.SetCommand(template, ItemLongTappedCommand);
//LongPressedEffect.SetCommandParameter(template, item1);
}
return template;
}
private void BuildTiles()
{
// Wipe out the previous row & Column definitions if they're there.
if (RowDefinitions.Any())
{
RowDefinitions.Clear();
}
BuildColumns();
Children.Clear();
var tiles = ItemsSource;
if (tiles != null)
{
var numberOfRows = Math.Ceiling(tiles.Count / (float)MaxColumns);
for (var i = 0; i < numberOfRows; i++)
{
RowDefinitions.Add(new RowDefinition { Height = new GridLength(0, GridUnitType.Auto) });
}
for (var index = 0; index < tiles.Count; index++)
{
var column = index % MaxColumns;
var row = (int)Math.Floor(index / (float)MaxColumns);
var tile = BuildTile(tiles[index]);
Children.Add(tile, column, row);
}
}
}
private void GridView_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == ItemsSourceProperty.PropertyName)
{
var items = ItemsSource as INotifyCollectionChanged;
if (items != null)
items.CollectionChanged += ItemsCollectionChanged;
BuildTiles();
}
if (e.PropertyName == MaxColumnsProperty.PropertyName || e.PropertyName == TileHeightProperty.PropertyName)
{
BuildTiles();
}
}
private void GridView_PropertyChanging(object sender, Xamarin.Forms.PropertyChangingEventArgs e)
{
if (e.PropertyName == ItemsSourceProperty.PropertyName)
{
var items = ItemsSource as INotifyCollectionChanged;
if (items != null)
items.CollectionChanged -= ItemsCollectionChanged;
}
}
private void ItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
BuildTiles();
}
}
public class LongPressedEffect : RoutingEffect
{
public LongPressedEffect() : base("MyApp.LongPressedEffect")
{ }
public static readonly BindableProperty CommandProperty = BindableProperty.CreateAttached("Command", typeof(ICommand), typeof(LongPressedEffect), (object)null);
public static ICommand GetCommand(BindableObject view)
{
//do something you want
Console.WriteLine("long press Gesture recognizer has been striked");
return (ICommand)view.GetValue(CommandProperty);
}
public static void SetCommand(BindableObject view, ICommand value)
{
view.SetValue(CommandProperty, value);
}
public static readonly BindableProperty CommandParameterProperty = BindableProperty.CreateAttached("CommandParameter", typeof(object), typeof(LongPressedEffect), (object)null);
public static object GetCommandParameter(BindableObject view)
{
return view.GetValue(CommandParameterProperty);
}
public static void SetCommandParameter(BindableObject view, object value)
{
view.SetValue(CommandParameterProperty, value);
}
}
I noticed you used Effect to create your own long pressed command. But if you consumed a TapGestureRecognizer at the same time, it will intercept the effect. Then your long pressed command won't be triggered.
You can either define the single tap click event in the effect to achieve them both. Here is my effect:
public class PressedEffect : RoutingEffect
{
public PressedEffect() : base("MyApp.PressedEffect")
{
}
public static readonly BindableProperty LongTapCommandProperty = BindableProperty.CreateAttached("LongTapCommand", typeof(ICommand), typeof(PressedEffect), (object)null);
public static ICommand GetLongTapCommand(BindableObject view)
{
return (ICommand)view.GetValue(LongTapCommandProperty);
}
public static void SetLongTapCommand(BindableObject view, ICommand value)
{
view.SetValue(LongTapCommandProperty, value);
}
public static readonly BindableProperty LongParameterProperty = BindableProperty.CreateAttached("LongParameter", typeof(object), typeof(PressedEffect), (object)null);
public static object GetLongParameter(BindableObject view)
{
return view.GetValue(LongParameterProperty);
}
public static void SetLongParameter(BindableObject view, object value)
{
view.SetValue(LongParameterProperty, value);
}
public static readonly BindableProperty TapCommandProperty = BindableProperty.CreateAttached("TapCommand", typeof(ICommand), typeof(PressedEffect), (object)null);
public static ICommand GetTapCommand(BindableObject view)
{
return (ICommand)view.GetValue(TapCommandProperty);
}
public static void SetTapCommand(BindableObject view, ICommand value)
{
view.SetValue(TapCommandProperty, value);
}
public static readonly BindableProperty TapParameterProperty = BindableProperty.CreateAttached("TapParameter", typeof(object), typeof(PressedEffect), (object)null);
public static object GetTapParameter(BindableObject view)
{
return view.GetValue(TapParameterProperty);
}
public static void SetTapParameter(BindableObject view, object value)
{
view.SetValue(TapParameterProperty, value);
}
}
Android implementation:
[assembly: ResolutionGroupName("MyApp")]
[assembly: ExportEffect(typeof(AndroidPressedEffect), "PressedEffect")]
namespace PressedEffectDemo.Droid
{
public class AndroidPressedEffect : PlatformEffect
{
private bool _attached;
public static void Initialize() { }
public AndroidPressedEffect()
{
}
protected override void OnAttached()
{
if (!_attached)
{
if (Control != null)
{
Control.LongClickable = true;
Control.LongClick += Control_LongClick;
Control.Click += Control_Click;
}
else
{
Container.LongClickable = true;
Container.LongClick += Control_LongClick;
Container.Click += Control_Click;
}
_attached = true;
}
}
private void Control_Click(object sender, EventArgs e)
{
var command = PressedEffect.GetTapCommand(Element);
command?.Execute(PressedEffect.GetTapParameter(Element));
}
private void Control_LongClick(object sender, Android.Views.View.LongClickEventArgs e)
{
var command = PressedEffect.GetLongTapCommand(Element);
command?.Execute(PressedEffect.GetLongParameter(Element));
}
protected override void OnDetached()
{
if (_attached)
{
if (Control != null)
{
Control.LongClickable = true;
Control.LongClick -= Control_LongClick;
Control.Click -= Control_Click;
}
else
{
Container.LongClickable = true;
Container.LongClick -= Control_LongClick;
Control.Click -= Control_Click;
}
_attached = false;
}
}
}
}
iOS implementation:
[assembly: ResolutionGroupName("MyApp")]
[assembly: ExportEffect(typeof(iOSPressedEffect), "PressedEffect")]
namespace PressedEffectDemo.iOS
{
public class iOSPressedEffect : PlatformEffect
{
private bool _attached;
private readonly UILongPressGestureRecognizer _longPressRecognizer;
private readonly UITapGestureRecognizer _tapRecognizer;
public iOSPressedEffect()
{
_longPressRecognizer = new UILongPressGestureRecognizer(HandleLongClick);
_tapRecognizer = new UITapGestureRecognizer(HandleClick);
}
protected override void OnAttached()
{
if (!_attached)
{
Container.AddGestureRecognizer(_longPressRecognizer);
Container.AddGestureRecognizer(_tapRecognizer);
_attached = true;
}
}
private void HandleClick()
{
var command = PressedEffect.GetTapCommand(Element);
command?.Execute(PressedEffect.GetTapParameter(Element));
}
private void HandleLongClick(UILongPressGestureRecognizer recognizer)
{
if (recognizer.State == UIGestureRecognizerState.Ended)
{
var command = PressedEffect.GetLongTapCommand(Element);
command?.Execute(PressedEffect.GetLongParameter(Element));
}
}
protected override void OnDetached()
{
if (_attached)
{
Container.RemoveGestureRecognizer(_longPressRecognizer);
Container.RemoveGestureRecognizer(_tapRecognizer);
_attached = false;
}
}
}
}
At last, you can consume them on XAML like:
<StackLayout>
<Grid HeightRequest="200"
BackgroundColor="Green"
local:PressedEffect.TapCommand="{Binding TapCommand}"
local:PressedEffect.LongTapCommand="{Binding LongTapCommand}">
<Grid.Effects>
<local:PressedEffect />
</Grid.Effects>
</Grid>
</StackLayout>
You could refer to my sample here.

Spring custom Generic converter not working

In my spring mvc web-application i use a generic converter that converts String (id) to Company by fetch using (service and dao) components
first of all in my MVC-config i add the converter like follow :
#Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new GenericIdToCompanyConverter(new CompanyServiceImp()));
}
companyService
#Service
#Transactional
#Qualifier("companyService")
public class CompanyServiceImp implements ICompanyService {
#Resource
#Qualifier("companyDAO")
private ICompanyDao dao;
public void setDao(ICompanyDao dao) {
this.dao = dao;
}
#Override
public Company find(Long id) throws BusinessException {
Company current = dao.find(id);
if(current == null) {
throw new BusinessException("notFound");
}
return current;
}
....
}
Generic converter :
public class GenericIdToCompanyConverter implements GenericConverter {
private ICompanyService companyService;
public GenericIdToCompanyConverter(ICompanyService companyService) {
super();
this.companyService = companyService;
}
#Override
public Set<ConvertiblePair> getConvertibleTypes() {
ConvertiblePair[] pairs = new ConvertiblePair[] { new ConvertiblePair(Number.class, Company.class), new ConvertiblePair(String.class, Company.class) };
return ImmutableSet.copyOf(pairs);
}
#Override
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
long id = 0;
if( sourceType.getType() == String.class) {
try {
id = Long.valueOf((String) source);
}catch(NumberFormatException e) {
return null;
}
}else if( sourceType.getType() == Number.class) {
id = (Long) source;
}else {
return null;
}
try {
return companyService.find(Long.valueOf(id));
} catch (BusinessException e) {
return null;
}
}
}
and here the controller that receives data form (via ajax request)
public #ResponseBody JsonResponseBean applay(#Valid VoucherForm form, BindingResult result, Locale locale) throws BusinessException {
....
}
where VoucherForm has these attributes
public class VoucherForm{
protected Long id;
protected Company company;
...
}
when i run the application and call controller method it returns type mismatch error for company attribute
and when i execute this on debug mode i see that it fails on serviceCompany - dao.find(id) statment where my dao is == null
Please help
finally i have to autowire the converter
Mvc-config
....
#Autowired
private GenericIdToCompanyConverter genericIdToCompanyConverter;
#Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(genericIdToCompanyConverter);
}
and update the converter like follow :
public class GenericIdToCompanyConverter implements GenericConverter {
#Resource
#Qualifier("companyService")
private ICompanyService companyService;
#Override
public Set<ConvertiblePair> getConvertibleTypes() {
....
}
#Override
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
....
}
}

Unit Testing Generic Handlers

How can i test return value of "ProcessRequest" method in a generic handler with unit Test?
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
}
public bool IsReusable
{
get
{
return false;
}
}
}
Instead of using mock, try to create test HttpContext with SimpleWorkerRequest like this:
SimpleWorkerRequest testRequest = new SimpleWorkerRequest("","","", null, new StringWriter());
HttpContext testContext = new HttpContext(testRequest);
HttpContext.Current = testContext;
Then you could create your handler and provide testContext to the ProcessRequest method:
var handler = new Handler1();
handler.ProcessRequest(testContext);
Then you could check HttpContext.Current.Response to make assertion about your test.
UPDATE:
I am attaching the full example of working unit-test(implementation of OutputFilterStream was taken from here):
[TestFixture]
[Category("Unit")]
public class WhenProcessingRequest
{
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
}
public bool IsReusable
{
get
{
return false;
}
}
}
public class OutputFilterStream : Stream
{
private readonly Stream InnerStream;
private readonly MemoryStream CopyStream;
public OutputFilterStream(Stream inner)
{
this.InnerStream = inner;
this.CopyStream = new MemoryStream();
}
public string ReadStream()
{
lock (this.InnerStream)
{
if (this.CopyStream.Length <= 0L ||
!this.CopyStream.CanRead ||
!this.CopyStream.CanSeek)
{
return String.Empty;
}
long pos = this.CopyStream.Position;
this.CopyStream.Position = 0L;
try
{
return new StreamReader(this.CopyStream).ReadToEnd();
}
finally
{
try
{
this.CopyStream.Position = pos;
}
catch { }
}
}
}
public override bool CanRead
{
get { return this.InnerStream.CanRead; }
}
public override bool CanSeek
{
get { return this.InnerStream.CanSeek; }
}
public override bool CanWrite
{
get { return this.InnerStream.CanWrite; }
}
public override void Flush()
{
this.InnerStream.Flush();
}
public override long Length
{
get { return this.InnerStream.Length; }
}
public override long Position
{
get { return this.InnerStream.Position; }
set { this.CopyStream.Position = this.InnerStream.Position = value; }
}
public override int Read(byte[] buffer, int offset, int count)
{
return this.InnerStream.Read(buffer, offset, count);
}
public override long Seek(long offset, SeekOrigin origin)
{
this.CopyStream.Seek(offset, origin);
return this.InnerStream.Seek(offset, origin);
}
public override void SetLength(long value)
{
this.CopyStream.SetLength(value);
this.InnerStream.SetLength(value);
}
public override void Write(byte[] buffer, int offset, int count)
{
this.CopyStream.Write(buffer, offset, count);
this.InnerStream.Write(buffer, offset, count);
}
}
[Test]
public void should_write_response()
{
//arrange
SimpleWorkerRequest testRequest = new SimpleWorkerRequest("", "", "", null, new StringWriter());
HttpContext testContext = new HttpContext(testRequest);
testContext.Response.Filter = new OutputFilterStream(testContext.Response.Filter);
//act
var handler = new Handler1();
handler.ProcessRequest(testContext);
testContext.Response.End();//end request here(if it is not done in your Handler1)
//assert
var result = ((OutputFilterStream)testContext.Response.Filter).ReadStream();
Assert.AreEqual("Hello World", result);
}
}

EF SingleOrDefault doesn't work on ASP.NET

I've wrote some unit-tests for my project who tests my presenters, these presenters queries an EF context with SingleOrDefault, all the unit-tests are successful. But when I run my ASP.NET application I get continuously the error "'Single' not supported by Linq to Entities?" I want to know why this behavior is kicking in? I can't find any documentation about this behavior.
I use the following code:
Presenter:
public class ManagedQueryPresenter : BasePresenterMetModel<IManagedQueriesView, ManagedQueryBeheerModel>, IWebPartPresenter
{
public ManagedQueryPresenter(IManagedQueriesView view) : base(view, new ManagedQueryBeheerModel()) { }
#region IPagePresenter Members
public void OnViewInitialize()
{
}
public void OnViewInitialized()
{
}
public void OnViewLoaded()
{
}
#endregion
public void OnManagedQueriesSelecting()
{
View.ManagedQueries = Model.GetAll();
}
public void OnManagedQueryInserted(ManagedQuery entity)
{
Model.AddManagedQuery(entity);
View.ManagedQueries = Model.GetAll();
}
public void OnManagedQueryUpdated(ManagedQuery entity)
{
Model.UpdateManagedQuery(entity);
}
public void OnManagedQueryDeleted(ManagedQuery entity)
{
Model.DeleteManagedQuery(entity);
}
}
Model:
public class ManagedQueryBeheerModel : BaseModel, IModel
{
public void AddManagedQuery(ManagedQuery entity)
{
...
}
public void DeleteManagedQuery(ManagedQuery entity)
{
...
}
public void UpdateManagedQuery(ManagedQuery entity)
{
DoEntityAction<bool>(context =>
{
ManagedQuery toUpdate = context.ManagedQueries.Include(q => q.ManagedQueryParameters).SingleOrDefault(x => x.ID == entity.ID);
...
context.SaveChanges();
return true;
});
}
public IList<ManagedQuery> GetAll()
{
return DoRepositoryAction<ManagedQuery, List<ManagedQuery>>(repository => (List<ManagedQuery>)repository.GetAll());
}
public ManagedQuery Get(long ID)
{
return DoRepositoryAction<ManagedQuery, ManagedQuery>(repository => repository.GetSingleOrDefault(x => x.ID == ID));
}
}
UnitTest:
[TestMethod()]
public void OnManagedQueryUpdatedTest()
{
IManagedQueriesView view = new MockedManagedQueriesView();
ManagedQueryPresenter target = new ManagedQueryPresenter(view);
ManagedQuery entity = ManagedQueryHelper.CreateNewRecord(target.Model);
entity.Name += "Updated";
target.OnManagedQueryUpdated(entity);
}
public static class ManagedQueryHelper
{
public static ManagedQuery CreateNewRecord(ManagedQueryBeheerModel model)
{
ManagedQuery entity = new ManagedQuery
{
Description = "Test Query",
Name = "Test",
QueryText = #"SOME QUERY",
HasOutput = true,
Category = "Test",
};
model.AddManagedQuery(entity);
return entity;
}
}
ASP.NET View (Codebehind of ascx):
public partial class ManagedQueriesUserControl : WebPartMangedUserControlWithPresenter<ManagedQueryPresenter>, IManagedQueriesView
{
protected ASPxGridView _grid;
protected ObjectContainerDataSource _ocdsManagedQueries;
#region IServicesView Members
public IList<Entities.ManagedQuery> ManagedQueries
{
set
{
_grid.ForceDataRowType(typeof(ManagedQuery));
_ocdsManagedQueries.DataSource = value;
}
}
#endregion
protected void _ocdsManagedQueries_Deleted(object sender, Microsoft.Practices.Web.UI.WebControls.ObjectContainerDataSourceStatusEventArgs e)
{
Presenter.OnManagedQueryDeleted((ManagedQuery)e.Instance);
}
protected void _ocdsManagedQueries_Updated(object sender, Microsoft.Practices.Web.UI.WebControls.ObjectContainerDataSourceStatusEventArgs e)
{
Presenter.OnManagedQueryUpdated((ManagedQuery)e.Instance);
}
protected void _ocdsManagedQueries_Inserted(object sender, Microsoft.Practices.Web.UI.WebControls.ObjectContainerDataSourceStatusEventArgs e)
{
Presenter.OnManagedQueryInserted((ManagedQuery)e.Instance);
}
protected void _ocdsManagedQueries_Selecting(object sender, Microsoft.Practices.Web.UI.WebControls.ObjectContainerDataSourceSelectingEventArgs e)
{
Presenter.OnManagedQueriesSelecting();
}
#region IWebPartView Members
public bool IsValid()
{
return Page.IsValid;
}
public string ErrorText
{
set { }
}
#endregion
}
I believe you can find the answer on this thread Error, method not supported by LINQ to Entities
I was forgotten that unittests are by default in VS2010 written in .NET 4 and my code in .NET3.5 so therefore it isn't working. In EF4 Single(OrDefault) is supported!

Resources