MVC RenderAction from View Error after model error - asp.net-mvc-4

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?

Related

Sitefinity feather multiple content items selectors exception in designer

I am using the sf-list-selector in my designer as shown below. I see my products list and I can select and sort.
<sf-list-selector sf-dynamic-items-selector sf-provider="properties.ProductProviderName.PropertyValue" sf-item-type="properties.ProductType.PropertyValue" sf-multiselect="true" sf-sortable="true" sf-master="true" sf-selected-ids="properties.ProductIds.PropertyValue" />
However I am getting an exception in the log file when I press save in the designer:
Requested URL :
https://localhost/Sitefinity/Services/Pages/ControlPropertyService.svc/batch/fc82280c-3055-6fae-9336-ff0000e88380/?pageId=230b270c-3055-6fae-9336-ff0000e88380&mediaType=0&propertyLocalization=0
Inner Exception --------------- Type : System.Xml.XmlException,
System.Xml, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089 Message : End element 'PropertyValue'
from namespace '' expected. Found element 'item' from namespace ''.
Source : System.Runtime.Serialization Help link : LineNumber : 0
LinePosition : 0 SourceUri : Data :
System.Collections.ListDictionaryInternal TargetSite : Void
ThrowXmlException(System.Xml.XmlDictionaryReader, System.String,
System.String, System.String, System.String) HResult : -2146232000
Stack Trace : at
System.Xml.XmlExceptionHelper.ThrowXmlException(XmlDictionaryReader
reader, String res, String arg1, String arg2, String arg3)
at System.Xml.XmlExceptionHelper.ThrowEndElementExpected(XmlDictionaryReader
reader, String localName, String ns)
at System.Xml.XmlBaseReader.ReadEndElement()
at System.Xml.XmlBaseReader.ReadElementContentAsString()
at ReadWcfControlPropertyFromJson(XmlReaderDelegator , XmlObjectSerializerReadContextComplexJson , XmlDictionaryString ,
XmlDictionaryString[] )
at System.Runtime.Serialization.Json.JsonClassDataContract.ReadJsonValueCore(XmlReaderDelegator
jsonReader, XmlObjectSerializerReadContextComplexJson context)
at System.Runtime.Serialization.Json.XmlObjectSerializerReadContextComplexJson.ReadDataContractValue(DataContract
dataContract, XmlReaderDelegator reader)
at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator
reader, String name, String ns, Type declaredType, DataContract&
dataContract)
at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserialize(XmlReaderDelegator
xmlReader, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle,
String name, String ns)
at ReadArrayOfWcfControlPropertyFromJson(XmlReaderDelegator , XmlObjectSerializerReadContextComplexJson , XmlDictionaryString ,
XmlDictionaryString , CollectionDataContract )
at System.Runtime.Serialization.Json.JsonCollectionDataContract.ReadJsonValueCore(XmlReaderDelegator
jsonReader, XmlObjectSerializerReadContextComplexJson context)
at System.Runtime.Serialization.Json.XmlObjectSerializerReadContextComplexJson.ReadDataContractValue(DataContract
dataContract, XmlReaderDelegator reader)
at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator
reader, String name, String ns, Type declaredType, DataContract&
dataContract)
at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserialize(XmlReaderDelegator
xmlReader, Type declaredType, DataContract dataContract, String name,
String ns)
at System.Runtime.Serialization.Json.DataContractJsonSerializer.InternalReadObject(XmlReaderDelegator
xmlReader, Boolean verifyObjectName)
at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator
reader, Boolean verifyObjectName, DataContractResolver
dataContractResolver)
I don't have a JSON or JS file for the view. When I use the variation of this for single item select all works good.
It turns out the value for the sf-selected-ids attribute needs to be in JSON array format. e.g. [ productId1, productId2, productId3]. Otherwise the backend service throws that exception. However, the selector by itself creates the string as product1, product2, product3. I.e. without the brackets. (You can see this in the advanced view of the designer).
So here are the detailed steps:
Here is the selector in the designer view (DesignerView.Simple.cshtml):
<sf-list-selector sf-dynamic-items-selector sf-provider="properties.ProductProviderName.PropertyValue" sf-item-type="properties.ProductType.PropertyValue" sf-multiselect="true" sf-sortable="true" sf-master="true" sf-selected-ids="productIds" />
You'll need the designer JS file to do the JSON conversion back and forth. So I save this in the MVC/Scripts/[WidgetName]/designer-simple.json: (Simple is the name of the designer view)
(function ($) {
var designerModule = angular.module('designer');
angular.module('designer').requires.push('sfSelectors');
designerModule.controller('SimpleCtrl', ['$scope', 'propertyService', function ($scope, propertyService) {
$scope.feedback.showLoadingIndicator = true;
propertyService.get().then(function (data) {
if (data) {
$scope.properties = propertyService.toAssociativeArray(data.Items);
}
},
function (data) {
$scope.feedback.showError = true;
if (data)
$scope.feedback.errorMessage = data.Detail;
}).finally(function () {
$scope.feedback.showLoadingIndicator = false;
});
$scope.$watch('properties.ProductIds.PropertyValue', function (newValue, oldValue) {
if (newValue) {
$scope.productIds = JSON.parse(newValue);
}
});
$scope.$watch('productIds', function (newValue, oldValue) {
if (newValue) {
$scope.properties.ProductIds.PropertyValue = JSON.stringify(newValue);
}
});
}]);
})(jQuery);
Lastly I added a DesignerView.Simple.json file in the same folder as DesignerView.Simple.cshtml:
{
"priority": 1,
"scripts": [
"client-components/selectors/common/sf-selected-items-view.js"
],
"components" : ["sf-dynamic-items-selector"]
}
The widget controller has a ProductIds property. Its values will be in format [productId1, productId2, etc.]. I used a JSON deserializer to get an array of products for the controller Index action:
public class ProductListController : Controller
{
private string productProviderName = WebConfigurationManager.AppSettings["productProviderName"];
private string productTypeName = WebConfigurationManager.AppSettings["productTypeName"];
public string ProductIds { get; set; }
public string ProductType
{
get { return productTypeName; }
set { productTypeName = value; }
}
public string ProductProviderName
{
get { return productProviderName; }
set { productProviderName = value; }
}
public ActionResult Index()
{
var selectedProducts = string.IsNullOrEmpty(this.ProductIds) ? new Guid[0] : JsonConvert.DeserializeObject<Guid[]>(this.ProductIds);
// ... rest of your controller index action
}
}

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();
}

Ravendb - Patching a List of Strings

Using Ravendb (build 960) I am attempting to perform a bulk update on a set of documents to replace a single value in list of strings. I used Google Group Question as base for the code, as the request was the nearly identical, but for some reason they were able to get theirs to work while mine errors out. I have composed the following sample console application to demo the issue.
public class Document
{
public const string OLD_NAME = "Label A";
public const string NEW_NAME = "Label B";
public Document()
{
Labels = new List<string> { OLD_NAME };
}
public string Id { get; set; }
public IList<string> Labels { get; set; }
}
public class Document_By_Labels : AbstractIndexCreationTask<Document>
{
public Document_By_Labels()
{
Map = leads => from doc in leads select new {doc.Labels};
}
}
internal class Program
{
private static void Main(string[] args)
{
IDocumentStore store = new DocumentStore
{
Url = "http://localhost:8081",
DefaultDatabase = "RavendbPatchStringListTest"
}.Initialize();
IndexCreation.CreateIndexes(typeof (Program).Assembly, store);
using (IDocumentSession session = store.OpenSession())
{
var s = new Document();
session.Store(s);
session.SaveChanges();
var d = session.Load<Document>(s.Id);
var m = session.Advanced.GetMetadataFor(d);
}
store.DatabaseCommands.UpdateByIndex("Document/By/Labels",
new IndexQuery {Query = string.Format("Labels:\"{0}\"", Document.OLD_NAME)},
new[]
{
new PatchRequest
{
Type = PatchCommandType.Modify,
Name = "Labels",
AllPositions = true,
Nested =
new[]
{
new PatchRequest
{
Type = PatchCommandType.Remove,
Value = new RavenJValue(Document.OLD_NAME)
},
new PatchRequest
{
Type = PatchCommandType.Add,
Value = new RavenJValue(Document.NEW_NAME)
}
}
}
}, allowStale: true);
}
}
When I run I get:
System.InvalidCastException: Unable to cast object of type 'Raven.Json.Linq.RavenJValue' to type 'Raven.Json.Linq.RavenJObject'.
at Raven.Json.Linq.Extensions.Convert[U](RavenJToken token, Boolean cast) in c:\Builds\RavenDB-Stable\Raven.Abstractions\Json\Linq\Extensions.cs:line 131
at Raven.Json.Linq.Extensions.Convert[U](RavenJToken token) in c:\Builds\RavenDB-Stable\Raven.Abstractions\Json\Linq\Extensions.cs:line 116
at Raven.Json.Linq.Extensions.Value[U](RavenJToken value) in c:\Builds\RavenDB-Stable\Raven.Abstractions\Json\Linq\Extensions.cs:line 24
at Raven.Database.Json.JsonPatcher.ModifyValue(PatchRequest patchCmd, String propName, RavenJToken property) in c:\Builds\RavenDB-Stable\Raven.Database\Json\JsonPatcher.cs:line 138
at Raven.Database.Json.JsonPatcher.Apply(PatchRequest patchCmd) in c:\Builds\RavenDB-Stable\Raven.Database\Json\JsonPatcher.cs:line 61
at Raven.Database.Json.JsonPatcher.Apply(PatchRequest[] patch) in c:\Builds\RavenDB-Stable\Raven.Database\Json\JsonPatcher.cs:line 30
at Raven.Database.DocumentDatabase.<>c__DisplayClassc1.<ApplyPatch>b__be(IStorageActionsAccessor actions) in c:\Builds\RavenDB-Stable\Raven.Database\DocumentDatabase.cs:line 1150
at Raven.Storage.Esent.TransactionalStorage.Batch(Action`1 action) in c:\Builds\RavenDB-Stable\Raven.Storage.Esent\TransactionalStorage.cs:line 330
at Raven.Database.DocumentDatabase.ApplyPatch(String docId, Nullable`1 etag, PatchRequest[] patchDoc, TransactionInformation transactionInformation) in c:\Builds\RavenDB-Stable\Raven.Database\DocumentDatabase.cs:line 1131
at Raven.Database.Impl.DatabaseBulkOperations.<>c__DisplayClass2.<UpdateByIndex>b__1(String docId, TransactionInformation tx) in c:\Builds\RavenDB-Stable\Raven.Database\Impl\DatabaseBulkOperations.cs:line 42
at Raven.Database.Impl.DatabaseBulkOperations.<>c__DisplayClassa.<PerformBulkOperation>b__5(IStorageActionsAccessor actions) in c:\Builds\RavenDB-Stable\Raven.Database\Impl\DatabaseBulkOperations.cs:line 80
at Raven.Storage.Esent.TransactionalStorage.ExecuteBatch(Action`1 action) in c:\Builds\RavenDB-Stable\Raven.Storage.Esent\TransactionalStorage.cs:line 376
at Raven.Storage.Esent.TransactionalStorage.Batch(Action`1 action) in c:\Builds\RavenDB-Stable\Raven.Storage.Esent\TransactionalStorage.cs:line 337
at Raven.Database.Impl.DatabaseBulkOperations.PerformBulkOperation(String index, IndexQuery indexQuery, Boolean allowStale, Func`3 batchOperation) in c:\Builds\RavenDB-Stable\Raven.Database\Impl\DatabaseBulkOperations.cs:line 75
at Raven.Database.Impl.DatabaseBulkOperations.UpdateByIndex(String indexName, IndexQuery queryToUpdate, PatchRequest[] patchRequests, Boolean allowStale) in c:\Builds\RavenDB-Stable\Raven.Database\Impl\DatabaseBulkOperations.cs:line 40
at Raven.Database.Server.Responders.DocumentBatch.<>c__DisplayClass3.<Respond>b__0(String index, IndexQuery query, Boolean allowStale) in c:\Builds\RavenDB-Stable\Raven.Database\Server\Responders\DocumentBatch.cs:line 47
at Raven.Database.Server.Responders.DocumentBatch.OnBulkOperation(IHttpContext context, Func`4 batchOperation) in c:\Builds\RavenDB-Stable\Raven.Database\Server\Responders\DocumentBatch.cs:line 64
at Raven.Database.Server.Responders.DocumentBatch.Respond(IHttpContext context) in c:\Builds\RavenDB-Stable\Raven.Database\Server\Responders\DocumentBatch.cs:line 46
at Raven.Database.Server.HttpServer.DispatchRequest(IHttpContext ctx) in c:\Builds\RavenDB-Stable\Raven.Database\Server\HttpServer.cs:line 550
at Raven.Database.Server.HttpServer.HandleActualRequest(IHttpContext ctx) in c:\Builds\RavenDB-Stable\Raven.Database\Server\HttpServer.cs:line 316
While I believe the believe the process is correct I must be missing something otherwise it wouldn't be erroring out.
Please note there is no name on the above nested patches as I have tried a many different combos with the same error. Examples of attempts: "", "$values", "Labels". Same error each time and as a list of strings does not seem to have a Name I left it out in the above on purpose.
Thanks in advance.
I've been looking how to do the same thing recently. It sounds like it isn't possible to use the current patching API to change a string array.
See the discussion I've been having here: https://groups.google.com/forum/#!topic/ravendb/5qYWsq_ny0M

Mvvm light toolkit and navigate by frame

Do you have a tutoriel which explain navigate with uri. When my application start i load in my frame "Login.xaml" and his viewModel. When i click on my button "Log" (i use a relaycommand) i want that my frame load "Acceuil.xaml".
how make it ?
thx
You are trying too hard. Frame navigation is very simple - just create your frame, such as 'MyFrame' then created Hyperlinks with a simple NavigateUri value of "/Acceuil.xaml". If you want to show/hide the links from the status / details of your view model, use a property which you bind to and update in the view model. For example. You can use a UserInfo property, then a converter class such as this to show / hide based upon the UserInfo property being a null value or a class result:
public class HideWhenNullConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null)
{
return Visibility.Collapsed;
}
return Visibility.Visible;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
Hope this helps you get started. Another tip is to add some logic to your application to prevent attempts to navigate to unauthenticated locations. For example:
private void mainFrame_Navigating(object sender, System.Windows.Navigation.NavigatingCancelEventArgs e)
{
List<string> anonUrls = new List<string>();
anonUrls.Add("/Welcome");
anonUrls.Add("/Register");
anonUrls.Add("/ValidateEmail");
var myAnonUrl = (from u in anonUrls
where e.Uri.OriginalString.StartsWith(u)
select u).Count();
if ((WebContext.Current.User == null ||
WebContext.Current.User.IsAuthenticated == false) &&
myAnonUrl == 0)
{
origUri = e.Uri;
e.Cancel = true;
mainFrame.Navigate(new Uri("/Welcome", UriKind.Relative));
}
}
Hoepfully this helps you to understand the navigation frame a little more.

NHibernate dynamic-update fails to update data changed in interceptor

If I set dynamic-update=true I've found that fields updated in my Interceptor do not get included in the update statement that goes to the database. When I set it to false all the columns including the time stamp get updated. I really want to use dynamic update.
public class Interceptor : EmptyInterceptor
{
public override Boolean OnFlushDirty(object entity, object id, object[] state,
object[] previousState, string[] propertyNames, IType[] types)
{
var auditEntity = entity as BaseAuditEntity;
if (auditEntity != null)
{
var now = DateTime.Now;
var index = Array.IndexOf(propertyNames, "LastModifiedTimestamp");
state[index] = now;
auditEntity.LastModifiedTimestamp = now;
}
return base.OnFlushDirty(entity, id, state, previousState, propertyNames, types);
}
}
I thought that this line would have marked my the last modified column as dirty.
auditEntity.LastModifiedTimestamp = now;
Is there something I should do in my interceptor to mark the time stamp field as dirty?
The API-Doc says: "returns true if the user modified the currentState in any way."
Did you try to return true instead of calling the empty base implementation?
public class Interceptor : EmptyInterceptor
{
public override Boolean OnFlushDirty(object entity, object id, object[] state,
object[] previousState, string[] propertyNames, IType[] types)
{
var auditEntity = entity as BaseAuditEntity;
if (auditEntity != null)
{
var now = DateTime.Now;
var index = Array.IndexOf(propertyNames, "LastModifiedTimestamp");
state[index] = now;
auditEntity.LastModifiedTimestamp = now;
return true;
}
return base.OnFlushDirty(entity, id, state, previousState, propertyNames, types);
}
}