I have a project include MVC and Web API controllers. I have,
GlobalConfiguration.MessageHandlers.Insert(0, new MessageHandler1());
But when I request a MVC controller it executes this handler. It hurting me because SuppressDefaultHostAuthentication is executing PassiveAuthenticationMessageHandler handler on MVC request. I have put a break-point on MessageHandler1.SendAsync and found that System.Web.HttpContext.Current.Handler = {System.Web.Mvc.MvcHandler} which confirm that it is MVC request.
StackTrace,
MyApp.dll!MyApp.MessageHandler1.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Line 120 C#
System.Net.Http.dll!System.Net.Http.DelegatingHandler.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown
System.Web.Http.dll!System.Web.Http.Tracing.Tracers.MessageHandlerTracer.AnonymousMethod__FabricatedMethod5() Unknown
System.Web.Http.dll!System.Web.Http.Tracing.Tracers.MessageHandlerTracer.SendAsync.AnonymousMethod__0() Unknown
System.Web.Http.dll!System.Web.Http.Tracing.ITraceWriterExtensions.TraceBeginEndAsync<System.Net.Http.HttpResponseMessage>(System.Web.Http.Tracing.ITraceWriter traceWriter, System.Net.Http.HttpRequestMessage request, string category, System.Web.Http.Tracing.TraceLevel level, string operatorName, string operationName, System.Action<System.Web.Http.Tracing.TraceRecord> beginTrace, System.Func<System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>> execute, System.Action<System.Web.Http.Tracing.TraceRecord,System.Net.Http.HttpResponseMessage> endTrace, System.Action<System.Web.Http.Tracing.TraceRecord> errorTrace) Unknown
System.Web.Http.dll!System.Web.Http.Tracing.Tracers.MessageHandlerTracer.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown
System.Net.Http.dll!System.Net.Http.DelegatingHandler.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown
System.Web.Http.dll!System.Web.Http.Tracing.Tracers.RequestMessageHandlerTracer.AnonymousMethod__FabricatedMethod6() Unknown
System.Web.Http.dll!System.Web.Http.Tracing.Tracers.RequestMessageHandlerTracer.SendAsync.AnonymousMethod__1() Unknown
System.Web.Http.dll!System.Web.Http.Tracing.ITraceWriterExtensions.TraceBeginEndAsync<System.Net.Http.HttpResponseMessage>(System.Web.Http.Tracing.ITraceWriter traceWriter, System.Net.Http.HttpRequestMessage request, string category, System.Web.Http.Tracing.TraceLevel level, string operatorName, string operationName, System.Action<System.Web.Http.Tracing.TraceRecord> beginTrace, System.Func<System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>> execute, System.Action<System.Web.Http.Tracing.TraceRecord,System.Net.Http.HttpResponseMessage> endTrace, System.Action<System.Web.Http.Tracing.TraceRecord> errorTrace) Unknown
System.Web.Http.dll!System.Web.Http.Tracing.Tracers.RequestMessageHandlerTracer.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown
System.Net.Http.dll!System.Net.Http.DelegatingHandler.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown
System.Web.Http.dll!System.Web.Http.HttpServer.AnonymousMethod__FabricatedMethod9() Unknown
System.Web.Http.dll!System.Web.Http.HttpServer.SendAsync() Unknown
mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start<System.Web.Http.HttpServer.SendAsync>(ref System.Web.Http.HttpServer.SendAsync stateMachine) Unknown
mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.__Canon>.Start<System.Web.Http.HttpServer.SendAsync>(ref System.Web.Http.HttpServer.SendAsync stateMachine) Unknown
System.Web.Http.dll!System.Web.Http.HttpServer.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown
System.Net.Http.dll!System.Net.Http.HttpMessageInvoker.SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) Unknown
System.Web.Http.Owin.dll!System.Web.Http.Owin.HttpMessageHandlerAdapter.InvokeCore() Unknown
mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start<System.Web.Http.Owin.HttpMessageHandlerAdapter.InvokeCore>(ref System.Web.Http.Owin.HttpMessageHandlerAdapter.InvokeCore stateMachine) Unknown
mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start<System.Web.Http.Owin.HttpMessageHandlerAdapter.InvokeCore>(ref System.Web.Http.Owin.HttpMessageHandlerAdapter.InvokeCore stateMachine) Unknown
System.Web.Http.Owin.dll!System.Web.Http.Owin.HttpMessageHandlerAdapter.InvokeCore(Microsoft.Owin.IOwinContext context, Microsoft.Owin.IOwinRequest owinRequest, Microsoft.Owin.IOwinResponse owinResponse) Unknown
System.Web.Http.Owin.dll!System.Web.Http.Owin.HttpMessageHandlerAdapter.Invoke(Microsoft.Owin.IOwinContext context) Unknown
Microsoft.Owin.Security.dll!Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware<Microsoft.Owin.Security.Google.GoogleOAuth2AuthenticationOptions>.Invoke() Unknown
mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start<Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware<Microsoft.Owin.Security.Google.GoogleOAuth2AuthenticationOptions>.Invoke>(ref Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware<Microsoft.Owin.Security.Google.GoogleOAuth2AuthenticationOptions>.Invoke stateMachine) Unknown
mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.Threading.Tasks.VoidTaskResult>.Start<Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware<Microsoft.Owin.Security.Google.GoogleOAuth2AuthenticationOptions>.Invoke>(ref Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware<Microsoft.Owin.Security.Google.GoogleOAuth2AuthenticationOptions>.Invoke stateMachine) Unknown
mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start<Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware<Microsoft.Owin.Security.Google.GoogleOAuth2AuthenticationOptions>.Invoke>(ref Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware<Microsoft.Owin.Security.Google.GoogleOAuth2AuthenticationOptions>.Invoke stateMachine) Unknown
Microsoft.Owin.Security.dll!Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware<Microsoft.Owin.Security.Google.GoogleOAuth2AuthenticationOptions>.Invoke(Microsoft.Owin.IOwinContext context) Unknown
Microsoft.Owin.Security.dll!Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware<Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions>.Invoke() Unknown
mscorlib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start<Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware<Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions>.Invoke>(ref Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware<Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions>.Invoke stateMachine) Unknown
mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder<System.Threading.Tasks.VoidTaskResult>.Start<Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware<Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions>.Invoke>(ref Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware<Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions>.Invoke stateMachine) Unknown
mscorlib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start<Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware<Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions>.Invoke>(ref Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware<Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions>.Invoke stateMachine) Unknown
Microsoft.Owin.Security.dll!Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware<Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions>.Invoke(Microsoft.Owin.IOwinContext context) Unknown
Microsoft.Owin.dll!Microsoft.Owin.Infrastructure.OwinMiddlewareTransition.Invoke(System.Collections.Generic.IDictionary<string,object> environment) Unknown
Microsoft.Owin.Host.SystemWeb.dll!Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContextStage.BeginEvent(object sender, System.EventArgs e, System.AsyncCallback cb, object extradata) Unknown
System.Web.dll!System.Web.HttpApplication.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() Unknown
System.Web.dll!System.Web.HttpApplication.ExecuteStep(System.Web.HttpApplication.IExecutionStep step, ref bool completedSynchronously) Unknown
System.Web.dll!System.Web.HttpApplication.PipelineStepManager.ResumeSteps(System.Exception error) Unknown
System.Web.dll!System.Web.HttpApplication.BeginProcessRequestNotification(System.Web.HttpContext context, System.AsyncCallback cb) Unknown
System.Web.dll!System.Web.HttpRuntime.ProcessRequestNotificationPrivate(System.Web.Hosting.IIS7WorkerRequest wr, System.Web.HttpContext context) Unknown
System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags) Unknown
System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags) Unknown
[Native to Managed Transition]
[Managed to Native Transition]
System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags) Unknown
System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags) Unknown
[AppDomain Transition]
I just fix it using custom MessageHandler,
GlobalConfiguration.SuppressDefaultHostAuthentication();
GlobalConfiguration.Filters.Add(new HostAuthenticationFilter(OAuthOptions.AuthenticationType));
GlobalConfiguration.MessageHandlers.Insert(0, new ResetMvcPrincipalMessageHandler());
public class ResetMvcPrincipalMessageHandler : DelegatingHandler
{
protected async override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
var url = request.RequestUri.AbsolutePath;
if (!url.Contains("/api/"))// not web api request
{
var principal = request.GetRequestContext().Principal;
var response = await base.SendAsync(request, cancellationToken);;
request.GetRequestContext().Principal = principal;
return response;
}
return await base.SendAsync(request, cancellationToken);
}
}
Related
I've been working on this for the last 3 hours and haven't found a good resource or solution to this problem. I've followed the directions found in Microsoft's documentation to change my ASP.net Privatekey from a string to an int. Since then, I have been presented with the following error:
FormatException: Input string was not in a correct format.
The app will not load past this method in the program.cs class:
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
I have hit a roadblock and any help with this issue would be appreciated.
Asp.net Error Stack:
FormatException: Input string was not in a correct format.
System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type)
ArgumentException: 4c3ccce2-61cd-4315-9cf2-99933f6797ed is not a valid value for Int32. (Parameter 'value')
System.ComponentModel.BaseNumberConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
Stack Query Cookies Headers Routing
FormatException: Input string was not in a correct format.
System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type)
int.Parse(string s, NumberStyles style, IFormatProvider provider)
System.ComponentModel.Int32Converter.FromString(string value, NumberFormatInfo formatInfo)
System.ComponentModel.BaseNumberConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
Show raw exception details
System.FormatException: Input string was not in a correct format.
at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type)
at System.Int32.Parse(String s, NumberStyles style, IFormatProvider provider)
at System.ComponentModel.Int32Converter.FromString(String value, NumberFormatInfo formatInfo)
at System.ComponentModel.BaseNumberConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
ArgumentException: 4c3ccce2-61cd-4315-9cf2-99933f6797ed is not a valid value for Int32. (Parameter 'value')
System.ComponentModel.BaseNumberConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
System.ComponentModel.TypeConverter.ConvertFromInvariantString(string text)
Microsoft.AspNetCore.Identity.UserStoreBase<TUser, TKey, TUserClaim, TUserLogin, TUserToken>.ConvertIdFromString(string id)
Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore<TUser, TRole, TContext, TKey, TUserClaim, TUserRole, TUserLogin, TUserToken, TRoleClaim>.FindByIdAsync(string userId, CancellationToken cancellationToken)
Microsoft.AspNetCore.Identity.UserManager.FindByIdAsync(string userId)
Microsoft.AspNetCore.Identity.UserManager.GetUserAsync(ClaimsPrincipal principal)
Microsoft.AspNetCore.Identity.SignInManager.ValidateSecurityStampAsync(ClaimsPrincipal principal)
Microsoft.AspNetCore.Identity.SecurityStampValidator.ValidateAsync(CookieValidatePrincipalContext context)
Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler.HandleAuthenticateAsync()
Microsoft.AspNetCore.Authentication.AuthenticationHandler.AuthenticateAsync()
Microsoft.AspNetCore.Authentication.AuthenticationService.AuthenticateAsync(HttpContext context, string scheme)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
Show raw exception details
System.ArgumentException: 4c3ccce2-61cd-4315-9cf2-99933f6797ed is not a valid value for Int32. (Parameter 'value')
---> System.FormatException: Input string was not in a correct format.
at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type)
at System.Int32.Parse(String s, NumberStyles style, IFormatProvider provider)
at System.ComponentModel.Int32Converter.FromString(String value, NumberFormatInfo formatInfo)
at System.ComponentModel.BaseNumberConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
--- End of inner exception stack trace ---
at System.ComponentModel.BaseNumberConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
at System.ComponentModel.TypeConverter.ConvertFromInvariantString(String text)
at Microsoft.AspNetCore.Identity.UserStoreBase5.ConvertIdFromString(String id) at Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore9.FindByIdAsync(String userId, CancellationToken cancellationToken)
at Microsoft.AspNetCore.Identity.UserManager1.FindByIdAsync(String userId) at Microsoft.AspNetCore.Identity.UserManager1.GetUserAsync(ClaimsPrincipal principal)
at Microsoft.AspNetCore.Identity.SignInManager1.ValidateSecurityStampAsync(ClaimsPrincipal principal) at Microsoft.AspNetCore.Identity.SecurityStampValidator1.ValidateAsync(CookieValidatePrincipalContext context)
at Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler.HandleAuthenticateAsync()
at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.AuthenticateAsync()
at Microsoft.AspNetCore.Authentication.AuthenticationService.AuthenticateAsync(HttpContext context, String scheme)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context
I think the problem may be that the login of your previous user may be completed when the ID is a string.
You now change it to int, so now it no longer knows what to do with the string.
I think the simplest solution is that you should delete the cookie, log out and log in again (use int instead).
Not working Swagger Ui
500 : {"Message":"An error has occurred.","ExceptionMessage":"Invalid type owner for DynamicMethod.","ExceptionType":"System.ArgumentException","StackTrace":" at System.Reflection.Emit.DynamicMethod.Init(String name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] signature, Type owner, Module m, Boolean skipVisibility, Boolean transparentMethod, StackCrawlMark& stackMark)\r\n at System.Reflection.Emit.DynamicMethod..ctor(String name, Type returnType, Type[] parameterTypes, Type owner, Boolean skipVisibility)\r\n at Newtonsoft.Json.Utilities.DynamicReflectionDelegateFactory.CreateDynamicMethod(String name, Type returnType, Type[] parameterTypes, Type owner)\r\n at Newtonsoft.Json.Utilities.DynamicReflectionDelegateFactory.CreateDefaultConstructor[T](Type type)\r\n at Newtonsoft.Json.Serialization.DefaultContractResolver.GetDefaultCreator(Type createdType)\r\n at Newtonsoft.Json.Serialization.DefaultContractResolver.InitializeContract(JsonContract contract)\r\n at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateArrayContract(Type objectType)\r\n at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateContract(Type objectType)\r\n at Newtonsoft.Json.Serialization.DefaultContractResolver.ResolveContract(Type type)\r\n at Swashbuckle.Swagger.SchemaRegistry.CreateInlineSchema(Type type)\r\n at Swashbuckle.Swagger.SchemaRegistry.GetOrRegister(Type type)\r\n at Swashbuckle.Swagger.SwaggerGenerator.CreateParameter(String location, ApiParameterDescription paramDesc, SchemaRegistry schemaRegistry)\r\n at Swashbuckle.Swagger.SwaggerGenerator.<>c__DisplayClass12.b__11(ApiParameterDescription paramDesc)\r\n at System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext()\r\n at System.Collections.Generic.List1..ctor(IEnumerable1 collection)\r\n at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source)\r\n at Swashbuckle.Swagger.SwaggerGenerator.CreateOperation(ApiDescription apiDesc, SchemaRegistry schemaRegistry)\r\n at Swashbuckle.Swagger.SwaggerGenerator.CreatePathItem(IEnumerable1 apiDescriptions, SchemaRegistry schemaRegistry)\r\n at Swashbuckle.Swagger.SwaggerGenerator.<>c__DisplayClass7.<GetSwagger>b__4(IGrouping2 group)\r\n at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable1 source, Func2 keySelector, Func2 elementSelector, IEqualityComparer1 comparer)\r\n at Swashbuckle.Swagger.SwaggerGenerator.GetSwagger(String rootUrl, String apiVersion)\r\n at Swashbuckle.Application.SwaggerDocsHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\r\n at System.Net.Http.HttpMessageInvoker.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\r\n at System.Web.Http.Dispatcher.HttpRoutingDispatcher.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\r\n at System.Net.Http.DelegatingHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\r\n at System.Web.Http.HttpServer.d__0.MoveNext()"} http://localhost:5352/swagger/docs/v1
When I got this error, it was because I had an error/omission in my ResponseType definition (WebApi). The compiler was fine with it, but Swagger wasn't.
Failed
[ResponseType(typeof(IEnumerable<>))]
Worked
[ResponseType(typeof(IEnumerable<string>))]
I have created a project that makes use of Catel, Entity Framework 6 and Syncfusion Community Edition. Specifically I am using the sfDataGrid from Syncfusion.
I have come across an issue that has me completely stumped, maybe someone out there could point me in the right direction.
I have a Catel UserControl with a sfDataGrid in it. The ViewModel has an ObservableCollection (Catel Property) of the data I am using as the ItemsSource for the sfDataGrid. I have filtering enabled on the sfDataGrid. Here is the code for the sfDataGrid:
<sync:SfDataGrid
x:Name="ItemsDataGrid"
ItemsSource="{Binding MyItems, Mode=OneWay}"
SelectedItem="{Binding MyItem, Mode=TwoWay}"
AutoGenerateColumns="False"
AllowFiltering="True"
AllowResizingColumns="True"
GridCopyOption="IncludeHeaders"
GridPasteOption="None"
ShowGroupDropArea="True"
ShowRowHeader="True"
DataFetchSize="50">
<!-- Columns -->
</sync:SfDataGrid>
I add a new Item to the collection on a different view and then I save it to the datacontext and refresh the list:
private async void OnNewMyItemExecute()
{
MyItem= new MyItem();
MyItemsRepository.Add(MyItem);
var myItemsViewModel = TypeFactory
.Default
.CreateInstanceWithParametersAndAutoCompletion<myItemsViewModel >(MyItem); //the construction has parameters for IUIVisualizerService, IPleaseWaitService, etc.
if (await _UIVisualizerService.ShowDialogAsync(myItemsViewModel) ?? true)
{
var myItem= myItemsViewModel.MyItem;
await InitializeAsync();
MyItem = myItem;
}
else
{
_UnitOfWorkService.Rollback(); //just undo some changes
MyItem = null;
}
UnitOfWork.SaveChanges();
}
Creating a new Item is not a problem at all, the thing that is weird is that after I created a new Item and then attempt to filter grid on any column of the sfDataGrid (click the filter button in the column header, a filter popup opens, enter a value in the criteria textbox and click 'OK'), I get this:
MyProject.vshost.exe Warning: 0 : 17:57:49:075 => [WARNING]
[Catel.Services.UIVisualizerService] [8] An error occurred, returning
null since we don't know the result | [TargetInvocationException]
System.Reflection.TargetInvocationException: Exception has been thrown
by the target of an invocation. --->
System.Reflection.TargetInvocationException: Exception has been thrown
by the target of an invocation. ---> System.InvalidCastException:
Unable to cast object of type 'MyProject.Domain.MyItem' to type
'System.Data.Entity.DynamicProxies.MyItem_4CA6F59AB53174892ED9EFBC1D3CC07B862579FC3C5733C6CF4DE857907CFF9C'.
at lambda_method(Closure , MyItem ) --- 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.Delegate.DynamicInvokeImpl(Object[] args) at
System.Delegate.DynamicInvoke(Object[] args) at
Syncfusion.Data.QueryableCollectionView.<>c__DisplayClass3.b__1(Object
o) at Syncfusion.Data.QueryableCollectionView.FilterRecord(Object
record) at
Syncfusion.Data.EnumerableRecordsWrapper..ctor(IEnumerable source,
CollectionViewAdv view) at
Syncfusion.Data.EnumerableRecordsWrapper.CreateNew(IEnumerable source,
CollectionViewAdv view) at
Syncfusion.Data.QueryableCollectionView.CreateRecords() at
Syncfusion.Data.CollectionViewAdv.EnsureInitialized() at
Syncfusion.Data.CollectionViewAdv.get_Records() at
Syncfusion.Data.CollectionViewAdv.EnsureRecordsInitialized() at
Syncfusion.Data.CollectionViewAdv.Refresh() at
Syncfusion.Data.QueryableCollectionView.RefreshFilter() at
Syncfusion.Data.CollectionViewAdv.ApplyFilters() at
Syncfusion.Data.CollectionViewAdv.set_FilterPredicates(ObservableCollection1
value) at Syncfusion.UI.Xaml.Grid.GridModel.FilterColumn(GridColumn
column, List1 filterPredicates) at
Syncfusion.UI.Xaml.Grid.GridFilterControl.RefreshFilter() at
Syncfusion.UI.Xaml.Grid.GridFilterControl.b__10(Object
s, RunWorkerCompletedEventArgs e) at
System.ComponentModel.BackgroundWorker.OnRunWorkerCompleted(RunWorkerCompletedEventArgs
e) at
System.ComponentModel.BackgroundWorker.AsyncOperationCompleted(Object
arg) at
System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate
callback, Object args, Int32 numArgs) at
System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source,
Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.DispatcherOperation.InvokeImpl() at
System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(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.Windows.Threading.DispatcherOperation.Invoke() at
System.Windows.Threading.Dispatcher.ProcessQueue() at
System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32
msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at
MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam,
IntPtr lParam, Boolean& handled) at
MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o) at
System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate
callback, Object args, Int32 numArgs) at
System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source,
Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
at
System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority
priority, TimeSpan timeout, Delegate method, Object args, Int32
numArgs) at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd,
Int32 msg, IntPtr wParam, IntPtr lParam) at
MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg) at
System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame
frame) at
System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Window.ShowHelper(Object booleanBox) at
System.Windows.Window.Show() at System.Windows.Window.ShowDialog()
--- 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
Catel.Services.UIVisualizerService.<>c__DisplayClass23_0.b__0()
in
C:\CI_WS\Ws\86058\Source\Catel\src\Catel.MVVM\Catel.MVVM.Shared\Services\UIVisualizerService.cs:line
499
This is the method of UIVisualizerService with Line 499:
protected virtual bool? ShowWindow(FrameworkElement window, bool showModal)
{
if (showModal)
{
var showDialogMethodInfo = window.GetType().GetMethodEx("ShowDialog");
if (showDialogMethodInfo != null)
{
// Child window does not have a ShowDialog, so not null is allowed
bool? result = null;
window.Dispatcher.InvokeIfRequired(() =>
{
// Safety net to prevent crashes when this is the main window
try
{
result = showDialogMethodInfo.Invoke(window, null) as bool?; //Line 499
}
catch (Exception ex)
{
Log.Warning(ex, "An error occurred, returning null since we don't know the result");
}
});
return result;
}
Log.Warning("Method 'ShowDialog' not found on '{0}', falling back to 'Show'", window.GetType().Name);
}
I have tried opening MyItemsView with .ShowAsync(), .ShowDialogAsync() and before I upgraded to Catel 4.4 I also used .ShowDialog(), but it made no difference. I could turn Proxy Creation off in EF, but that would cause a lot of changes I have to make in my project (no more lazy loading for me, and that is not an option). I do believe the problem being the new Item I add not being a Dynamic Proxy, and getting it to be a Dynamic Proxy would probably solve the issue, but I have tried loading all the data from the DbContext again, but it also does not solve the problem.
Any advice would be appreciated.
The issue is this:
System.InvalidCastException: Unable to cast object of type 'MyProject.Domain.MyItem' to type 'System.Data.Entity.DynamicProxies.MyItem_4CA6F59AB53174892ED9EFBC1D3CC07B862579FC3C5733C6CF4DE857907CFF9C'.
The reason is, of course, that you are trying to cast a base type to a derived type (which it simply isn't). That this eventually results in the window closing is because an exception happens, but that isn't the real problem.
This exception occurs in the FilterRecord method of the grid. I am not sure if that is something you have written yourself or something that is inside syncfusion, but that is the place to look.
The reason you have generated proxies is because you enabled (or it's enabled by default) the proxy generation of the Entity Framework DbContext.
Using the the OAuthAuthorizationServer and OAuthClient samples, I am getting the following:
[ProtocolException: Unexpected response Content-Type text/html]
DotNetOpenAuth.Messaging.ErrorUtilities.VerifyProtocol(Boolean condition, String unformattedMessage, Object[] args) in c:\BuildAgent\work\1e6dbb6a394efdc4\src\DotNetOpenAuth.Core\Messaging\ErrorUtilities.cs:205
DotNetOpenAuth.Messaging.ErrorUtilities.ThrowProtocol(String unformattedMessage, Object[] args) in c:\BuildAgent\work\1e6dbb6a394efdc4\src\DotNetOpenAuth.Core\Messaging\ErrorUtilities.cs:238
DotNetOpenAuth.OAuth2.ChannelElements.OAuth2ClientChannel.ReadFromResponseCore(IncomingWebResponse response) in c:\BuildAgent\work\1e6dbb6a394efdc4\src\DotNetOpenAuth.OAuth2.Client\OAuth2\ChannelElements\OAuth2ClientChannel.cs:101
DotNetOpenAuth.Messaging.Channel.RequestCore(IDirectedProtocolMessage request) in c:\BuildAgent\work\1e6dbb6a394efdc4\src\DotNetOpenAuth.Core\Messaging\Channel.cs:750
DotNetOpenAuth.Messaging.Channel.Request(IDirectedProtocolMessage requestMessage) in c:\BuildAgent\work\1e6dbb6a394efdc4\src\DotNetOpenAuth.Core\Messaging\Channel.cs:536
DotNetOpenAuth.OAuth2.ClientBase.UpdateAuthorizationWithResponse(IAuthorizationState authorizationState, EndUserAuthorizationSuccessAuthCodeResponse authorizationSuccess) in c:\BuildAgent\work\1e6dbb6a394efdc4\src\DotNetOpenAuth.OAuth2.Client\OAuth2\ClientBase.cs:341
DotNetOpenAuth.OAuth2.WebServerClient.ProcessUserAuthorization(HttpRequestBase request) in c:\BuildAgent\work\1e6dbb6a394efdc4\src\DotNetOpenAuth.OAuth2.Client\OAuth2\WebServerClient.cs:164
OAuthClient._Default.Page_Load(Object sender, EventArgs e) in C:\SourceCode\Damikaa\DotNetAuthPoc\OAuthClient\Default.aspx.cs:37
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +25
System.Web.UI.Control.LoadRecursive() +71
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3064
Any one have any ideas?
The reason could be from the urls you have given for your AuthorizationEndpoint and TokenEndpoint and the url that you create request to it for getting your response.
Make sure that you have set the proper urls for these items.
Looks like a faulty authorization server. One that does not properly set the HTTP headers in its response.
I have written a simple SignalR hub:
public void PostUpdate(string message)
{
try
{
var update = URS.Tools.JsonSerializer.DeserializeFromJson<DataUpdate>(message);
switch (update.UpdateType)
{
case DataUpdateType.Opportunity:
Clients.All.UpdateOpportunity(update.DataUpdateId);
break;
case DataUpdateType.Contact:
Clients.All.UpdateContact(update.DataUpdateId);
break;
case DataUpdateType.Client:
Clients.All.UpdateClient(update.DataUpdateId);
break;
}
}
catch (Exception exception)
{
Logger.LogError(exception);
}
}
It is running with a Silverlight 5 client. For the most part it works, but after 5 - 30 minutes I get an error coming from withing the library:
Exception information:
Exception type: FormatException
Exception message: Invalid cursor.
at Microsoft.AspNet.SignalR.Messaging.Cursor.GetCursors(String cursor, Func`2 keyMaximizer)
at Microsoft.AspNet.SignalR.Messaging.DefaultSubscription..ctor(String identity, IEnumerable`1 eventKeys, TopicLookup topics, String cursor, Func`2 callback, Int32 maxMessages, IStringMinifier stringMinifier, IPerformanceCounterManager counters)
at Microsoft.AspNet.SignalR.Messaging.MessageBus.CreateSubscription(ISubscriber subscriber, String cursor, Func`2 callback, Int32 messageBufferSize)
at Microsoft.AspNet.SignalR.Messaging.MessageBus.Subscribe(ISubscriber subscriber, String cursor, Func`2 callback, Int32 maxMessages)
at Microsoft.AspNet.SignalR.Infrastructure.Connection.Receive(String messageId, Func`2 callback, Int32 maxMessages)
at Microsoft.AspNet.SignalR.Transports.ForeverTransport.ProcessMessages(ITransportConnection connection, Func`1 postReceive, Action`1 endRequest)
When I look at the packets, I cannot see a difference between the one just prior to the error that succeeds and the call that fails. It is running serverEvents transport, but I tried longPolling to no avail.
The exception is happening in the server.
Any ideas what could be causing the above error and/or how to resolve it?