ASP.NET Core on Linux problem with itextsharp - asp.net-mvc

We have a small ASP.NET Core 3.1 web app. We use itextsharp library (5.5.13) for generating a simple PDF and exporting it.
All works well in debug (and on Windows server), but when published on a Linux server (Debian 10) there is an error generating the PDF:
Error: The document has no pages.
Stack trace:
at iTextSharp.text.pdf.PdfPages.WritePageTree()
at iTextSharp.text.pdf.PdfWriter.Close()
at iTextSharp.text.pdf.PdfDocument.Close()
at iTextSharp.text.Document.Close()
at eDov.Web.Helpers.Reports.Dovolilnice.GetPdfTest() in C:\*\Reports\Dovolilnica.cs:line 173
at eDov.Web.Controllers.DovolilniceController.TestPdf(Int32 id) in C:\*\Controllers\DovolilniceController.cs:line 184
at lambda_method(Closure , Object , Object[] )
at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync() at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)
The code from the controller that is called to generate the PDF:
public IActionResult TestPdf(int id)
{
var file = new Dokument
{
Naziv = string.Format("Dovolilnica - {0}.pdf", id.ToString()),
Extension = ".pdf",
ContentType = "application/pdf",
};
//this is the line that the error from stack trace is referring
file.Contents = Helpers.Reports.Dovolililnice.GetPdfTest();
return File(file.Contents, file.ContentType, file.Naziv);
}
and the code that generates the PDF:
public static byte[] GetPdfTest()
{
byte[] result = null;
// custom velikost nalepke
// 1 inch = 72px
var pgSize = new iTextSharp.text.Rectangle(176f, 135f);
MemoryStream pdfData = new MemoryStream();
iTextSharp.text.Document document = new iTextSharp.text.Document(pgSize, 7.5f, 7.5f, 7.5f, 7.5f);
PdfWriter pdfWriter = PdfWriter.GetInstance(document, pdfData);
pdfWriter.ViewerPreferences = PdfWriter.PageModeUseOutlines;
document.Open();
document.Add(new Paragraph("Create test Pdf Document"));
pdfWriter.CloseStream = false;
document.Close();
//this is the line that the error from stack trace is referring
pdfData.Position = 0;
result = pdfData.ToArray();
pdfData.Dispose();
return result;
}
Has anyone used itextsharp (lower than version 7) successfully when publishing on Linux?

We couldn't get this working on Linux so we tried using iTextSharp.LGPLv2.Core port of the itextsharp library (see: https://github.com/VahidN/iTextSharp.LGPLv2.Core) and it works.
It's also available in Nuget PM.

Related

TikaOnDotNet with .NET Core 3.1 / .NET 5 fails with Method not found: 'Void System.IO.FileStream..ctor

With .NET Core 3.1 and .NET 5 I tried to reference the TikaOnDotNet NuGet package.
Sample code is as follows.
using System;
using System.IO;
using TikaOnDotNet.TextExtraction;
namespace tika
{
class Program
{
static void Main(string[] args)
{
var textExtractor = new TextExtractor();
var original = new FileInfo(Path.Combine(Directory.GetCurrentDirectory(), #"pptexamples.ppt"));
var wordDocContents = textExtractor.Extract(original.FullName);
}
}
}
In the textExtractor.Extract method it throws below exception.
TikaOnDotNet.TextExtraction.TextExtractionException: "Extraction of text from the file '/Users/serhatonal/Projects/tika/tika/bin/Debug/netcoreapp3.1/pptexamples.ppt' failed." ---> TikaOnDotNet.TextExtraction.TextExtractionException: "Extraction failed." ---> System.MissingMethodException: "Method not found: 'Void System.IO.FileStream..ctor(System.String, System.IO.FileMode, System.Security.AccessControl.FileSystemRights, System.IO.FileShare, Int32, System.IO.FileOptions)'."
at Java_java_io_FileDescriptor.open(String name, FileMode fileMode, FileAccess fileAccess)
at java.io.FileDescriptor.open(String , FileMode , FileAccess )
at java.io.FileDescriptor.open(String , Int32 , Int32 )
at java.io.FileDescriptor.openReadOnly(String )
at Java_java_io_RandomAccessFile.open0(Object _this, String name, Int32 mode, FileDescriptor fd, Int32 O_RDWR)
at java.io.RandomAccessFile.open0(String , Int32 )
at java.io.RandomAccessFile.open(String , Int32 )
at java.io.RandomAccessFile..ctor(File file, String mode)
at java.util.zip.ZipFile..ctor(File file, Int32 mode, Charset charset)
at java.util.zip.ZipFile..ctor(File file, Int32 mode)
at java.util.jar.JarFile..ctor(File file, Boolean verify, Int32 mode)
at java.util.jar.JarFile..ctor(String name)
at IKVM.NativeCode.ikvm.runtime.AssemblyClassLoader.lazyDefinePackages(ClassLoader _this)
at ikvm.runtime.AssemblyClassLoader.lazyDefinePackages()
at ikvm.runtime.AssemblyClassLoader.lazyDefinePackagesCheck()
at ikvm.runtime.AssemblyClassLoader.getPackage(String name)
at java.lang.Package.getPackage(Class )
at java.lang.Class.getPackage()
at org.apache.tika.mime.MimeTypesFactory.create(String coreFilePath, String extensionFilePath, ClassLoader classLoader)
at org.apache.tika.mime.MimeTypes.getDefaultMimeTypes(ClassLoader classLoader)
at org.apache.tika.config.TikaConfig.getDefaultMimeTypes(ClassLoader )
at org.apache.tika.config.TikaConfig..ctor()
at org.apache.tika.config.TikaConfig.getDefaultConfig()
at org.apache.tika.parser.AutoDetectParser..ctor()
at TikaOnDotNet.TextExtraction.Stream.StreamTextExtractor.Extract(Func`2 streamFactory, Stream outputStream)
--- End of inner exception stack trace ---
at TikaOnDotNet.TextExtraction.Stream.StreamTextExtractor.Extract(Func`2 streamFactory, Stream outputStream)
at TikaOnDotNet.TextExtraction.TextExtractor.Extract[TExtractionResult](Func`2 streamFactory, Func`3 extractionResultAssembler)
at TikaOnDotNet.TextExtraction.TextExtractor.Extract[TExtractionResult](String filePath, Func`3 extractionResultAssembler)
--- End of inner exception stack trace ---
at TikaOnDotNet.TextExtraction.TextExtractor.Extract[TExtractionResult](String filePath, Func`3 extractionResultAssembler)
at TikaOnDotNet.TextExtraction.TextExtractor.Extract(String filePath)
at tika.Program.Main(String[] args) in /Users/serhatonal/Projects/tika/tika/Program.cs:16
Even though I found out that issue "System.MissingMethodException: "Method not found: 'Void System.IO.FileStream..ctor(System.String, System.IO.FileMode, System.Security.AccessControl.FileSystemRights, System.IO.FileShare, Int32, System.IO.FileOptions)'."" is considered fixed with the .NET 5 release according to below issue. But the problem still persists.
https://github.com/dotnet/runtime/issues/30435
Anyone having the same issue?
IMVM the basis of the library, as this is a java port, is not dotnet
core compatible.
https://github.com/KevM/tikaondotnet/issues/136#issuecomment-583695410
Unfortunately, this is why.

Logging Response bodies in action filters

I have the following code in a class that implements IAsyncActionFilter using .Net Core.
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
await next.Invoke();
using (var reader = new StreamReader(context.HttpContext.Response.Body))
{
var responseBodyText = await reader.ReadToEndAsync();
var messageObjToLog = new
{
responseBody = responseBodyText,
statusCode = context.HttpContext.Response.StatusCode
};
_logger.LogInformation(JsonConvert.SerializeObject(messageObjToLog));
context.HttpContext.Response.Body.Seek(0, SeekOrigin.Begin);
}
}
This line:
using (var reader = new StreamReader(context.HttpContext.Response.Body))
produces the following error
fail: Microsoft.AspNetCore.Server.Kestrel[13]
Connection id "0HLFBE2K7NSD3", Request id "0HLFBE2K7NSD3:00000001": An
unhandled exception was thrown by the application.
System.ArgumentException: Stream was not readable. at
System.IO.StreamReader..ctor(Stream stream, Encoding encoding, Boolean
detectEncodingFromByteOrderMarks, Int32 bufferSize, Boolean leaveOpen)
at System.IO.StreamReader..ctor(Stream stream) at
Adapter.Logging.Middleware.LogResponseFilter.d__2.MoveNext()
in C:\src\Adapter\Logging\Middleware\LogRequestResponseFilter.cs:line
56
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__10.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 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.d__14.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.d__22.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext
context) at
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next,
Scope& scope, Object& state, Boolean& isCompleted) at
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.d__17.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.d__15.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.AspNetCore.Builder.RouterMiddleware.d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.AspNetCore.Hosting.Internal.RequestServicesContainerMiddleware.d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Frame`1.d__2.MoveNext()
My question is:
What do I need to do in order to safely reset the response stream?
I have another implementation of IAsyncActionFilter for logging:
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
using (var reader = new StreamReader(context.HttpContext.Request.Body))
{
var requestBodyText = await reader.ReadToEndAsync();
context.HttpContext.Request.EnableRewind();
context.HttpContext.Request.Body.Seek(0, SeekOrigin.Begin);
var messageObjToLog = new
{
scheme = context.HttpContext.Request.Scheme,
host = context.HttpContext.Request.Host,
path = context.HttpContext.Request.Path,
queryString = context.HttpContext.Request.Query,
requestBody = requestBodyText
};
_logger.LogInformation(JsonConvert.SerializeObject(messageObjToLog));
}
await next.Invoke();
}
Probably put "await next.Invoke();" at the end of the method.

not able to get values in entity framework sometimes(i suspect there is issue with context creation)

I am getting null in the below statement sometimes.
public GlobalEnums.AuthenticationResults Authenticate(UserLoginDTO Login, bool skipPolicy = false, bool skipUpdateLastLoggedOn = false)
{
try
{
using (var context = new eNextDALEntities())
{
List<tblUser> lstUser = context.tblUsers
.Where(usr => (string.Compare(usr.UserName, Login.UserName, true) == 0))
.ToList();
Int32 userCnt = lstUser.Count;
}
}
catch (System.Exception ex)
{
throw ex;
}
}
so it results in throwing error "Object reference not set to an instance of an object. "
It rarely shows this behavior.
I am unable to understand this strange behavior. It would be helpful if someone explains me why and how of this behavior or else point me in the right direction of how I can avoid this situation.
I think it might be related to context creation but not sure though. Even if it is how should I solve it.
Calling Code -
public HttpResponseMessage Authenticate()
{
IEnumerable<string> headerValues;
string userName = "";
if (Request.Headers.TryGetValues("UserName", out headerValues))
{
userName = headerValues.First();
}
UserLoginDTO user = new UserLoginDTO();
user.UserName = userName;
if (userName == "")
{
return ControllerContext.Request
.CreateResponse(HttpStatusCode.Unauthorized, "Please provide the credentials.");
}
GlobalEnums.AuthenticationResults _login = _repository.Authenticate(user);
if (!_login.Equals(GlobalEnums.AuthenticationResults.Authenticated))
{
return ControllerContext.Request
.CreateResponse(HttpStatusCode.Unauthorized, _login.ToString());
}
else
{
return ControllerContext.Request
.CreateResponse(HttpStatusCode.OK);
}
}
Also the point that I am thinking is even if username is null or wrong and it doesnt get any data then also context.tblUsers
.Where(usr => (string.Compare(usr.UserName, Login.UserName, true) == 0))
.ToList();
will return empty list but it will not return null. It can return null only if there is some issue with context
STACK TRACE:
Stack Trace: at LoginRepository.Authenticate(UserLoginDTO Login)
at Controllers.LoginController.Authenticate()
at lambdamethod(Closure , Object , Object[] )
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>cDisplayClass10.b9(Object instance, Object[] methodParameters)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary2 arguments, CancellationToken cancellationToken)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
at System.Web.Http.Controllers.ApiControllerActionInvoker.d0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
at System.Web.Http.Controllers.ExceptionFilterResult.d_0.MoveNext()

Catel UIVisualizerService issue with Syncfusion sfDatagrid

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.

Quartz.net - "Job's key cannot be null"

I'm trying to schedule a job on a remote scheduler using the following code:
NameValueCollection properties = new NameValueCollection();
properties["quartz.scheduler.instanceName"] = "RemoteClient";
// set thread pool info
properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz";
properties["quartz.threadPool.threadCount"] = "5";
properties["quartz.threadPool.threadPriority"] = "Normal";
// set remoting expoter
properties["quartz.scheduler.proxy"] = "true";
properties["quartz.scheduler.proxy.address"] = "tcp://127.0.0.1:555/QuartzScheduler";
// First we must get a reference to a scheduler
ISchedulerFactory sf = new StdSchedulerFactory(properties);
IScheduler sched = sf.GetScheduler();
// define the job and ask it to run
IJobDetail job = JobBuilder.NewJob<TestJob>()
.WithIdentity("remotelyAddedJob", "test")
.Build();
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("remotelyAddedTrigger", "test")
.ForJob(job)
.WithSchedule(CalendarIntervalScheduleBuilder.Create().WithIntervalInMinutes(1))
.Build();
// schedule the job
sched.ScheduleJob(job, trigger);
When I execute the code I get the following exception is thrown:
Quartz.SchedulerException was unhandled
Message=Job's key cannot be null
Source=mscorlib
StackTrace:
Server stack trace:
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at Quartz.Simpl.IRemotableQuartzScheduler.ScheduleJob(IJobDetail jobDetail, ITrigger trigger)
at Quartz.Impl.RemoteScheduler.ScheduleJob(IJobDetail jobDetail, ITrigger trigger) in D:\Data\ben\Projects\Utils\lahma-quartznet-b8cfbde\lahma-quartznet-b8cfbde\src\Quartz\Impl\RemoteScheduler.cs:line 424
at QuartzDemo.Program.Main(String[] args) in D:\Data\ben\Projects\demos\QuartzDemo\QuartzDemo\Program.cs:line 54
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.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
Everything works fine when using a local scheduler. The Quartz server is running as a service and listening on tcp port 555.
This is using the latest quartz.net code from github.
This was indeed a bug but it has been fixed. Do a new pull and you'll be good to go.
There are comments on the Quartz mailing list about issues with the database access in the 2.0 release.
From the syntax, it appears that you are using the 2.0 code base. It's not even released as beta yet. I hope this isn't a production system you're putting together.

Resources