Data deletion through WFC data service client applciation - oracle

I am self hosting a Odata WCF data service in a console application that is hooked up to an Oracle database through ADO.Net entity model. i am using Microsoft.Data.Services v5.5.0.I can read/write data through the client application but cannot delete. Here is the code:
Server code:
public class tos_host : DataService<Entities>
{
public static void InitializeService(DataServiceConfiguration config)
{
// TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
// Examples:
config.SetEntitySetAccessRule("*", EntitySetRights.All);
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
}
}
class Program
{
static void Main(string[] args)
{
Uri[] baseAddresses = new Uri[1];
baseAddresses[0] = new Uri("http://localhost:4444/tos_host");
using (DataServiceHost host = new DataServiceHost(typeof(tos_host), baseAddresses))
{
host.Open();
Console.WriteLine("TOS host up and running.....");
Console.ReadLine();
host.Close();
}
}
}
Client code:
static void Main(string[] args)
{
Entities context = new Entities(new Uri("http://localhost:4444/tos_host"));
context.MergeOption = MergeOption.OverwriteChanges;
context.IgnoreMissingProperties = true;
var container = new CONTAINERS();
container.CONTAINER_ID = "CONT";
container.TIMESTAMP=DateTime.UtcNow;
context.AddToCONTAINERS(container);
context.SaveChanges();
CONTAINERS container_2 = context.CONTAINERS.Where(c => c.CONTAINER_ID == "CONT").First();
context.DeleteObject(container_2);
context.SaveChanges(); //Here i get an exception
}
The exception is as follows:
System.Data.Services.Client.DataServiceRequestException was unhandled
HResult=-2146233079
Message=An error occurred while processing this request.
Source=Microsoft.Data.Services.Client
StackTrace:
at System.Data.Services.Client.SaveResult.HandleResponse()
at System.Data.Services.Client.BaseSaveResult.EndRequest()
at System.Data.Services.Client.DataServiceContext.SaveChanges(SaveChangesOptions options)
at System.Data.Services.Client.DataServiceContext.SaveChanges()
at client_test_lnew_libs.Program.Main(String[] args) in c:\Users\ITS\Desktop\rmcs_tests \client_test_lnew_libs\client_test_lnew_libs\Program.cs:line 27
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.Data.Services.Client.DataServiceClientException
HResult=-2146233079
Message=<?xml version="1.0" encoding="utf-8"?><m:error xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"><m:code /><m:message xml:lang="el-GR">Resource not found for the segment 'CONTAINERS'.</m:message></m:error>
StatusCode=404
InnerException:
What am i doing wrong? Any clues?

From my understanding, when you query and no results are returned, the dataservice will throw the exception you're seeing. To return an empty set instead, you need to set the IgnoreResourceNotFoundException property:
context.IgnoreResourceNotFoundException = true;
See the following blog post for more information:
http://blogs.msdn.com/b/peter_qian/archive/2009/03/20/safe-resource-not-found-404-exception-handling-in-ado-net-data-service-client.aspx?Redirected=true

Related

ASP.NET Boilerplate: ObjectDisposedException in EventHandler

I use ABP 5.1.0
.Net Core,
I have my class
ItemAsyncEventBaseHandler : IAsyncEventHandler<TEvent>, ITransientDependency
where TEvent : EventData {…}
Then i have class:
CustomHandler: ItemAsyncEventBaseHandler<EventData>
{
public CustomHandler(
IUnitOfWorkManager unitOfWorkManager,
ISettingManager settingManager)
{
_unitOfWorkManager = unitOfWorkManager;
_settingManager = settingManager;
}
}
public override async Task HandleInternallyAsync(ItemUpdatedEvent eventData)
{
await _settingManager.ChangeSettingForApplicationAsync("key", value.ToString());
}
At first glance, this works, but if I run the handler on two different items in quick succession, I get an error:
(On some machines it is enough to run the event on two items, on others it is necessary to run the event on the other two items in order for the same error to occur.)
System.ObjectDisposedException: Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
Object name: 'MyDbContext'.
at Microsoft.EntityFrameworkCore.DbContext.CheckDisposed()
at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
at Microsoft.EntityFrameworkCore.DbContext.Set[TEntity]()
at Abp.EntityFrameworkCore.Repositories.EfCoreRepositoryBase`3.GetQueryable()
at Abp.EntityFrameworkCore.Repositories.EfCoreRepositoryBase`3.GetAllIncluding(Expression`1[] propertySelectors)
at Abp.EntityFrameworkCore.Repositories.EfCoreRepositoryBase`3.FirstOrDefaultAsync(Expression`1 predicate)
at Abp.Threading.InternalAsyncHelper.AwaitTaskWithPostActionAndFinallyAndGetResult[T](Task`1 actualReturnValue, Func`1 postAction, Action`1 finalAction)
at Abp.Configuration.SettingStore.GetSettingOrNullAsync(Nullable`1 tenantId, Nullable`1 userId, String name)
at Abp.Threading.InternalAsyncHelper.AwaitTaskWithPostActionAndFinallyAndGetResult[T](Task`1 actualReturnValue, Func`1 postAction, Action`1 finalAction)
at Abp.Configuration.SettingManager.InsertOrUpdateOrDeleteSettingValueAsync(String name, String value, Nullable`1 tenantId, Nullable`1 userId)
at Abp.Configuration.SettingManager.ChangeSettingForApplicationAsync(String name, String value)
at Abp.Threading.InternalAsyncHelper.AwaitTaskWithPostActionAndFinally(Task actualReturnValue, Func`1 postAction, Action`1 finalAction)
at Nito.AsyncEx.Synchronous.TaskExtensions.WaitAndUnwrapException(Task task)
at Nito.AsyncEx.AsyncContext.<>c__DisplayClass15_0.<Run>b__0(Task t)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location where exception was thrown ---
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
--- End of stack trace from previous location where exception was thrown ---
at Nito.AsyncEx.Synchronous.TaskExtensions.WaitAndUnwrapException(Task task)
at Nito.AsyncEx.AsyncContext.Run(Func`1 action)
And the value in the application settings is not updated.
I tried wrapping in uow but it doesn't help:
public override async Task HandleInternallyAsync(ItemUpdatedEvent eventData)
{
using (var uow = _unitOfWorkManager.Begin(TransactionScopeOption.RequiresNew))
{
await _settingManager.ChangeSettingForApplicationAsync("key", value.ToString());
await uow.CompleteAsync();
}
}

ASP.NET Core tries to cast an object to System.Int64 when using LINQ GroupBy

When trying to execute the following ASP.NET Core code:
public class Foo
{
public long A { get; set; }
public string B { get; set; }
}
[HttpGet]
[Route("Foos")]
public ActionResult<IEnumerable<IGrouping<long, Foo>>> Foos()
{
var foos = new List<Foo> { new Foo { A = 1, B = "Foo" }, new Foo { A = 2, B = "Bar" }, new Foo { A = 2, B = "Baz" } };
return new ActionResult<IEnumerable<IGrouping<long, Foo>>>(foos.GroupBy(f => f.A));
}
I get:
System.InvalidCastException: Unable to cast object of type 'Foo' to type 'System.Int64'.
at System.Text.Json.JsonPropertyInfoNotNullable`4.OnWriteEnumerable(WriteStackFrame& current, Utf8JsonWriter writer)
at System.Text.Json.JsonPropertyInfo.WriteEnumerable(WriteStack& state, Utf8JsonWriter writer)
at System.Text.Json.JsonSerializer.HandleEnumerable(JsonClassInfo elementClassInfo, JsonSerializerOptions options, Utf8JsonWriter writer, WriteStack& state)
at System.Text.Json.JsonSerializer.Write(Utf8JsonWriter writer, Int32 originalWriterDepth, Int32 flushThreshold, JsonSerializerOptions options, WriteStack& state)
at System.Text.Json.JsonSerializer.WriteAsyncCore(Stream utf8Json, Object value, Type inputType, JsonSerializerOptions options, CancellationToken cancellationToken)
at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|29_0[TFilter,TFilterAsync](ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
Why does it seem to be trying to serialize an object to an int64? How can I successfully return the result of a GroupBy from a web API endpoint?
New System.Text.Json serializer cannot serialize IEnumerable<IGrouping<long, Foo>>.
Solution
I would recommend switching to old Json.Net serializer in your ASP.Net Core project. I've tested it and it works fine with Json.Net.
See this article for information about switching to Json.Net.
It will be something as easy as that:
services.AddMvc()
.AddNewtonsoftJson();

AsyncTaskCodeActivity and lost context after await

AsyncTaskCodeActivity fails when the context parameter is accessed after the first await is performed. For example:
public class TestAsyncTaskCodeActivity : AsyncTaskCodeActivity<int>
{
protected async override Task<int> ExecuteAsync(AsyncCodeActivityContext context, CancellationToken cancellationToken)
{
await Task.Delay(50);
// context has already been disposed and the next line throws
// ObjectDisposedException with the message:
// An ActivityContext can only be accessed within the scope of the function it was passed into.
context.Track(new CustomTrackingRecord("test"));
// more awaits can happen here
return 3;
}
}
Is there any simple way to preserve the context so it can be used also after awaiting something?
Ah.
When I wrote AsyncTaskCodeActivity<T>, I assumed that the AsyncCodeActivityContext was in fact going to be the same instance at the beginning and end of the asynchronous method, and be available all the way through. This is not the case (which is a bit odd - not sure why the WF team made that decision).
Instead, the AsyncCodeActivityContext can only be accessed at the beginning and end of the activity. Awkward, indeed.
The updated code below will allow you to access the context at the beginning (e.g., reading In variables) and then access the context again at the end. I also introduce an optional TState, which can be used for storing activity state (which the activity can access throughout its execution). Let me know if this fits your needs; I haven't tested it.
public abstract class AsyncTaskCodeActivity<T, TState> : AsyncCodeActivity<T>
{
protected sealed override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state)
{
TState activityState = PreExecute(context);
context.UserState = activityState;
var task = ExecuteAsync(activityState);
return AsyncFactory<T>.ToBegin(task, callback, state);
}
protected sealed override T EndExecute(AsyncCodeActivityContext context, IAsyncResult asyncResult)
{
var result = AsyncFactory<T>.ToEnd(asyncResult);
return PostExecute(context, (TState)context.UserState, result);
}
protected virtual TState PreExecute(AsyncCodeActivityContext context)
{
return default(TState);
}
protected abstract Task<T> ExecuteAsync(TState activityState);
protected virtual T PostExecute(AsyncCodeActivityContext context, TState activityState, T result)
{
return result;
}
}
public abstract class AsyncTaskCodeActivity<T> : AsyncTaskCodeActivity<T, object>
{
}

MVVM Light IoC not Binding? What am I missing?

I have a windows 7 phone application that I am working on. I made a couple service classes with interfaces but every-time I try to navigate too these views they now crash.
I setup my project to load one of these views as soon as the emulator loads up(through WMAppManifest.xml)
I have something like this
public interface IGpsService
{
void StartGps();
GeoPosition<GeoCoordinate> CurrentPostion();
}
public class GpsService : IGpsService
{
private GeoCoordinateWatcher gpsWatcher;
public GpsService()
{
gpsWatcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default)
{
MovementThreshold = 20,
};
}
public void StartGps()
{
gpsWatcher.Start();
}
public GeoPosition<GeoCoordinate> CurrentPostion()
{
return gpsWatcher.Position;
}
}
my view model locator
static ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
if (ViewModelBase.IsInDesignModeStatic)
{
SimpleIoc.Default.Register<IGpsService, Design.GpsDataService>();
}
else
{
SimpleIoc.Default.Register<IGpsService, GpsService>();
}
SimpleIoc.Default.Register<AddProductPriceVm>();
}
// AddProductPrice.xaml.cs
public AddProductPrice(IGpsService gpsService)
{
InitializeComponent();
}
Does the Ioc only bind to View Models or something? Is that why it is not working as I have it in my code behind?
I am using a mix of code behind and MVVM as something are just so much easier to do with code behind.
Error Message
MissingMethodException
at System.Activator.InternalCreateInstance(Type type, Boolean nonPublic, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type)
at System.Windows.Navigation.PageResourceContentLoader.BeginLoad_OnUIThread(AsyncCallback userCallback, PageResourceContentLoaderAsyncResult result)
at System.Windows.Navigation.PageResourceContentLoader.<>c__DisplayClass4.<BeginLoad>b__0(Object args)
at System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi, Object obj, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)
at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at System.Delegate.DynamicInvokeOne(Object[] args)
at System.MulticastDelegate.DynamicInvokeImpl(Object[] args)
at System.Delegate.DynamicInvoke(Object[] args)
at System.Windows.Threading.DispatcherOperation.Invoke()
at System.Windows.Threading.Dispatcher.Dispatch(DispatcherPriority priority)
at System.Windows.Threading.Dispatcher.OnInvoke(Object context)
at System.Windows.Hosting.CallbackCookie.Invoke(Object[] args)
at System.Windows.Hosting.DelegateWrapper.InternalInvoke(Object[] args)
at System.Windows.RuntimeHost.ManagedHost.InvokeDelegate(IntPtr pHandle, Int32 nParamCount, ScriptParam[] pParams, ScriptParam& pResult)
Dies in NavigationFailed
// Code to execute if a navigation fails
private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// A navigation has failed; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
You're injecting the service directly into the View, not the viewmodel. The View is not created using SimpleIoc so has no knowledge of where to resolve your IGpsService reference in the constructor.
Your best bet, if you want to do this, is to inject the IGpsService into your viewmodel and expose it as a property. Add a DataContextChanged event to your view and, when it fires, take the IGpsService from the viewmodel.
Edit:
//AddProductPrice View
<UserControl
DataContext="{StaticResource Locator.AddProductPriceVm}">
/ AddProductPrice.xaml.cs
public AddProductPrice()
{
InitializeComponent();
DataContextChanged+=DataContextChanged
}
void DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
var context=sender as AddProductPriceVm;
if(context!=null)
_myGpsService=context.GpsService;
}
//AddProductPriceVm
public class AddProductPriceVm
{
public AddProductPriceVm(IGpsService gpsService)
{
GpsService=gpsService;
}
public IGpsService GpsService{get;set;}
}
The issue isn't really a DI problem, it's just how the MVVM Light works. It expects the view to be there before it permforms and dependency injection. if you wanted to inject things directly into the view then you could look at using Prism (but it's much heavier with lots more scaffolding).

Ninject bbv EventBroker subscription error

I am attempting to use bbv.common.EventBroker with Ninject and am running into a few problems getting things wired up correctly.
I currently am using Ninject factories to create an item and then, since I subscribe to events, use the eventbroker to do the subscription. However when the register method is called I get an error that I can not find any information for at all. I am not even sure what the error means.
Error:
bbv.Common.EventBroker.Exceptions.RepeatedSubscriptionException occurred
Message=Cannot add more than one subscription handler method of the same subscriber one topic: 'Method1'.
Source=bbv.Common.EventBroker
StackTrace:
at bbv.Common.EventBroker.Internals.EventTopic.ThrowIfRepeatedSubscription(Object subscriber, String handlerMethodName)
at bbv.Common.EventBroker.Internals.EventTopic.AddSubscription(Object subscriber, MethodInfo handlerMethod, IHandler handler, IList`1 subscriptionMatchers)
at bbv.Common.EventBroker.Internals.EventInspector.HandleSubscriber(Object subscriber, Boolean register, MethodInfo methodInfo, EventSubscriptionAttribute attr, IEventTopicHost eventTopicHost)
at bbv.Common.EventBroker.Internals.EventInspector.ProcessSubscriber(Object subscriber, Boolean register, IEventTopicHost eventTopicHost)
at bbv.Common.EventBroker.EventBroker.Register(Object item)
InnerException:
Code:
public const string Topic1 = "Topic1";
public const string Topic2 = "Topic2";
public const string Topic3 = "Topic3";
public const string Topic4 = "Topic4";
public ItemHelper(IItem item, IEventBroker eventBroker)
{
_item = item;
eventBroker.Register(this);
}
[EventSubscription(Topic1, typeof(bbv.Common.EventBroker.Handlers.Publisher))]
public void Method1(object sender, SomeArgs1 args)
{
...
}
[EventSubscription(Topic2, typeof(bbv.Common.EventBroker.Handlers.Publisher))]
public void Method2(object sender, SomeArgs2 args)
{
...
}
[EventSubscription(Topic3, typeof(bbv.Common.EventBroker.Handlers.Publisher))]
public void Method3(object sender, SomeArgs3 args)
{
...
}
[EventSubscription(Topic4, typeof(bbv.Common.EventBroker.Handlers.Publisher))]
public void Method4(object sender, SomeArgs4 args)
{
...
}
It turned out that the class had an interface which had the [EventSubscription] attributes on its methods. The error message does make a lot more sense now that I know this.

Resources