Error when using GetAll (AsyncCrudAppService) and apply sorting - asp.net-core

I've built an application service based on the AsyncCrudAppService class, like this:
public class ServiceTemplateAppService : AsyncCrudAppService<ServiceTemplate, ServiceTemplateDto, int, PagedAndSortedResultRequestDto, CreateServiceTemplateDto, UpdateServiceTemplateDto>, IServiceTemplateAppService
Everything works as intended, but once in a while I get an error when calling the GetAll method and passing in a sorting parameter, like this:
api/services/app/CostCenter/GetAll?SkipCount=0&MaxResultCount=10&Sorting=displayName%20asc
I have overridden the CreateFilteredQuery method and it now looks like this because I want to get some child entities.
protected override IQueryable<ServiceTemplate> CreateFilteredQuery(PagedAndSortedResultRequestDto input)
{
return Repository.GetAll()
.Include(x => x.ServiceTemplateRole)
.ThenInclude(y => y.Role)
.Include(x => x.ServiceTemplateImage)
.Include(x => x.ServiceTemplateCategory);
}
The error message that I get is this one:
INFO 2018-11-16 13:45:02,101 [21 ] ore.Mvc.Internal.ControllerActionInvoker - Route matched with {area = "app", action = "GetAll", controller = "ServiceTemplate"}. Executing action dsim.Services.ServiceTemplateAppService.GetAll (dsim.Application)
INFO 2018-11-16 13:45:02,104 [21 ] ore.Mvc.Internal.ControllerActionInvoker - Executing action method dsim.Services.ServiceTemplateAppService.GetAll (dsim.Application) with arguments (Abp.Application.Services.Dto.PagedAndSortedResultRequestDto) - Validation state: Valid
ERROR 2018-11-16 13:45:02,189 [24 ] Mvc.ExceptionHandling.AbpExceptionFilter - Could not load type 'System.ComponentModel.DataAnnotations.BindableTypeAttribute' from assembly 'System.ComponentModel.DataAnnotations, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.
System.TypeLoadException: Could not load type 'System.ComponentModel.DataAnnotations.BindableTypeAttribute' from assembly 'System.ComponentModel.DataAnnotations, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.
at System.ModuleHandle.ResolveType(RuntimeModule module, Int32 typeToken, IntPtr* typeInstArgs, Int32 typeInstCount, IntPtr* methodInstArgs, Int32 methodInstCount, ObjectHandleOnStack type)
at System.ModuleHandle.ResolveTypeHandleInternal(RuntimeModule module, Int32 typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
at System.Reflection.RuntimeModule.ResolveType(Int32 metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
at System.Reflection.CustomAttribute.FilterCustomAttributeRecord(CustomAttributeRecord caRecord, MetadataImport scope, Assembly& lastAptcaOkAssembly, RuntimeModule decoratedModule, MetadataToken decoratedToken, RuntimeType attributeFilterType, Boolean mustBeInheritable, Object[] attributes, IList derivedAttributes, RuntimeType& attributeType, IRuntimeMethodInfo& ctor, Boolean& ctorHasParameters, Boolean& isVarArg)
at System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeModule decoratedModule, Int32 decoratedMetadataToken, Int32 pcaCount, RuntimeType attributeFilterType, Boolean mustBeInheritable, IList derivedAttributes)
at System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeType type, RuntimeType caType, Boolean inherit)
at System.Linq.Dynamic.Core.CustomTypeProviders.AbstractDynamicLinqCustomTypeProvider.<>c.<FindTypesMarkedWithDynamicLinqTypeAttribute>b__0_1(Type x)
at System.Linq.Enumerable.WhereEnumerableIterator`1.MoveNext()
at System.Collections.Generic.HashSet`1.UnionWith(IEnumerable`1 other)
at System.Collections.Generic.HashSet`1..ctor(IEnumerable`1 collection, IEqualityComparer`1 comparer)
at System.Linq.Dynamic.Core.CustomTypeProviders.DefaultDynamicLinqCustomTypeProvider.GetCustomTypes()
at System.Linq.Dynamic.Core.Parser.KeywordsHelper..ctor(ParsingConfig config)
at System.Linq.Dynamic.Core.Parser.ExpressionParser..ctor(ParameterExpression[] parameters, String expression, Object[] values, ParsingConfig parsingConfig)
at System.Linq.Dynamic.Core.DynamicQueryableExtensions.OrderBy(IQueryable source, ParsingConfig config, String ordering, Object[] args)
at System.Linq.Dynamic.Core.DynamicQueryableExtensions.OrderBy[TSource](IQueryable`1 source, ParsingConfig config, String ordering, Object[] args)
at System.Linq.Dynamic.Core.DynamicQueryableExtensions.OrderBy[TSource](IQueryable`1 source, String ordering, Object[] args)
at Castle.Proxies.Invocations.CrudAppServiceBase`6_ApplySorting_3.InvokeMethodOnTarget()
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Abp.Domain.Uow.UnitOfWorkInterceptor.PerformSyncUow(IInvocation invocation, UnitOfWorkOptions options)
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Castle.Proxies.ServiceTemplateAppServiceProxy.ApplySorting(IQueryable`1 query, PagedAndSortedResultRequestDto input)
at Abp.Application.Services.AsyncCrudAppService`8.GetAll(TGetAllInput input)
at Abp.Threading.InternalAsyncHelper.AwaitTaskWithPostActionAndFinallyAndGetResult[T](Task`1 actualReturnValue, Func`1 postAction, Action`1 finalAction)
at lambda_method(Closure , Object )
at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync()
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync()
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextExceptionFilterAsync()
I've tried to figure out what could cause the problem and adding the assembly that the exceptions tells me, but no progress. The strange thing is that this sometimes work, so my guess is that is has something to do with the actual data in the DB, but hey?! I don't know...

GetAll Method From AsyncCrudAppService calls ApplySorting Method, you can override it and there sort as you want.
protected override IQueryable<YourEntity> ApplySorting(IQueryable<YourEntity> query, PagedAndSortedResultRequestDto input)
{
if (input.Sorting.IsNullOrEmpty())
{
input.Sorting = "yourColumn asc";
}
return base.ApplySorting(query, input);
}
If you want to crate another GetAll Method here is an example:
public Task<PagedResultDto<PaisDto>> GetAllFiltered(PagedAndSortedResultRequestDto input, string filter)
{
var paisList = new List<Pais>();
var query = Repository.GetAll();
query = ApplySorting(query, input);
if (filter != null && filter != string.Empty)
{
paisList = query
.Where(x => x.Identificador.StartsWith(filter) || x.Nombre.StartsWith(filter))
.Skip(input.SkipCount)
.Take(input.MaxResultCount).ToList();
var result = new PagedResultDto<PaisDto>(query.Count(), ObjectMapper.Map<List<PaisDto>>(paisList));
return Task.FromResult(result);
}
else
{
paisList = query
.Skip(input.SkipCount)
.Take(input.MaxResultCount).ToList()
.ToList();
var result = new PagedResultDto<PaisDto>(query.Count(), ObjectMapper.Map<List<PaisDto>>(paisList));
return Task.FromResult(result);
}
}
query = ApplySorting(query, input); in this line you can call base method base.ApplySorting(query, input);

Related

Return inline dynamic SVG from MVC Controller

I'm building a method on my Controller to generate an SVG QR Code (QRCoder) and I'm trying to inline the resultant SVG from the controller into the View using a Method on the Controller.
When I attempt to view the method directly, I see the SVG XML coming back successfully, but it's getting an exception. I'm not quite sure what I need to make my controller return so that I can do this in my view.
<img src="~/Redirect/QRCode/{code}/svg"/>
the equivalent PNG version works perfectly.
<img src="~/Redirect/QRCode/{code}/png"/>
[Route("[controller]/QRCode/{code}/{format?}")]
public IActionResult QRCodeImage(string code, BarcodeService.Format format = BarcodeService.Format.Png)
{
//Database call to get the real Uri...
var uri = "https://github.com/paulfarry/";
switch (format)
{
case BarcodeService.Format.Svg:
{
var data = barcodeService.GenerateQRCodeSvg(uri);
return File(data, "image/svg+xml; charset=utf-8");
}
case BarcodeService.Format.Png:
default:
{
var data = barcodeService.GenerateQRCode(uri);
return File(data, "image/png");
}
}
}
When I view the page directly I would have expected to see the SVG rendered but I get this exception information plus the SVG data.
https://localhost:5001/Redirect/QRCode/a/svg
An unhandled exception occurred while processing the request.
FileNotFoundException: Could not find file:
<svg version="1.1" baseProfile="full" shape-rendering="crispEdges" width="740" height="740" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><rect x="0" y="0" width="740" height="740" fill="#FFFFFF" />
<!--Remaining SVG data is here-->
</svg>
Microsoft.AspNetCore.Mvc.Infrastructure.VirtualFileResultExecutor.ExecuteAsync(ActionContext context, VirtualFileResult result)
Microsoft.AspNetCore.Mvc.VirtualFileResult.ExecuteResultAsync(ActionContext context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultAsync(IActionResult result)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext<TFilter, TFilterAsync>(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeNextResultFilterAsync<TFilter, TFilterAsync>()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext<TFilter, TFilterAsync>(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
Turns out to be very simple to solve.
Just needed to return Content instead of File
But took a lot of experimenting.
case BarcodeService.Format.Svg:
{
var data = barcodeService.GenerateQRCodeSvg(uri);
return Content(data, "image/svg+xml);
}

MVC RenderAction from View Error after model error

I am experiencing a bizarre problem with RenderAction. As my view model is very complex I will try to streamline the process in broad strokes, as follows:
Browser requests controller action.
Action populates complex view model and passes to a view
View contains a renderAction to build child/partial view. (I
uses renderAction instead of a partialView at this point
due to the complexity of the model the partial view needs.)
This proceeds as necessary and the view is shown in the browser without error.
If I create a model error after posting back some bad data and then return the same model to the same view, an error is thrown when the renderAction is called. When debugging, the controller is accessed, but the action is skipped and the app goes directly to disposing at the bottom of the controller.
It would seem that the only difference is that main controller action (not the partial) that populates the big view model is at first reached via a get and then fails when reached via a post. I played around for hours with the model - even recreated the model from scratch - so it can't be related to the model.
Here is the stack trace:
at System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride)
at System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage)
at System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm)
at System.Web.HttpServerUtilityWrapper.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm)
at System.Web.Mvc.Html.ChildActionExtensions.ActionHelper(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues, TextWriter textWriter)
at System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper htmlHelper, String actionName, Object routeValues)
at ASP._Page_Views_Pricelist__drawProductPricelistProductRow_cshtml.Execute() in c:\Users\Administrator\Documents\ProofPix_TFS\ProofPix\ProofPixAdmin\Views\Pricelist\_drawProductPricelistProductRow.cshtml:line 35
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
at System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance)
at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer)
at System.Web.Mvc.HtmlHelper.RenderPartialInternal(String partialViewName, ViewDataDictionary viewData, Object model, TextWriter writer, ViewEngineCollection viewEngineCollection)
at System.Web.Mvc.Html.RenderPartialExtensions.RenderPartial(HtmlHelper htmlHelper, String partialViewName, Object model)
at ASP._Page_Views_Pricelist_edit_cshtml.Execute() in c:\Users\Administrator\Documents\ProofPix_TFS\ProofPix\ProofPixAdmin\Views\Pricelist\Edit.cshtml:line 121
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
at System.Web.WebPages.StartPage.RunPage()
at System.Web.WebPages.StartPage.ExecutePageHierarchy()
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
at System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance)
at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer)
at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation)
Here is the renderAction:
Html.RenderAction("_pricelistProductOptions", new { id = Model.Product.ProductId, ShowHtml = false });
You're help is greatly appreciated. BTW (kinda a newb)!
EDIT (added action)
// POST: /Pricelist/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(adminEditPricelistVM adminEditPricelistVM)
{
if (ModelState.IsValid)
{
//Code removed for simplicity
return RedirectToAction("Edit", new { id = pricelist.PricelistId });
}
int vendorId = (int)adminEditPricelistVM.VendorId;
Vendor vendor = (from b in db.Vendors where b.VendorId == vendorId select b).SingleOrDefault();
adminEditPricelistVM.ProductCategories = (from a in db.ProductCategories
from b in db.VendorProductCategory
where b.VendorId == vendorId && a.ProductCategoryId == b.ProductCategoryId
select a).OrderBy(o => o.SortOrder).ToList();
List<Product> products = (from a in db.Products where a.DiscontinuedDate == null && a.VendorId == 1 select a).OrderBy(o => o.SortOrder).ToList();
//repopulate ProductCategory and Vendor nav properties in the Formula items as these are no longer populated after post
foreach(PricingFormula pf in adminEditPricelistVM.PricingFormulas){
pf.ProductCategory = (from a in adminEditPricelistVM.ProductCategories where a.ProductCategoryId == pf.ProductCategoryId select a).SingleOrDefault();
pf.Vendor = vendor;
}
adminEditPricelistVM.Pricelist.PricingFormulas = new List<PricingFormula>();
adminEditPricelistVM.Pricelist.PricingFormulas.AddRange(adminEditPricelistVM.PricingFormulas);
List<PricelistProduct> thisFilteredPP = (from a in adminEditPricelistVM.Pricelist.PricelistProducts where a.ProductId > 0 select a).ToList();
List<PricelistProductOption> thisOptionsToDelete = new List<PricelistProductOption>();
List<PricelistProductOptionsDetail> thisOptionDetailsToDelete = new List<PricelistProductOptionsDetail>();
//filter pricelistProducts so only selected options remain in list
foreach (PricelistProduct pp in thisFilteredPP)
{
pp.PricelistId = adminEditPricelistVM.Pricelist.PricelistId;
var x = pp.ProductId;
foreach (PricelistProductOption ppo in pp.PricelistProductOptions)
{
//repopulate PricelistProduct object
ppo.PricelistProduct = pp;
ppo.PricelistProductId = pp.PricelistProductId;
int numPODs = (from a in ppo.PricelistProductOptionsDetails where a.ProductOptionsDetailId > 0 select a).Count();
if (numPODs == 0)
{
thisOptionsToDelete.Add(ppo);
}
else
{
foreach (PricelistProductOptionsDetail ppod in ppo.PricelistProductOptionsDetails)
{
//repopulate PricelistProductOption object
ppod.PricelistProductOption = ppo;
ppod.PricelistProductOptionsId = ppo.PricelistProductOptionId;
if (ppod.ProductOptionsDetailId == 0)
{
thisOptionDetailsToDelete.Add(ppod);
}
else //POD is selected but if it is the default option and it is the only option and it is priced at 0.00, then we will remove it to as it is the default setting.
{
if (ppod.Price == 0 && numPODs == 1)
{
ProductOptionsDetail prodOpDet = (from c in db.ProductOptionsDetails where c.ProductOptionsDetailId == ppod.ProductOptionsDetailId select c).SingleOrDefault();
if (prodOpDet.IsDefault == true)
{
thisOptionsToDelete.Add(ppo);
}
}
}
}
foreach (PricelistProductOptionsDetail dppod in thisOptionDetailsToDelete)
{
ppo.PricelistProductOptionsDetails.Remove(dppod);
}
thisOptionDetailsToDelete.Clear();
}
}
foreach (PricelistProductOption dppo in thisOptionsToDelete)
{
pp.PricelistProductOptions.Remove(dppo);
}
thisOptionsToDelete.Clear();
}
adminEditPricelistVM.Pricelist.PricelistProducts = new List<PricelistProduct>();
adminEditPricelistVM.Pricelist.PricelistProducts.AddRange(thisFilteredPP);
adminEditPricelistVM.PPPVMs =
(from product in products
join pricelistProduct in adminEditPricelistVM.Pricelist.PricelistProducts on product.ProductId equals pricelistProduct.ProductId into gj
from subpricelistProduct in gj.DefaultIfEmpty()
select new adminEditProductsPricelistProductsVM()
{
CategoryId = (int)product.ProductCategoryId,
Product = product,
PricelistProduct = subpricelistProduct
}).ToList();
//repopulate PricelistProducts.Product and PricelistProducts.ProductCategory in Pricelist
foreach (PricelistProduct pp in adminEditPricelistVM.Pricelist.PricelistProducts)
{
pp.Product = (from p in products where p.ProductId == pp.ProductId select p).SingleOrDefault();
pp.ProductCategory = (from a in adminEditPricelistVM.ProductCategories where a.ProductCategoryId == pp.ProductCategoryId select a).SingleOrDefault();
pp.Pricelist = adminEditPricelistVM.Pricelist;
}
ViewBag.PricingFormulaRoundingTypes = (from c in db.PricingFormulaRoundingTypes select c).ToList();
var errors = ModelState.Select(x => x.Value.Errors).ToList();
return View(adminEditPricelistVM);
}
This answer is just a hunge, as the actual error isn't showing, just the stacktrace.
//repopulate PricelistProducts.Product and PricelistProducts.ProductCategory in Pricelist
foreach (PricelistProduct pp in adminEditPricelistVM.Pricelist.PricelistProducts)
{
pp.Product = (from p in products where p.ProductId == pp.ProductId select p).SingleOrDefault();
There are probably more products in your PricelistProducts, with a ProductId that doesn't match with any of the products in your products list, resulting in pp.Product being set to null.
When rendering your action for each object in the Model.PricelistProducts with
html.RenderAction("_pricelistProductOptions", new { id = Model.Product.ProductId, ShowHtml = false });
it will (probably) throw a System.NullReferenceException: Object reference not set to an instance of an object. as you can't call Model.Product.ProductId, since Model.Product is null.
You are using Razor engine there (*.cshtml files)? In that case you have to use:
#Html.Action("actionName", "controllerName", new { id="myId" })
and, it seems you put name of the view there "_pricelistProductOptions", instead of action. I doubt that you have: public ActionResult _pricelistProductOptions(....) right?

How to extend a WCF Data Services context class on clientside?

I'm using the following code to extend my Service-Context with a FullName on clientside:
public partial class Customer {
public string FullName
{
get
{
return string.Concat(LastName, (FirstName == "" ? "" : ", "), FirstName);
}
}
}
That works fine, until it comes to the point where I need to Add a new Object to the Context with the AddOBject Method. It throws an Exception. When I remove the FullName extension th AddObject method saves the new Object to the database.
What is the best way to extend my Context and still make it Update- and Insertable?
Edit: The DataServiceRequest Exception:
System.Data.Services.Client.DataServiceRequestException was not handled by user code.
HResult=-2146233079
Message=Fehler beim Verarbeiten dieser Anforderung.
Source=Microsoft.Data.Services.Client.WindowsStore
StackTrace:
at System.Data.Services.Client.SaveResult.HandleResponse()
at System.Data.Services.Client.BaseSaveResult.EndRequest()
at System.Data.Services.Client.DataServiceContext.EndSaveChanges(IAsyncResult asyncResult)
at Pointsale.Client.Service.PointsaleEntities.<SaveChanges>b__0(IAsyncResult asResult) in c:\Users\Jan\Desktop\pointsale_worksapce\pointsale.client\Helper\TenantHelper.cs:line 98
at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)
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="de-DE">Error occurred while processing this request.</m:message></m:error>
StatusCode=400
InnerException:
And the SaveChanges method overide to get it async:
public async Task<DataServiceResponse> SaveChanges()
{
var queryTask = Task.Factory.FromAsync(this.BeginSaveChanges(null, null), asResult =>
{
var result = this.EndSaveChanges(asResult);
return result;
});
return await queryTask;
}
On EndSaveChanges the error occures.

How to return IEnumerable <int> in WebAPI (applying filters manually)

I want to return all IDs of my process (Processo class) (apply filters and order before), something like this:
Url: api/processos/getIds?&$filter=(Id eq 1)
public IEnumerable<int> getIds(ODataQueryOptions opts)
{
var results = Repositorio.Query<Processo>();
results = opts.ApplyTo(results) as IQueryable<Processo>;
return results.Select(p => p.Id).ToArray();
}
Error
Full image in: http://i.stack.imgur.com/gzJ7n.jpg
Exception
System.ArgumentException was unhandled by user code
HResult=-2147024809
Message=Cannot apply ODataQueryOptions of 'System.Int32' to IQueryable of 'CreditoImobiliarioBB.Model.Processo'.
Parameter name: query
Source=System.Web.Http.OData
ParamName=query
StackTrace:
at System.Web.Http.OData.Query.ODataQueryOptions`1.ValidateQuery(IQueryable query)
at System.Web.Http.OData.Query.ODataQueryOptions`1.ApplyTo(IQueryable query)
at CreditoImobiliarioBB.Web.Api.processosController.getIds(ODataQueryOptions opts) in w:\Clients\creditoimobiliariobb.com.br\src\CreditoImobiliarioBB\CreditoImobiliarioBB.Web\Api\processosController.cs:line 39
at lambda_method(Closure , Object , Object[] )
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass13.<GetExecutor>b__c(Object instance, Object[] methodParameters)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.<>c__DisplayClass5.<ExecuteAsync>b__4()
at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)
InnerException:
You need to give ODataQueryOptions a type argument, otherwise it will use the action's return type to build the options. Here is the fixed code:
public IEnumerable<int> getIds(ODataQueryOptions<Processo> opts)
{
var results = Repositorio.Query<Processo>();
results = opts.ApplyTo(results) as IQueryable<Processo>;
return results.Select(p => p.Id).ToArray();
}

IndexOutOfRangeException Deep in the bowels of NHibernate

I have the following mappings:
public class SecurityMap : ClassMap<Security>
{
public SecurityMap()
{
Table("Security");
CompositeId().KeyProperty(k => k.Id, "SecurityId").KeyProperty(k => k.EndDate);
Map(x => x.LastUpdateUser);
References(x => x.Company).Columns("CompanyId", "EndDate");
References(x => x.PrimaryListing).Columns("PrimaryListingId", "EndDate");
}
}
public class ListingMap : ClassMap<Listing>
{
public ListingMap()
{
Table("Listing");
CompositeId().KeyProperty(k => k.Id, "ListingID").KeyProperty(k => k.EndDate);
References(x => x.Security).Columns("SecurityId","EndDate");
}
}
public class CompanyMap : ClassMap<Company>
{
public CompanyMap()
{
Table("Company");
CompositeId().KeyProperty(k => k.Id, "CompanyID").KeyProperty(k => k.EndDate);
HasMany(x => x.Securities).KeyColumns.Add("CompanyId", "EndDate");
}
}
When I attempt to run this test:
[Test]
public void can_update_a_security()
{
var repo = IoC.Resolve<ISecurityRepository>();
int someSecurity = 1;
using (var work = IoC.Resolve<IUnitOfWorkManager>().Current)
{
Security security = repo.Get(someSecurity);
security.ShouldNotBeNull();
security.LastUpdateUser = "Dirk Diggler" + DateTime.Now.Ticks;
repo.Save(security);
work.Commit();
}
}
I get the following error deep in the bowels of NHibernate:
Execute
System.IndexOutOfRangeException: Invalid index 6 for this
SqlParameterCollection with Count=6.
at System.Data.SqlClient.SqlParameterCollection.RangeCheck(Int32
index)
at System.Data.SqlClient.SqlParameterCollection.GetParameter(Int32
index)
at System.Data.Common.DbParameterCollection.System.Collections.IList.get_Item(Int32
index)
s:\NHibernate\NHibernate\src\NHibernate\Type\DateTimeType.cs(65,0):
at
NHibernate.Type.DateTimeType.Set(IDbCommand
st, Object value, Int32 index)
s:\NHibernate\NHibernate\src\NHibernate\Type\NullableType.cs(180,0):
at
NHibernate.Type.NullableType.NullSafeSet(IDbCommand
cmd, Object value, Int32 index)
s:\NHibernate\NHibernate\src\NHibernate\Type\NullableType.cs(139,0):
at
NHibernate.Type.NullableType.NullSafeSet(IDbCommand
st, Object value, Int32 index,
ISessionImplementor session)
s:\NHibernate\NHibernate\src\NHibernate\Type\ComponentType.cs(213,0):
at
NHibernate.Type.ComponentType.NullSafeSet(IDbCommand
st, Object value, Int32 begin,
ISessionImplementor session)
s:\NHibernate\NHibernate\src\NHibernate\Persister\Entity\AbstractEntityPersister.cs(2393,0):
at
NHibernate.Persister.Entity.AbstractEntityPersister.Dehydrate(Object
id, Object[] fields, Object rowId,
Boolean[] includeProperty, Boolean[][]
includeColumns, Int32 table,
IDbCommand statement,
ISessionImplementor session, Int32
index)
s:\NHibernate\NHibernate\src\NHibernate\Persister\Entity\AbstractEntityPersister.cs(2754,0):
at
NHibernate.Persister.Entity.AbstractEntityPersister.Update(Object
id, Object[] fields, Object[]
oldFields, Object rowId, Boolean[]
includeProperty, Int32 j, Object
oldVersion, Object obj, SqlCommandInfo
sql, ISessionImplementor session)
s:\NHibernate\NHibernate\src\NHibernate\Persister\Entity\AbstractEntityPersister.cs(2666,0):
at
NHibernate.Persister.Entity.AbstractEntityPersister.UpdateOrInsert(Object
id, Object[] fields, Object[]
oldFields, Object rowId, Boolean[]
includeProperty, Int32 j, Object
oldVersion, Object obj, SqlCommandInfo
sql, ISessionImplementor session)
s:\NHibernate\NHibernate\src\NHibernate\Persister\Entity\AbstractEntityPersister.cs(2940,0):
at
NHibernate.Persister.Entity.AbstractEntityPersister.Update(Object
id, Object[] fields, Int32[]
dirtyFields, Boolean
hasDirtyCollection, Object[]
oldFields, Object oldVersion, Object
obj, Object rowId, ISessionImplementor
session)
s:\NHibernate\NHibernate\src\NHibernate\Action\EntityUpdateAction.cs(78,0):
at
NHibernate.Action.EntityUpdateAction.Execute()
s:\NHibernate\NHibernate\src\NHibernate\Engine\ActionQueue.cs(130,0):
at
NHibernate.Engine.ActionQueue.Execute(IExecutable
executable)
s:\NHibernate\NHibernate\src\NHibernate\Engine\ActionQueue.cs(113,0):
at
NHibernate.Engine.ActionQueue.ExecuteActions(IList
list)
s:\NHibernate\NHibernate\src\NHibernate\Engine\ActionQueue.cs(147,0):
at
NHibernate.Engine.ActionQueue.ExecuteActions()
s:\NHibernate\NHibernate\src\NHibernate\Event\Default\AbstractFlushingEventListener.cs(241,0):
at
NHibernate.Event.Default.AbstractFlushingEventListener.PerformExecutions(IEventSource
session)
s:\NHibernate\NHibernate\src\NHibernate\Event\Default\DefaultFlushEventListener.cs(19,0):
at
NHibernate.Event.Default.DefaultFlushEventListener.OnFlush(FlushEvent
event)
s:\NHibernate\NHibernate\src\NHibernate\Impl\SessionImpl.cs(1478,0):
at NHibernate.Impl.SessionImpl.Flush()
s:\NHibernate\NHibernate\src\NHibernate\Transaction\AdoTransaction.cs(187,0):
at
NHibernate.Transaction.AdoTransaction.Commit()
at lambda_method(ExecutionScope , ITransaction )
Now the interesting thing is if I comment out the reference to Company or PrimaryListing in the SecurityMap, I don't get the error. It doesn't seem to matter which I comment out. The error only happens when I have both.
When the update actually goes through NHProf shows me this update:
UPDATE Security
SET LastUpdateUser = '2010-02-19T08:09:24.00' /* #p0 */,
CompanyId = 54199 /* #p1 */,
EndDate = '9999-12-31T00:00:00.00' /* #p2 */
WHERE SecurityId = 1 /* #p3 */
AND EndDate = '9999-12-31T00:00:00.00' /* #p4 */
I am not sure why it is updating CompanyId and EndDate, but I suspect it is related.
Any one have ideas? Work arounds would be greatly appreciated.
Yes its a common problem, you are using the Column "EndDate" twice in your mapping definition (for both Company and PrimaryListing) and that is not allowed. One of them has to go, or have an additional EndDate column (one for each association)
check this too
nHibernate 2.0 - mapping a composite-id *and* many-to-one relationship causes "invalid index" error
and
http://devlicio.us/blogs/derik_whittaker/archive/2009/03/19/nhibernate-and-invalid-index-n-for-this-sqlparametercollection-with-count-n-error.aspx