When I start my page everything loads fine I try to reload for the second time I get the following error
I run the urls from angular
A second operation started on this context before a previous
asynchronous operation completed. Use 'await' to ensure that any
asynchronous operations have completed before calling another method
on this context. Any instance members are not guaranteed to be thread
safe.
This is the method
private readonly PuntovService puntovService = new PuntovService(new PuntovRepository(CentralContext.Create()));
private readonly IMapper mapper;
public PuntovController()
{
this.mapper = WebApiApplication.MapperConfiguration.CreateMapper();
}
[HttpGet]
[Route("Puntos")]
[ResponseType(typeof(IEnumerable<PuntovDTO>))]
public async Task<IHttpActionResult> GetAll()
{
var pv = await puntovService.GetAll();
var puntovDTO = pv.Select(x => mapper.Map<PuntovDTO>(x));
var tipoComitePersona = from com in puntovDTO
select new {com.PuntoV};
return Ok(tipoComitePersona);
}
in this class call the context that would be the database
using APICentralBL.Models;
using System.Data.Entity;
namespace APICentralBL.Data
{
public class CentralContext : DbContext
{
private static CentralContext centralContext = null;
public CentralContext() : base("Context")
{
}
public DbSet<SDN> SDN { get; set;}
public DbSet<CALIF> CALIF { get; set; }
public DbSet<UVT> UVT { get; set; }
public DbSet<PUNTOV> PUNTOV { get; set; }
public DbSet<TRANS> TRANS { get; set; }
public static CentralContext Create()
{
if (centralContext == null)
centralContext = new CentralContext();
return centralContext;
}
}
}
It not only happens with this method, it happens when I try to call more than one
ex.StackTrace
en System.Data.Entity.Internal.ThrowingMonitor.EnsureNotEntered()
en System.Data.Entity.Core.Objects.ObjectQuery`1.System.Data.Entity.Infrastructure.IDbAsyncEnumerable<T>.GetAsyncEnumerator()
en System.Data.Entity.Infrastructure.IDbAsyncEnumerableExtensions.ForEachAsync[T](IDbAsyncEnumerable`1 source, Action`1 action, CancellationToken cancellationToken)
en System.Data.Entity.Infrastructure.IDbAsyncEnumerableExtensions.ToListAsync[T](IDbAsyncEnumerable`1 source, CancellationToken cancellationToken)
en System.Data.Entity.Infrastructure.IDbAsyncEnumerableExtensions.ToListAsync[T](IDbAsyncEnumerable`1 source)
en APICentralBL.Repositories.Implements.GenericRepository`1.<GetAll>d__3.MoveNext() en D:\ANTIOQUENA DEVELOPERS REPOSITORY\ANTIOQUENA DEVELOPERS\DEVELOPMENTS\API'S PROJECT\APICentral-Deploy\APICentralBL\Repositories\Implements\GenericRepository.cs: línea 33
en System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
en System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
en System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
en APICentralBL.Services.Implements.GenericService`1.<GetAll>d__3.MoveNext() en D:\ANTIOQUENA DEVELOPERS REPOSITORY\ANTIOQUENA DEVELOPERS\DEVELOPMENTS\API'S PROJECT\APICentral-Deploy\APICentralBL\Services\Implements\GenericService.cs: línea 25
en System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
en System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
en System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
en APICentral.Controllers.PuntovController.<GetAll>d__4.MoveNext() en D:\ANTIOQUENA DEVELOPERS REPOSITORY\ANTIOQUENA DEVELOPERS\DEVELOPMENTS\API'S PROJECT\APICentral-Deploy\APICentral\Controllers\PuntovController.cs: línea 65**
Since your context is stored in a static field, it will be shared by all threads serving requests to your controllers concurrently. You should usually use a context per request
Related
The server runs but when I try to connect to the server I recieve this Exception:
2023-01-12 15:10:00,023 [12] ERROR Photon.SocketServer.Peers.ManagedPeer - Autofac.Core.DependencyResolutionException:
An exception was thrown while activating NinjaBricks.NinjaPhoton.Implementation.Client.PhotonClientPeer ->
NinjaBricks.Framework.Implementation.Messaging.ClientHandlerList ->
λ:NinjaBricks.Framework.Interfaces.Messaging.IHandler`1[[NinjaBricks.Framework.Interfaces.Client.IClientPeer, NinjaBricks.Framework,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]][] -> NinjaBricks.NinjaPhoton.Implementation.Handler.ClientRequestForwardHandler.
---> Autofac.Core.DependencyResolutionException: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'NinjaBricks.NinjaPhoton.Implementation.Handler.ClientRequestForwardHandler' can be invoked with the available services and parameters:
Cannot resolve parameter 'NinjaBricks.Framework.Interfaces.Support.IClientCodeRemover clientCodeRemover' of constructor
'Void .ctor(ExitGames.Logging.ILogger,
NinjaBricks.Framework.Interfaces.Server.IServerConnectionCollection`2
[NinjaBricks.Framework.Interfaces.Config.IServerType,
NinjaBricks.Framework.Interfaces.Server.IServerPeer],
NinjaBricks.Framework.Interfaces.Support.IClientCodeRemover,
NinjaBricks.Framework.Interfaces.Config.IServerType)'.
en Autofac.Core.Activators.Reflection.ReflectionActivator.GetValidConstructorBindings(ConstructorInfo[] availableConstructors, IComponentContext context, IEnumerable`1 parameters)
en Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters)
en Autofac.Core.Resolving.InstanceLookup.CreateInstance(IEnumerable`1 parameters)
--- Fin del seguimiento de la pila de la excepción interna ---
en Autofac.Core.Resolving.InstanceLookup.CreateInstance(IEnumerable`1 parameters)
en Autofac.Core.Resolving.InstanceLookup.Execute()
en Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, ResolveRequest request)
en Autofac.Core.Resolving.ResolveOperation.Execute(ResolveRequest request)
en lambda_method(Closure , InitRequest )
en NinjaBricks.NinjaPhoton.Implementation.PhotonPeerFactory.CreatePeer[T](IPeerConfig config) en D:\Users\pndia\Documents\GitHub\NinjaBricks\ninja-bricks-game-server\NinjaBricks.NinjaPhoton\Implementation\PhotonPeerFactory.cs:lÃnea 61
en Photon.SocketServer.Peers.ManagedPeer.CreatePeerBase(InitRequest initRequest)
The code was made by other programmer and It is old code, but I Can't run it properly and i have no documentation about the code.
This is the ClientRequestForwardHandler class:
using ExitGames.Logging;
using NinjaBricks.Common;
using NinjaBricks.Common.Codes;
using NinjaBricks.Framework.Implementation.Config;
using NinjaBricks.Framework.Implementation.Messaging;
using NinjaBricks.Framework.Interfaces.Client;
using NinjaBricks.Framework.Interfaces.Config;
using NinjaBricks.Framework.Interfaces.Messaging;
using NinjaBricks.Framework.Interfaces.Server;
using NinjaBricks.Framework.Interfaces.Support;
using System;
using System.Linq;
namespace NinjaBricks.NinjaPhoton.Implementation.Handler
{
public class ClientRequestForwardHandler : IHandler<IClientPeer>, IDefaultRequestHandler<IClientPeer>
{
private readonly IServerConnectionCollection<IServerType, IServerPeer> _serverConnectionCollection;
private readonly IClientCodeRemover _clientCodeRemover;
private readonly IServerType _serverType;
public ILogger Log { get; set; }
public byte Code { get => 0x0ff; }
public int? SubCode { get => null; }
public MessageType Type { get => MessageType.Request; }
public ClientRequestForwardHandler(ILogger log,
IServerConnectionCollection<IServerType, IServerPeer> serverConnectionCollection,
IClientCodeRemover clientCodeRemover,
IServerType serverType)
{
Log = log;
_serverConnectionCollection = serverConnectionCollection;
_clientCodeRemover = clientCodeRemover;
_serverType = serverType;
}
public bool HandleMessage(IMessage message, IClientPeer clientPeer)
{
if (!message.Parameters.ContainsKey((byte)ParameterCode.ServerType))
{
return false;
}
var serverType = _serverType.GetServerType(Convert.ToInt32(message.Parameters[(byte)ParameterCode.ServerType]));
var server = _serverConnectionCollection.GetServersByType<IServerPeer>(serverType).FirstOrDefault();
if (server != null)
{
_clientCodeRemover.RemoveServerType(message);
_clientCodeRemover.RemovePeerId(message);
AddMessageCodes(message, clientPeer);
server.SendMessage(message);
return true;
}
return false;
}
private void AddMessageCodes(IMessage message, IClientPeer clientPeer)
{
message.Parameters.Add((byte)ParameterCode.PeerId, clientPeer.PeerId.ToByteArray());
}
}
}
And this is the IClientCodeRemover:
using NinjaBricks.Common.Codes;
using NinjaBricks.Framework.Interfaces.Messaging;
using NinjaBricks.Framework.Interfaces.Support;
namespace NinjaBricks.Framework.Implementation.Support
{
public class ClientCodeRemover : IClientCodeRemover
{
public void RemovePeerId(IMessage message)
{
message.Parameters.Remove((byte)MessageParameterCode.PeerId);
}
public void RemoveServerType(IMessage message)
{
message.Parameters.Remove((byte)ParameterCode.ServerType);
}
public void RemoveName(IMessage message)
{
message.Parameters.Remove((byte)ParameterCode.Name);
}
}
}
Also here the configs of autofac:
using Autofac;
using NinjaBricks.NinjaPhoton.Implementation;
using NinjaBricks.NinjaPhoton.Implementation.Client;
using NinjaBricks.NinjaPhoton.Implementation.Data;
using NinjaBricks.NinjaPhoton.Implementation.Handler;
using NinjaBricks.NinjaPhoton.Implementation.Server;
using NinjaBricks.Framework.Implementation.Client;
using NinjaBricks.Framework.Implementation.Config;
using NinjaBricks.Framework.Implementation.Messaging;
using NinjaBricks.Framework.Implementation.Server;
namespace NinjaBricks.NinjaPhoton.Modules
{
public class ProxyServerModule : Module
{
protected override void Load(ContainerBuilder builder)
{
base.Load(builder);
builder.RegisterType<ServerApplication>().AsImplementedInterfaces().SingleInstance();
builder.RegisterType<PhotonPeerFactory>().AsImplementedInterfaces().SingleInstance();
builder.RegisterType<PeerConfig>().AsImplementedInterfaces();
builder.RegisterType<SubServerClientPeer>().AsSelf().AsImplementedInterfaces();
builder.RegisterType<PhotonClientPeer>().AsSelf().AsImplementedInterfaces();
builder.RegisterType<PhotonServerPeer>().AsSelf().AsImplementedInterfaces();
builder.RegisterType<ServerConnectionCollection>().AsImplementedInterfaces().SingleInstance();
builder.RegisterType<ClientConnectionCollection>().AsImplementedInterfaces().SingleInstance();
builder.RegisterType<ServerHandlerList>().AsImplementedInterfaces();
builder.RegisterType<EventForwardHandler>().AsImplementedInterfaces();
builder.RegisterType<RequestForwardHandler>().AsImplementedInterfaces();
builder.RegisterType<ResponseForwardHandler>().AsImplementedInterfaces();
builder.RegisterType<ClientHandlerList>().AsImplementedInterfaces();
builder.RegisterType<ClientRequestForwardHandler>().AsImplementedInterfaces();
builder.RegisterType<ServerRegistrationHandler>().AsImplementedInterfaces();
builder.RegisterType<ServerData>().AsImplementedInterfaces();
}
}
}
Autofac version 5.2.0
Based on the provided code it seems that you have forgot to register ClientCodeRemover. Try adding:
builder.RegisterType<ClientCodeRemover>().AsImplementedInterfaces();
To your ProxyServerModule.Load method.
I have an exception when I try to receive data from more than three websockets. If I try on only one, two or three websockets it works perfectly.
I get the exception in this line:
tasks.Add(Send(webSocket, "11"));
The exception message:
Exception: System.Net.WebSockets.WebSocketException (0x80004005): The
'System.Net.WebSockets.InternalClientWebSocket' instance cannot be
used for communication because it has been transitioned into the
'Aborted' state. ---> System.OperationCanceledException: The operation
was canceled. at
System.Threading.CancellationToken.ThrowOperationCanceledException()
at
System.Net.WebSockets.WebSocketConnectionStream.d__21.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at
System.Net.WebSockets.WebSocketBase.WebSocketOperation.d__19.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
System.Net.WebSockets.WebSocketBase.d__45.MoveNext()
at System.Net.WebSockets.WebSocketBase.ThrowIfAborted(Boolean aborted,
Exception innerException) at
System.Net.WebSockets.WebSocketBase.ThrowIfConvertibleException(String
methodName, Exception exception, CancellationToken cancellationToken,
Boolean aborted) at
System.Net.WebSockets.WebSocketBase.d__45.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Here's my code:
using System;
using System.Collections.Generic;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using RTLS_GetData_From_WebSockets.App_Code;
namespace RTLS_GetData_From_WebSockets
{
class Program
{
private static object consoleLock = new object();
private const int sendChunkSize = 256;
private const int receiveChunkSize = 256;
private const bool verbose = true;
private static readonly TimeSpan delay = TimeSpan.FromMilliseconds(30000);
private static WebSocket client;
const string host = "ws://localhost:8080";
static void Main(string[] args)
{
Connect(host).Wait();
}
public static async Task Connect(string uri)
{
ClientWebSocket webSocket = null;
try
{
webSocket = new ClientWebSocket();
await webSocket.ConnectAsync(new Uri(uri), CancellationToken.None);
List<Task> tasks = new List<Task>();
tasks.Add(Receive(webSocket));
tasks.Add(Send(webSocket, "9"));
tasks.Add(Send(webSocket, "10"));
tasks.Add(Send(webSocket, "11"));
await Task.WhenAll(tasks);
}
catch (Exception ex)
{
Console.WriteLine("Exception: {0}", ex);
}
finally
{
if (webSocket != null)
webSocket.Dispose();
Console.WriteLine();
lock (consoleLock)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("WebSocket closed.");
Console.ResetColor();
}
}
}
static UTF8Encoding encoder = new UTF8Encoding();
private static async Task Send(ClientWebSocket webSocket, string ZoneID)
{
byte[] buffer = encoder.GetBytes("{\"method\":\"subscribe\", \"resource\":\"/zones/" + ZoneID + "\"}");
await webSocket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None);
while (webSocket.State == WebSocketState.Open)
{
LogStatus(false, buffer, buffer.Length);
await Task.Delay(delay);
}
}
private static async Task Receive(ClientWebSocket webSocket)
{
byte[] buffer = new byte[receiveChunkSize];
while (webSocket.State == WebSocketState.Open)
{
var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Close)
{
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
}
else
{
LogStatus(true, buffer, result.Count);
}
}
}
private static void LogStatus(bool receiving, byte[] buffer, int length)
{
lock (consoleLock)
{
Console.ForegroundColor = receiving ? ConsoleColor.Green : ConsoleColor.Gray;
if (verbose)
{
string tmp = encoder.GetString(buffer);
var data = JsonConvert.DeserializeObject<Zones>(tmp);
Console.WriteLine(data.body.status);
Console.WriteLine();
}
Console.ResetColor();
}
}
}
}
[DataContract]
public class Zones
{
[DataMember(Name = "body")]
public ZoneBody body { get; set; }
}
public class ZoneBody
{
[DataMember(Name = "feed_id")]
public string feed_id { get; set; }
[DataMember(Name = "zone_id")]
public string zone_id { get; set; }
[DataMember(Name = "status")]
public string status { get; set; }
[DataMember(Name = "at")]
public string at { get; set; }
}
This is from MSDN, here is the link.
This operation will not block. The returned Task object will complete
after the send request on the ClientWebSocket instance has completed.
Exactly one send and one receive is supported on each ClientWebSocket
object in parallel.
Call your Connect method one by one.
I have a controller the beginning of which looks like this:
[Route("api/[controller]")]
public class PersonsController : BaseController
BaseController looks like this so far:
public class BaseController : Controller
{
public BaseController(CompanyDbContext dbContext)
{
Db = dbContext;
}
protected CompanyDbContext Db;
}
PersonsController has a few gets, a post, a put, and a delete. Everything except the Delete action works fine, there are no problems resolving the injected CompanyDbContext.
The Delete action looks like this:
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(int id)
{
var pers = await Db.Persons.SingleOrDefaultAsync(p => p.PersonId == id);
if (pers == null)
{
return NotFound();
}
Db.Remove(pers);
await Db.SaveChangesAsync();
return Ok();
}
Yet when I do a delete request:
public async Task DeletePersonAsync(int id)
{
var resp = await _client.DeleteAsync($"api/Persons/{id}");
resp.EnsureSuccessStatusCode();
}
where _client is an HttpClient, I get the following error:
InvalidOperationException: Unable to resolve service for type
'AcmeSoft.Api.Data.CompanyDbContext' while attempting to activate
'AcmeSoft.Api.Controllers.PersonsController'
I am using the default, built-in DI that comes with a new MVC Core 2.0 project. I register the context service in class Startup as follows:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<CompanyDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc();
}
Yet the service resolves properly for all actions but Delete. What could be wrong here? Where have I gone wrong?
For those that like long questions, the entire PersonsController is as follows:
[Route("api/[controller]")]
public class PersonsController : BaseController
{
public PersonsController(CompanyDbContext dbContext) : base(dbContext)
{
}
[HttpGet]
public IActionResult Get()
{
var persons = Db.Persons.ToList();
return Ok(persons);
}
[HttpGet("{id}")]
public async Task<IActionResult> Get(int id)
{
var pers = await Db.Persons.SingleOrDefaultAsync(p => p.PersonId == id);
if (pers == null)
{
return Ok(null);
}
return Ok(pers);
}
[HttpGet("GetByIdNumber/{idNumber}")]
public async Task<IActionResult> GetByIdNumber(string idNumber)
{
var pers = await Db.Persons.SingleOrDefaultAsync(e => e.IdNumber == idNumber);
if (pers == null)
{
return Ok(null);
}
return Ok(pers);
}
[HttpGet("PersonEmployees")]
public async Task<IActionResult> PersonEmployees()
{
var emps = await Db.PersonEmployees.ToListAsync();
return Ok(emps);
}
[HttpPost]
public async Task<IActionResult> Post([FromBody] Person person)
{
Db.Add(person);
await Db.SaveChangesAsync();
return Ok(person);
}
[HttpPut]
public async Task<IActionResult> Put([FromBody] Person person)
{
Db.Update(person);
await Db.SaveChangesAsync();
return Ok(person);
}
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(int id)
{
var pers = await Db.Persons.SingleOrDefaultAsync(p => p.PersonId == id);
if (pers == null)
{
return NotFound();
}
Db.Remove(pers);
await Db.SaveChangesAsync();
return Ok();
}
}
All actions except delete work.
ADDED: The stack trace shown on the developer error page is:
System.InvalidOperationException: Unable to resolve service for type 'AcmeSoft.Api.Data.CompanyDbContext' while attempting to activate 'AcmeSoft.Api.Controllers.PersonsController'.
at Microsoft.Extensions.Internal.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
at lambda_method(Closure , IServiceProvider , Object[] )
at Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider.<>c__DisplayClass4_0.<CreateActivator>b__0(ControllerContext controllerContext)
at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass5_0.<CreateControllerFactory>g__CreateController|0(ControllerContext controllerContext)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeInnerFilterAsync>d__14.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeNextResourceFilter>d__22.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeFilterPipelineAsync>d__17.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeAsync>d__15.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.<Invoke>d__7.MoveNext()
I've started getting these errors. It was working perfectly on my previous server.
using System;
using Abp.Dependency;
using Abp.Domain.Repositories;
using Abp.Threading.BackgroundWorkers;
using EMS.IPs;
using System.Threading.Tasks.Dataflow;
using System.Threading.Tasks;
using System.Linq;
using EMS.Contacts;
using System.Collections.Concurrent;
using Abp.Domain.Uow;
using System.Collections.Generic;
using EMS.EmailValidation;
using Microsoft.AspNetCore.SignalR;
using KellermanSoftware.NetEmailValidation;
using System.Net;
using System.Collections;
using System.Threading;
using System.ComponentModel;
using System.Transactions;
namespace EMS.BackgroundWorkers
{
public class ContactValidationBackgroundWorker : BackgroundWorkerBase, ITransientDependency
{
private readonly IRepository<IP> _ipsRepository;
private readonly IRepository<Contact> _contactsRepository;
private readonly IUnitOfWorkManager _unitOfWorkManager;
private readonly IUnitOfWorkManager _unitOfWorkManager2;
private readonly IRepository<Contact> _contactRepository;
private BackgroundWorker bgworker = new BackgroundWorker();
ActionBlock<ValidationObject> workerBlock;
public ContactValidationBackgroundWorker(
IRepository<IP> ipsRepository,
IRepository<Contact> contactsRepository,
IUnitOfWorkManager unitOfWorkManager,
IUnitOfWorkManager unitOfWorkManager2,
IRepository<Contact> contactRepository)
{
_ipsRepository = ipsRepository;
_contactsRepository = contactsRepository;
_unitOfWorkManager = unitOfWorkManager;
_unitOfWorkManager2 = unitOfWorkManager2;
_contactRepository = contactRepository;
bgworker.DoWork += Worker;
}
public override void Start()
{
base.Start();
bgworker.RunWorkerAsync();
}
public override void Stop()
{
bgworker.DoWork -= Worker;
}
public void Worker(object sender, DoWorkEventArgs e)
{
using (var unitOfWork = _unitOfWorkManager.Begin(TransactionScopeOption.RequiresNew))
{
var contacts = _contactsRepository.GetAll().Where(x => !x.IsChecked);
if (!contacts.Any())
{
Logger.Debug("No contacts");
return;
}
workerBlock = new ActionBlock<ValidationObject>(
async (arg) => await Validate(arg),
new ExecutionDataflowBlockOptions
{
MaxDegreeOfParallelism = 5
});
foreach (var contact in contacts)
{
workerBlock.Post(new ValidationObject()
{
Contact = contact
});
}
unitOfWork.Complete();
}
Logger.Debug("End posting jobs to threads. Awaits results...");
workerBlock.Complete();
workerBlock.Completion.Wait();
}
public override void WaitToStop()
{
base.WaitToStop();
}
private async Task Validate(ValidationObject validationObject)
{
try
{
using (var contactUnitOfWork = _unitOfWorkManager2.Begin(TransactionScopeOption.RequiresNew))
{
Contact contact = validationObject.Contact;
contact.IsChecked = true;
await _contactRepository.UpdateAsync(contact);
await contactUnitOfWork.CompleteAsync();
}
} catch (Exception ex) {
Logger.Error(ex.ToString());
throw;
}
}
}
public class ValidationResult
{
public ValidationResult()
{
IsValid = false;
Message = "";
}
public string Message { get; set; }
public bool IsValid { get; set; }
}
public class ValidationObject
{
public Contact Contact { get; set; }
}
}
It works inside background worker; it worked before. Now it doesn't. Contact object is not null.
It seems to ask me to add unitOfWork parameter to Update method. Please help me figure this out.
ERROR 2017-12-26 12:02:34,768 [14 ] orkers.ContactValidationBackgroundWorker - System.ArgumentNullException: Value cannot be null.
Parameter name: unitOfWork
at Abp.EntityFrameworkCore.Uow.UnitOfWorkExtensions.GetDbContext[TDbContext](IActiveUnitOfWork unitOfWork, Nullable`1 multiTenancySide)
at Abp.EntityFrameworkCore.Repositories.EfCoreRepositoryBase`3.Update(TEntity entity)
at Castle.Proxies.Invocations.IRepository`2_Update_8.InvokeMethodOnTarget()
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Abp.Domain.Uow.UnitOfWorkInterceptor.PerformSyncUow(IInvocation invocation, UnitOfWorkOptions options)
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Castle.Proxies.IRepository`1Proxy_3.Update(Contact entity)
at EMS.BackgroundWorkers.ContactValidationBackgroundWorker.<Validate>d__21.MoveNext() in /Users/grinay/Projects/EMSBackend/src/EMS.Application/BackgroundWorkers/ContactValidationBackgroundWorker.cs:line 329
UPDATE1
ERROR 2017-12-27 05:31:34,500 [9 ] orkers.ContactValidationBackgroundWorker - System.ArgumentNullException: Value cannot be null.
Parameter name: unitOfWork
at Abp.EntityFrameworkCore.Uow.UnitOfWorkExtensions.GetDbContext[TDbContext](IActiveUnitOfWork unitOfWork, Nullable`1 multiTenancySide)
at Abp.EntityFrameworkCore.Repositories.EfCoreRepositoryBase`3.UpdateAsync(TEntity entity)
at Castle.Proxies.Invocations.IRepository`2_UpdateAsync_8.InvokeMethodOnTarget()
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Abp.Domain.Uow.UnitOfWorkInterceptor.PerformAsyncUow(IInvocation invocation, UnitOfWorkOptions options)
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Castle.Proxies.IRepository`1Proxy_3.UpdateAsync(Contact entity)
at EMS.BackgroundWorkers.ContactValidationBackgroundWorker.<>c__DisplayClass23_0.<<Validate>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Nito.AsyncEx.Synchronous.TaskExtensions.WaitAndUnwrapException(Task task)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Nito.AsyncEx.Synchronous.TaskExtensions.WaitAndUnwrapException(Task task)
at Nito.AsyncEx.AsyncContext.Run(Func`1 action)
at EMS.BackgroundWorkers.ContactValidationBackgroundWorker.Validate(ValidationObject validationObject)
You cannot use async methods with unitOfWork like that in background worker.
Make the changes in these 5 lines:
public void Worker(object sender, DoWorkEventArgs e)
{
// ...
workerBlock = new ActionBlock<ValidationObject>(
(arg) => Validate(arg), // This line #1
new ExecutionDataflowBlockOptions
{
MaxDegreeOfParallelism = 5
});
// ...
}
private void Validate(ValidationObject validationObject) // This line #2
{
try
{
using (var contactUnitOfWork = _unitOfWorkManager2.Begin(TransactionScopeOption.RequiresNew))
{
Contact contact = validationObject.Contact;
contact.IsChecked = true;
AsyncHelper.RunSync(async () => // This line #3
{ // This line #4
await _contactRepository.UpdateAsync(contact);
await contactUnitOfWork.CompleteAsync();
}); // This line #5
}
} catch (Exception ex) {
Logger.Error(ex.ToString());
throw;
}
}
i have a problem in a new web api controller when i try to use EF5 with Oracle.
My controller:
public class DeviceV1Controller : ApiController
{
private readonly IDevice _repository;
public DeviceV1Controller()
{
IDevice _repository = new EFDeviceRepository();
}
[Route("api/Device/{hashImei}/app/{nome}")]
public HttpResponseMessage Post(string hashImei, string nome, [FromBody] DeviceInfo deviceInfo)
{
_repository.Add(deviceInfo);
return Request.CreateResponse(HttpStatusCode.OK);
}
}
_repository is correctly bound in the constructor, but entering the Post api this variable become null and i get this error:
{
message: "An error has occurred."
exceptionMessage: "object reference not set to an instance of an object."
exceptionType: "System.NullReferenceException"
stackTrace: " in MpssApiRest.Controllers.DeviceV1Controller.Post(String hashImei, String nome, DeviceInfo deviceInfo) in c:\SVILUPPO\MpssApiRest\MpssApiRest\MpssApiRest\Controllers\DeviceV1Controller.cs:riga 28 in lambda_method(Closure , Object , Object[] ) in System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters) in System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments) in System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken) --- Fine traccia dello stack da posizione precedente dove è stata generata l'eccezione --- in System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) in System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) in System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext() --- Fine traccia dello stack da posizione precedente dove è stata generata l'eccezione --- in System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) in System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) in System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext() --- Fine traccia dello stack da posizione precedente dove è stata generata l'eccezione --- in System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) in System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) in System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__0.MoveNext()"
}
EFDeviceRepository concrete class is:
public class EFDeviceRepository : IDevice
{
private readonly EntityDevice ctx;
public EFDeviceRepository()
{
ctx = new EntityDevice();
}
public void Add(Models.V1.DeviceInfo deviceInfo)
{
EntityDevice ctx = new EntityDevice();
MPSS_APP_DEVICE device = new MPSS_APP_DEVICE();
device.HASHIMEI = deviceInfo.HashImei;
ctx.MPSS_APP_DEVICE.Add(device);
ctx.SaveChanges();
}
}
Thanks
EDIT: Sample Web Request (retrieved from the comments)
Ip Address: 192.168.1.129
Url: /myproject/api/device/123456/app/appname
JSON:
{
"applicazione" : "Gestione Interventi",
"hashImei" : "123123121323123121",
"modello" : "Nexus 5",
"pushNotificatioToken" : "oifjwfijowfjfoiwjrgfoirwj42rohfoifrj",
"sistemaOperativo" : "ANDROID", "versione" : "LOLLIPOP_MR1"
}
The reason why _repository is null in your Action is because you are not initializing it in your constructor. Instead you have declared and initialized a local variable of the same name in your constructor!
public class DeviceV1Controller : ApiController
{
private readonly IDevice _repository;
public DeviceV1Controller()
{
_repository = new EFDeviceRepository();
}
// ...
}