Sitecore 7:Publishing fails on Custom Save Handler - events

I am trying to validate two date fields for start date to be before end date on item:saving event and below is the code for the same.
if (!string.IsNullOrEmpty(eventTemplate) && !string.IsNullOrEmpty(eventdate) && !string.IsNullOrEmpty(eventenddate))
{
//Validate ifitem is based on the event template then only doing the check
var validitem = (from temp in item.Template.BaseTemplates
where temp.ID == new Sitecore.Data.ID(eventTemplate)
select temp).FirstOrDefault();
if (validitem != null)
{
string firstFieldName = eventdate;
string lastFieldName = eventenddate;
Sitecore.Data.Fields.DateField first = item.Fields[firstFieldName];
Sitecore.Data.Fields.DateField last = item.Fields[lastFieldName];
if (last != null && last.DateTime != DateTime.MinValue && DateTime.Compare(first.DateTime, last.DateTime) > 0)
{
string firstTitle = Sitecore.StringUtil.GetString(first.InnerField.Title, first.InnerField.Name);
string lastTitle = Sitecore.StringUtil.GetString(last.InnerField.Title, last.InnerField.Name);
if (!string.IsNullOrEmpty(firstTitle) && !string.IsNullOrEmpty(lastTitle))
{
Sitecore.Web.UI.Sheer.SheerResponse.Alert(String.Format("Item not saved as {0} should be before or equal to {1}.", firstTitle, lastTitle));
}
eventArgs.Result.Cancel = true;
}
}
}
The above code works fine.However on publishing the site I get the below issue:
Job started: Publish to 'web'|#Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object.
at Sitecore.Web.UI.Sheer.ClientPage..ctor()
at Sitecore.Context.get_ClientPage()
at custom.ui.extensions.**ValidateDate.OnItemSaving**(Object sender, EventArgs args) in c:\Instance\source\ui\adiweb.ui.extensions\Custom Validations\ValidateDate.cs:line 46
at Sitecore.Events.Event.EventSubscribers.RaiseEvent(String eventName, Object[] parameters, EventResult result)
at Sitecore.Events.Event.RaiseEvent(String eventName, Object[] parameters)
at Sitecore.Events.Event.DataEngine_ItemSaving(Object sender, ExecutingEventArgs`1 e)
at System.EventHandler`1.Invoke(Object sender, TEventArgs e)
at Sitecore.Data.Engines.EngineCommand`2.CanExecute()
at Sitecore.Data.Engines.EngineCommand`2.Execute()
at Sitecore.Data.Engines.DataEngine.SaveItem(Item item)
at Sitecore.Data.Managers.ItemProvider.SaveItem(Item item)
at Sitecore.Data.Items.ItemEditing.AcceptChanges(Boolean updateStatistics, Boolean silent)
at Sitecore.Data.Items.EditContext.Dispose()
at Sitecore.Publishing.PublishHelper.CopyToTarget(Item sourceVersion)
at Sitecore.Publishing.PublishHelper.PublishVersionToTarget(Item sourceVersion, Item targetItem, Boolean targetCreated)
at Sitecore.Publishing.Pipelines.PublishItem.PerformAction.ExecuteAction(PublishItemContext context)
at Sitecore.Publishing.Pipelines.PublishItem.PerformAction.Process(PublishItemContext context)
at (Object , Object[] )
at Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args)
at Sitecore.Publishing.Pipelines.PublishItem.PublishItemPipeline.Run(PublishItemContext context)
at Sitecore.Publishing.Pipelines.Publish.ProcessQueue.ProcessEntries(IEnumerable`1 entries, PublishContext context)
at Sitecore.Publishing.Pipelines.Publish.ProcessQueue.ProcessEntries(IEnumerable`1 entries, PublishContext context)
at Sitecore.Publishing.Pipelines.Publish.ProcessQueue.ProcessEntries(IEnumerable`1 entries, PublishContext context)
at Sitecore.Publishing.Pipelines.Publish.ProcessQueue.ProcessEntries(IEnumerable`1 entries, PublishContext context)
at Sitecore.Publishing.Pipelines.Publish.ProcessQueue.ProcessEntries(IEnumerable`1 entries, PublishContext context)
at Sitecore.Publishing.Pipelines.Publish.ProcessQueue.ProcessEntries(IEnumerable`1 entries, PublishContext context)
at Sitecore.Publishing.Pipelines.Publish.ProcessQueue.ProcessEntries(IEnumerable`1 entries, PublishContext context)
at Sitecore.Publishing.Pipelines.Publish.ProcessQueue.ProcessEntries(IEnumerable`1 entries, PublishContext context)
at Sitecore.Publishing.Pipelines.Publish.ProcessQueue.ProcessEntries(IEnumerable`1 entries, PublishContext context)
at Sitecore.Publishing.Pipelines.Publish.ProcessQueue.ProcessEntries(IEnumerable`1 entries, PublishContext context)
at Sitecore.Publishing.Pipelines.Publish.ProcessQueue.Process(PublishContext context)
at (Object , Object[] )
at Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args)
at Sitecore.Publishing.Pipelines.Publish.PublishPipeline.Run(PublishContext context)
at Sitecore.Publishing.Publisher.Publish()
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at (Object , Object[] )
at Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args)
at Sitecore.Jobs.Job.ThreadEntry(Object state)
Avy idea on why i get this issue.
Here error points to the line:
Sitecore.Web.UI.Sheer.SheerResponse.Alert(String.Format("Item not saved as {0} should be before or equal to {1}.", firstTitle, lastTitle));
IS use of Sitecore.Web.UI.Sheer.SheerResponse.Alert is invalid but i see many such implementations.

You're making a classical mistake here. The item: events such as item:saved and item:saving will be fired, when publishing. Basically because the act of publishing an item, means reading the item, and saving it onto the "web" database under normal circumstances.
The quickest fix you can implement, is to make sure you're dealing with item:saving on an item in the database you expect, probably "master". Something like:
if (validitem != null && validItem.Database.Name == "master")
A more long term fix, would be to hook your code into the "saveUI" pipeline instead - it triggers on what you expect here; when an item is being saved in the UI.

Since the item:saving event also runs during publishing, you should add a null check on Sitecore.Context.ClientPage to the start of your event handler, if it's null, return immediately. That is likely the source of the NullReferenceException.
if (Sitecore.Context.ClientPage == null) return;

Related

Internet Service Error on Microsoft.Bot.Builder.Dialogs.Adaptive.Runtime on dot net 6

i attempt to migrate bot framework composer dot net 3.1 project to dot net 6
upon testing i hit Internet Service Error, any insight would be appreciated.
ArgumentNullException: Value cannot be null. (Parameter 'adaptiveDialogId')
Microsoft.Bot.Builder.Dialogs.Adaptive.AdaptiveDialogBot..ctor(string adaptiveDialogId, string languageGeneratorId, ResourceExplorer resourceExplorer, ConversationState conversationState, UserState userState, SkillConversationIdFactoryBase skillConversationIdFactoryBase, LanguagePolicy languagePolicy, BotFrameworkAuthentication botFrameworkAuthentication, IBotTelemetryClient telemetryClient, IEnumerable scopes, IEnumerable pathResolvers, IEnumerable dialogs, ILogger logger)
Microsoft.Bot.Builder.Dialogs.Adaptive.Runtime.ConfigurationAdaptiveDialogBot..ctor(IConfiguration configuration, ResourceExplorer resourceExplorer, ConversationState conversationState, UserState userState, SkillConversationIdFactoryBase skillConversationIdFactoryBase, LanguagePolicy languagePolicy, BotFrameworkAuthentication botFrameworkAuthentication, IBotTelemetryClient telemetryClient, IEnumerable scopes, IEnumerable pathResolvers, IEnumerable dialogs, ILogger logger)
System.RuntimeMethodHandle.InvokeMethod(object target, ref Span arguments, Signature sig, bool constructor, bool wrapExceptions)
System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor<TArgument, TResult>.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite callSite, RuntimeResolverContext context)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor<TArgument, TResult>.VisitCallSite(ServiceCallSite callSite, TArgument argument)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
Microsoft.Extensions.DependencyInjection.ServiceProvider.CreateServiceAccessor(Type serviceType)
System.Collections.Concurrent.ConcurrentDictionary<TKey, TValue>.GetOrAdd(TKey key, Func<TKey, TValue> valueFactory)
Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)
lambda_method8(Closure , IServiceProvider , object[] )
Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider+<>c__DisplayClass7_0.b__0(ControllerContext controllerContext)
Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider+<>c__DisplayClass6_0.g__CreateController|0(ControllerContext controllerContext)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
Thanks AP01 for dropping your knowledge
Unfortunately, the adaptiveDialogId is embedded in library Microsoft.Bot.Builder.Dialogs.Adaptive.Runtime in which I cannot debug
however, inspired by your advice
I modify the build target not from scratch, but simply upgrade the dot net target straight from 3.1 to 6
as it turns out the problems caused by nullable validation in the Project File, this causes dot net 3.1 libraries not working
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Platforms>x64</Platforms>
**<Nullable>enable</Nullable>**
...
</PropertyGroup>

MVVM Light IoC not Binding? What am I missing?

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

Data deletion through WFC data service client applciation

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

Linq 'Group by' after Migrate from Orchard 1.5.1 to Orchard 1.6

I have a problem with 'group by'.
before Migration to Orchard 1.5.1, I didn't have any problem with this code:
var list = (from r in GetAll()
group new { r.FormulaCatId, r.InputPeriodId, r.CurrencyId } by new { r.FormulaCatId, r.InputPeriodId, r.CurrencyId }
into grp
select (new CatCurPerViewModel
{
FormulaCatId = grp.Key.FormulaCatId,
InputPeriodId = grp.Key.InputPeriodId,
CurrencyId = grp.Key.CurrencyId
}));
but after migration to Orchard 1.6 this problem occurred:
2013-01-10 15:01:25,704 [7] Orchard.Exceptions.DefaultExceptionPolicy - An unexpected exception was caught
System.NotImplementedException: The method or operation is not implemented.
at NHibernate.Linq.CacheableExpressionNode.Resolve(ParameterExpression inputParameter, Expression expressionToBeResolved, ClauseGenerationContext clauseGenerationContext)
at Remotion.Linq.Parsing.Structure.IntermediateModel.ExpressionResolver.GetResolvedExpression(Expression unresolvedExpression, ParameterExpression parameterToBeResolved, ClauseGenerationContext clauseGenerationContext)
at Remotion.Linq.Parsing.Structure.IntermediateModel.GroupByExpressionNode.<>c__DisplayClass1.<GetResolvedKeySelector>b__0(ExpressionResolver r)
at Remotion.Linq.Parsing.Structure.IntermediateModel.ResolvedExpressionCache`1.GetOrCreate(Func`2 generator)
at Remotion.Linq.Parsing.Structure.IntermediateModel.GroupByExpressionNode.CreateResultOperator(ClauseGenerationContext clauseGenerationContext)
at Remotion.Linq.Parsing.Structure.IntermediateModel.ResultOperatorExpressionNodeBase.ApplyNodeSpecificSemantics(QueryModel queryModel, ClauseGenerationContext clauseGenerationContext)
at Remotion.Linq.Parsing.Structure.IntermediateModel.MethodCallExpressionNodeBase.Apply(QueryModel queryModel, ClauseGenerationContext clauseGenerationContext)
at Remotion.Linq.Parsing.Structure.QueryParser.ApplyAllNodes(IExpressionNode node, ClauseGenerationContext clauseGenerationContext)
at Remotion.Linq.Parsing.Structure.QueryParser.GetParsedQuery(Expression expressionTreeRoot)
at NHibernate.Linq.NhLinqExpression.Translate(ISessionFactoryImplementor sessionFactory)
at NHibernate.Hql.Ast.ANTLR.ASTQueryTranslatorFactory.CreateQueryTranslators(String queryIdentifier, IQueryExpression queryExpression, String collectionRole, Boolean shallow, IDictionary`2 filters, ISessionFactoryImplementor factory)
at NHibernate.Engine.Query.HQLExpressionQueryPlan.CreateTranslators(String expressionStr, IQueryExpression queryExpression, String collectionRole, Boolean shallow, IDictionary`2 enabledFilters, ISessionFactoryImplementor factory)
at NHibernate.Engine.Query.QueryPlanCache.GetHQLQueryPlan(IQueryExpression queryExpression, Boolean shallow, IDictionary`2 enabledFilters)
at NHibernate.Impl.AbstractSessionImpl.GetHQLQueryPlan(IQueryExpression queryExpression, Boolean shallow)
at NHibernate.Impl.AbstractSessionImpl.CreateQuery(IQueryExpression queryExpression)
at NHibernate.Linq.DefaultQueryProvider.Execute(Expression expression)
at NHibernate.Linq.DefaultQueryProvider.Execute[TResult](Expression expression)
at Remotion.Linq.QueryableBase`1.GetEnumerator()
at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at SAS.Core.Services.RateService.ListCatCurPer()
at SAS.Core.Controllers.RatesAdminController.Index()
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass13.<InvokeActionMethodWithFilters>b__10()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
the issue happens because in orchard 1.6 the Table property of Orchard.Data.Repository<T> is implemented in the following way:
public virtual IQueryable<T> Table
{
get { return Session.Query<T>().Cacheable(); }
}
and you cant use Group By with Cacheable() - there is an open ticket in HNIbernate Jira
Orchard does that Cacheable() call in order to leverage 2nd level Nhibernate cache.
If you do not use and do not intend to use this 2nd level cache and the corresponding module in Orchard, you can download Orchard source code, and change the implementation of the Table property in Orchard.Data.Repository<T> to
public virtual IQueryable<T> Table
{
get { return Session.Query<T>(); }
}
This will fix your issue.
Or if you do not want to change Orchard sources, you can create your own generic repository class, and wire it up into DependencyContainer (by default Orchard comes with Autofac).
Here is how it can be done with Autofac 2.6.3.862:
public class MyRepository<T> : Orchard.Data.Repository<T> where T:class
{
public MyRepository(ISessionLocator sessionLocator) : base(sessionLocator)
{
}
public override System.Linq.IQueryable<T> Table
{
get { return Session.Query<T>(); }
}
}
public class MyDataModule : Autofac.Module
{
protected override void AttachToComponentRegistration(Autofac.Core.IComponentRegistry componentRegistry, Autofac.Core.IComponentRegistration registration)
{
base.AttachToComponentRegistration(componentRegistry, registration);
Type limitType = registration.Activator.LimitType;
if (!limitType.IsGenericType || limitType.GetGenericTypeDefinition() != typeof (Repository<>)) return;
var epamRepoTye = typeof(MyRepository<>).MakeGenericType(limitType.GetGenericArguments());
registration.Activating += (s, e) =>
{
var locator = e.Context.Resolve<ISessionLocator>();
e.Instance = Activator.CreateInstance(epamRepoTye, new object[] {locator});
};
}
}
Probably (i have not tested this) the MyDataModule class can be simplified if you can guarantee that the assembly containing it will be loaded later than Orchard.Core assembly:
public class MyDataModule : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterGeneric(typeof(MyRepository<>)).As(typeof(IRepository<>)).InstancePerDependency();
}
}

MS.Internal.XcpImports.MethodEx(IntPtr ptr, String name, CValue[] cvData

I am getting an error "Value does not fall within the expected range". The stacktrace is given below. Please help...
at MS.Internal.XcpImports.MethodEx(IntPtr ptr, String name, CValue[] cvData)
at MS.Internal.XcpImports.MethodPack(IntPtr objectPtr, String methodName, Object[] rawData)
at MS.Internal.XcpImports.UIElement_TransformToVisual(UIElement element, UIElement visual)
at Microsoft.Phone.Controls.Pivot.ReleaseMouseCaptureAtGestureOrigin()
at Microsoft.Phone.Controls.Pivot.OnManipulationDelta(Object sender, ManipulationDeltaEventArgs args)
at MS.Internal.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex, Delegate handlerDelegate, Object sender, Object args)
at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, Int32 actualArgsTypeIndex, String eventName)
Might be you are trying to access main thread object or UI thread object in a asynchronous function.because asynchronous function's thread has lower priority so you cant access the main thread object from here..

Resources