How to fix this exception type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in - linq

This is continuation to my question: [How to get name data of multiple json object list that will be posted to web api?
I was able to update my code but now I am getting an erexception on
if (db.Sales1.Any(sl => sl.ExtSerial != s.ExtSerial))
Exception goes: An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code
Additional information: The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accessed by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread safe.
Here is the code:
public HttpResponseMessage PostSales(List<Sales> Sales, [FromUri] string auth)
{
try
{
if (ModelState.IsValid)
{
if (auth == "KDI")
{
#region Stable but not multiline
//Int64 rs = db.Sales1.Where(sl => sl.Serial == Sales.Serial).Count();
//if (1 == rs)
//{
// return Request.CreateErrorResponse(HttpStatusCode.Conflict, " Duplicate Found!");
//}
//else
//{
// db.Sales1.Add(Sales);
// db.SaveChanges();
// return Request.CreateErrorResponse(HttpStatusCode.OK, "Added!");
//}
#endregion
Parallel.ForEach(Sales, s =>
{
if (db.Sales1.Any(sl => sl.ExtSerial != s.ExtSerial))
{
db.Sales1.Add(s);
db.SaveChanges();
}
else
{
return;
}
});
return Request.CreateErrorResponse(HttpStatusCode.OK, "Success!");
}
else
{
return Request.CreateResponse(HttpStatusCode.Unauthorized, "Unauthorized Access!");
}
}
else
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, "Something's wrong with the JSON model you sent me.");
}
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
}
}

Related

GraphQL.ExecutionError: Error trying to resolve

Summary:
My GraphQL ExecuteAsync returns a result that contains. According to the stackTrace provided below, the system cannot resolve my custom type remitsGeneralSearch. The remitsGeneralSearch resolver can return a type called ClaimPaymentOrCheckSearchGraphType which is a UnionGraphType.
StackTrace:
["GraphQL.ExecutionError: Error trying to resolve remitsGeneralSearch.\n ---> System.InvalidOperationException: Unexpected type: \n at GraphQL.Execution.ExecutionStrategy.BuildExecutionNode(ExecutionNode parent, IGraphType graphType, Field field, FieldType fieldDefinition, String[] path)\n at GraphQL.Execution.ExecutionStrategy.SetSubFieldNodes(ExecutionContext context, ObjectExecutionNode parent, Dictionary`2 fields)\n at GraphQL.Execution.ExecutionStrategy.SetSubFieldNodes(ExecutionContext context, ObjectExecutionNode parent)\n at GraphQL.Execution.ExecutionStrategy.ExecuteNodeAsync(ExecutionContext context, ExecutionNode node)\n --- End of inner exception stack trace ---"]4008305)
GraphQL Version: 2.4.0
FrameWork: .Net
OS: MacOS Catalina
Links Referenced: https://github.com/graphql-dotnet/graphql-dotnet/issues/964
CODE SNIPPETS:
RESOLVER:
FieldAsync<ClaimPaymentOrCheckSearchGraphType>(
"remitsGeneralSearch",
resolve: async context =>
{
var securityFilter = await GetUserRemitFilters(context);
var range = context.GetRange();
var sortFields = context.GetArgument<List<SortField>>("sort") ?? Enumerable.Empty<SortField>();
var whereClaimPayment = context.GetArgument<ClaimPaymentSearchFilter>("whereClaimPayment");
Connection<ClaimPaymentSearchRow> claimPaymentSearchRowResult;
try
{
using (LogContext.PushProperty("where", whereClaimPayment, true))
{
//claimPaymentSearchRowResult = await DMAQueryService.GetRemitReadersAsync(context);
var whereArguments = context.Arguments["whereClaimPayment"] as Dictionary<string, object>;
claimPaymentSearchRowResult = await DMAQueryService.GetRemitReadersAsync(
range,
whereClaimPayment,
whereArguments,
sortFields,
securityFilter,
context.CancellationToken
);
}
}
catch (Exception e)
{
_logger.LogInformation("Exception occurred {e}", e);
throw e;
}
var userRemitFilters = context.UserContext as Services.DMA.UserRemitFilters;
if (claimPaymentSearchRowResult.EdgeCount > 0)
{
return claimPaymentSearchRowResult;
}
var _whereCheckSearch = context.GetArgument<CheckSearchFilter>("whereCheck");
try
{
Connection<CheckSearchRow> checkSearchRowResult;
using (LogContext.PushProperty("whereCheck", _whereCheckSearch, true))
{
checkSearchRowResult = await DMAQueryService.GetCheckReadersAsync(context);
return checkSearchRowResult;
}
}
catch (Exception e)
{
throw e;
}
},arguments: queryArguments
);
}
catch (Exception e)
{
throw e;
}
Custom GraphType:
[Transient]
public class ClaimPaymentOrCheckSearchGraphType : UnionGraphType
{
private readonly ILogger<ClaimPaymentOrCheckSearchGraphType> _logger;
public ClaimPaymentOrCheckSearchGraphType(
ILogger<ClaimPaymentOrCheckSearchGraphType> logger,
ConnectionGraphType<ClaimPaymentSearchGraphType> claimPaymentSearchGraphType,
ConnectionGraphType<CheckSearchGraphType> checkSearchGraphType
)
{
_logger = logger;
Type<ConnectionGraphType<ClaimPaymentSearchGraphType>>();
Type<ConnectionGraphType<CheckSearchGraphType>>();
ResolveType = obj =>
{
try
{
if (obj is Connection<ClaimPaymentSearchRow>)
{
return claimPaymentSearchGraphType;
}
if (obj is Connection<CheckSearchRow>)
{
return checkSearchGraphType;
}
throw new ArgumentOutOfRangeException($"Could not resolve graph type for {obj.GetType().Name}");
}
catch (Exception e)
{
_logger.LogInformation("ClaimPaymentOrCheckSearchGraphType Exception {e}: ", e);
throw e;
}
};
}
}
Link to answer found here: https://github.com/graphql-dotnet/graphql-dotnet/issues/2674Try replacing this:
Type<ConnectionGraphType<ClaimPaymentSearchGraphType>>();
Type<ConnectionGraphType<CheckSearchGraphType>>();
with this:
AddPossibleType(claimPaymentSearchGraphType);
AddPossibleType(checkSearchGraphType);
I'm thinking that if you're registering these types as transients, then the copy that gets registered to the schema initialization code is a different copy that gets returned from ResolveType. Because of that, its fields' ResolvedType properties was never set, and so null is passed into BuildExecutionNode for the graphType instead of a resolved type.
If the ResolveType method could return a type rather than an instance, there wouldn't be an issue, but unfortunately that's not the way it works. Or you could register the type as a singleton.

Can I catch specific exceptions globally in a Razor Page (all handler methods) and include them in ModelState?

I'd like to allow all handler methods in a Razor Page to be wrapped by some sort of logic to handle specific exceptions that are more or less validation exceptions.
I've tried the following, but still get the developer exception page:
public override async Task OnPageHandlerExecutionAsync(PageHandlerExecutingContext context, PageHandlerExecutionDelegate next)
{
try
{
await next();
}
catch(NotImplementedException ex)
{
_logger.LogWarning(ex, ex.Message);
ModelState.AddModelError(string.Empty, "Oops... this isn't all done yet.");
context.Result = Page();
}
catch (DomainValidationException ex)
{
ModelState.Include(ex.Results);
context.Result = Page();
}
}
The exception does not appear to bubble up from the await next() call and is handled in aspnetcore somehow.
It turns out that the next returns a result that needs to be inspected to get the exception and return the result.
The final implementation looks something like this:
public override async Task OnPageHandlerExecutionAsync(PageHandlerExecutingContext context, PageHandlerExecutionDelegate next)
{
var result = await next();
if (result.Exception != null)
{
if (result.Exception is NotImplementedException nex)
{
result.ExceptionHandled = true;
_logger.LogWarning(nex, nex.Message);
ModelState.AddModelError(string.Empty, "Oops... this isn't all done yet.");
}
else if (result.Exception is DomainValidationException dex)
{
result.ExceptionHandled = true;
ModelState.Include(dex.Results);
}
if (result.ExceptionHandled)
{
result.Result = Page();
}
}
}

Configuring Skype for Business delegates using UCMA

I have been struggling to programatically add a delegate to a user (boss/admin scenario).
After running my test code in the boss sfb client the admin appears as a delegate however, in the admin's sfb client the boss does not appear under the section "people I manage calls for". I verified in the rtc frontend database that the delegation is configured, however the admin subscription record does not list the boss. Below is the code I used to achieve this.
Any ideas why the admin sfb client is not being notified of the new delegation?
Thanks,
Simon
1) add delegate-management
public void SendAddDelegate()
{
string body = string.Format($"<setDelegates xmlns=\"http://schemas.microsoft.com/2007/09/sip/delegate-management\" version=\"1\"><delegate uri=\"sip:admin#example.com\" action=\"add\"/></setDelegates>");
byte[] encBody = Encoding.UTF8.GetBytes(body);
RealTimeAddress rta = new RealTimeAddress("sip:boss#example.com");
System.Net.Mime.ContentType contentType = new System.Net.Mime.ContentType("application/msrtc-setdelegate+xml")
endpoint.InnerEndpoint.BeginSendMessage(MessageType.Service, rta, contentType, encBody, SendAddDelegateManagementMessageComplete, null);
}
private void SendAddDelegateManagementMessageComplete(IAsyncResult result)
{
try
{
SipResponseData srd = endpoint.InnerEndpoint.EndSendMessage(result);
logger.Debug($"srd.ResponseCode - {srd.ResponseCode}");
}
catch (Exception exc)
{
logger.Error("Exception SendMessageComplete with message - {0}", exc.Message);
}
}
2) Publish presence
public void PublishRoutingCategory(string delegateUri)
{
//routes not created here for sample brevity
routes.DelegateRingEnabled = true;
routes.Delegates.Add(delegateUri);
routes.SimultaneousRingEnabled = true;
routes.SimultaneousRing.Add(delegateUri);
routes.SkipPrimaryEnabled = true;
routes.ForwardAudioAppInvitesEnabled = true;
try
{
userEndpoint.LocalOwnerPresence.BeginPublishPresence(new PresenceCategory[] { routes }, PublishComplete, null);
}
catch (Exception exc)
{
logger.Error("Unknown error - {0}", exc.Message);
}
}
private void PublishComplete(IAsyncResult result)
{
try
{
endpoint.LocalOwnerPresence.EndPublishPresence(result);
}
catch (Exception exc)
{
logger.Error("Error Publish Complete- {0}", exc.Message);
}
}

how to return an exception from async in asp.net webapi

I have a WebAPI2 mvc app where I'm doing Get/Post to another api. My code looks like below
public Task<SomeEntity> AddAsync(SomeEntity someEntity)
{
try
{
var response = apiService.PostItem(url, someEntity);
if (response == null || response!="Successful")
{
throw new InvalidOperationException(response);
}
}
catch (Exception ex)
{
_logger.Error("Error " + ex.Message);
// how to return this error or exception;
}
return Task.FromResult(someEntity);
}
If the call to the internal api return an exception string then I need to forward it from this method call. Any ideas how can I do it? thanks
You can use IHttpActionResult or HttpResponseMessage as your return type and return proper HTTP-Status codes. In case of exception you can return [if you return IHttpActionResult ]
public IHttpActionResult Error()
{
var error = new HttpError();
return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.BadRequest, error));
}
or as in your example, throw HttpResponseException with appropriate status code.
public Product GetProduct(int id)
{
Product item = repository.Get(id);
if (item == null)
{
var message = string.Format("Product with id = {0} not found", id);
throw new HttpResponseException(
Request.CreateErrorResponse(HttpStatusCode.NotFound, message));
}
else
{
return item;
}
}

How do you handle an exception with ASP.net MVC's AsyncController?

I've got this...
public void FooAsync()
{
AsyncManager.OutstandingOperations.Increment();
Task.Factory.StartNew(() =>
{
try
{
doSomething.Start();
}
catch (Exception e)
{
AsyncManager.Parameters["exc"] = e;
}
finally
{
AsyncManager.OutstandingOperations.Decrement();
}
});
}
public ActionResult FooCompleted(Exception exc)
{
if (exc != null)
{
throw exc;
}
return View();
}
Is there a better way of passing an exception back to ASP.net?
Cheers, Ian.
Task will catch the exceptions for you. If you call task.Wait(), it will wrap any caught exceptions in an AggregateException and throw it.
[HandleError]
public void FooAsync()
{
AsyncManager.OutstandingOperations.Increment();
AsyncManager.Parameters["task"] = Task.Factory.StartNew(() =>
{
try
{
DoSomething();
}
// no "catch" block. "Task" takes care of this for us.
finally
{
AsyncManager.OutstandingOperations.Decrement();
}
});
}
public ActionResult FooCompleted(Task task)
{
// Exception will be re-thrown here...
task.Wait();
return View();
}
Simply adding a [HandleError] attribute isn't good enough. Since the exception occurs in a different thread, we have to get the exception back to the ASP.NET thread in order to do anything with it. Only after we have the exception thrown from the right place will the [HandleError] attribute be able to do its job.
Try putting an attribute like this in FooAsync action:
[HandleError (ExceptionType = typeof (MyExceptionType) View = "Exceptions/MyViewException")]
This way you can create a view to display the detailed error to the user.

Resources