I am making my first WPF application, where I use the Youtube .NET API to upload a video to Youtube using the ResumableUploader.
This ResumableUploader works asynchronously and provides an event AsyncOperationProgress to periodically report its progress percentage.
I want a ProgressBar that will display this progress percentage. Here is some of the code I have for that:
void BtnUpload_Click(object sender, RoutedEventArgs e) {
// generate video
uploader = new ResumableUploader();
uploader.AsyncOperationCompleted += OnDone;
uploader.AsyncOperationProgress += OnProgress;
uploader.InsertAsync(authenticator, newVideo.YouTubeEntry, new UserState());
}
void OnProgress(object sender, AsyncOperationProgressEventArgs e) {
Dispatcher.BeginInvoke((SendOrPostCallback)delegate {
PgbUpload.Value = e.ProgressPercentage;
}, DispatcherPriority.Background, null);
}
Where PgbUpload is my progress bar and the other identifiers are not important for the purpose of this question.
When I run this, OnProgress will be hit a few times, and then I will get a TargetParameterCountException. I have tried several different syntax for invoking the method asynchronously, none of which worked. I am sure the problem is the delegate because if I comment it out, the code works fine (but the ProgressBar isn't updated of course).
Here is the Exception Detail (partially in French):
System.Reflection.TargetParameterCountException
was unhandled Message=Nombre de
paramètres incorrects.
Source=mscorlib StackTrace:
à System.Reflection.RuntimeMethodInfo.Invoke(Object
obj, BindingFlags invokeAttr, Binder
binder, Object[] parameters,
CultureInfo culture, Boolean
skipVisibilityChecks)
à System.Delegate.DynamicInvokeImpl(Object[]
args)
à System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate
callback, Object args, Boolean
isSingleParameter)
à System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object
source, Delegate callback, Object
args, Boolean isSingleParameter,
Delegate catchHandler)
à System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate
callback, Object args, Boolean
isSingleParameter, Delegate
catchHandler)
à System.Windows.Threading.DispatcherOperation.InvokeImpl()
à System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object
state)
à System.Threading.ExecutionContext.runTryCode(Object
userData)
à System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode
code, CleanupCode backoutCode, Object
userData)
à System.Threading.ExecutionContext.RunInternal(ExecutionContext
executionContext, ContextCallback
callback, Object state)
à System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback
callback, Object state)
à System.Windows.Threading.DispatcherOperation.Invoke()
à System.Windows.Threading.Dispatcher.ProcessQueue()
à System.Windows.Threading.Dispatcher.WndProcHook(IntPtr
hwnd, Int32 msg, IntPtr wParam, IntPtr
lParam, Boolean& handled)
à MS.Win32.HwndWrapper.WndProc(IntPtr
hwnd, Int32 msg, IntPtr wParam, IntPtr
lParam, Boolean& handled)
à MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object
o)
à System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate
callback, Object args, Boolean
isSingleParameter)
à System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object
source, Delegate callback, Object
args, Boolean isSingleParameter,
Delegate catchHandler)
à System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate
callback, Object args, Boolean
isSingleParameter, Delegate
catchHandler)
à System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority
priority, TimeSpan timeout, Delegate
method, Object args, Boolean
isSingleParameter)
à System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority
priority, Delegate method, Object arg)
à MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr
lParam)
à MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG&
msg)
à System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame
frame)
à System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame
frame)
à System.Windows.Threading.Dispatcher.Run()
à System.Windows.Application.RunDispatcher(Object
ignore)
à System.Windows.Application.RunInternal(Window
window)
à System.Windows.Application.Run(Window
window)
à System.Windows.Application.Run()
à WpfApplication3.App.Main() dans h:\razor\documents\visual studio
2010\Projects\WpfApplication3\WpfApplication3\obj\x86\Debug\App.g.cs:ligne
0
à System.AppDomain._nExecuteAssembly(Assembly
assembly, String[] args)
à System.AppDomain.ExecuteAssembly(String
assemblyFile, Evidence
assemblySecurity, String[] args)
à Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
à System.Threading.ThreadHelper.ThreadStart_Context(Object
state)
à System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback
callback, Object state)
à System.Threading.ThreadHelper.ThreadStart()
InnerException:
Thanks for any help.
Edit: I just found out that if I don't use the Dispatcher and just call set the value directly, it works fine! Is OnProgress called on main UI thread? How can that be?
The uploader (or any async component) can sync with the thread that created it. There are probably a variety of ways to do this, but the one I've seen before goes like this:
public class ResumableUploader {
private SynchronizationContext _syncContext;
public event EventHandler<ProgressChangedEventArgs> OnProgressChanged;
public ResumableUploader() {
_syncContext = SynchronizationContext.Current; //Think of this as the current thread
}
private ReportProgressChanged(int progress) {
if(OnProgressChanged != null) {
_syncContext.Send(s => { OnProgressChanged(this, new ProgressChangedEventArgs(progress)); }, null); //s is any data you want to pass in, here it is unused
}
}
}
Or, slightly more flexible but also more complex for the user/client would be if the user/client supplied the SynchronizationContext at instance creation:
public ResumableUploader(SynchronizationContext syncContext)
Related
we have a Kiosk Application and print using the Microsoft.PointOfService SDK. In our development environment everything works.
EDIT
The following specifications:
Windows 10 Enterprise LTSC 1809
.NET 4.8
Pos for .NET 1.14.1
Printer: CUSTOM VKP80III
We're trying to print a simple text, nothing fancy. Like I said the same setup worked on the development machine. Even on the machine where it's not working now it worked but suddenly stopped working. We are considering deinstalling POS and OPOS driver and than try again.
But on the customer machine (same printer/SDK/application) we get the following Error:
UPOSDevice | Method TransactionPrint threw an exception. Service Object specific error. | Microsoft.PointOfService.PosControlException: Method TransactionPrint threw an exception. Service Object specific error.
at Microsoft.PointOfService.Legacy.LegacyProxy.ThrowLegacyMethodException(String methodName, Int32 ResultCode, Exception e)
at Microsoft.PointOfService.Legacy.LegacyProxy.InvokeMethod(String methodName, Object[]& parameters, Boolean[] byRef)
at Microsoft.PointOfService.Legacy.LegacyProxy.InvokeMethodAndCheckImpl(String methodName, Object[]& parameters, Boolean[] byRef)
at Microsoft.PointOfService.Legacy.LegacyProxy.InvokeMethodAndCheck(String methodName, Object param1, Object param2)
at Microsoft.PointOfService.Legacy.LegacyPosPrinter.TransactionPrint(PrinterStation station, PrinterTransactionControl control)
at UPOSPosPrinter.EndTransaction(PrinterStation station)
ErrorCode: 65535
ErrorCodeExtended: -1
The EndTransaction-Method looks like this:
public void EndTransaction(PrinterStation station)
{
try
{
_device.TransactionPrint((UPOSPrinterStation)station, PrinterTransactionControl.Normal);
}
catch (Exception ex)
{
_logger.LogError(ex, "CapTransactin: {CapTransaction} | ErrorMessage: {ErrorMessage}", _device.CapTransaction, ex.Message);
throw;
}
}
I couldn't even find a defintion for the ErrorCode: 65535. Does somebody know what the problem is or at least what the ErrorCode stands for?
The log from POsforNET:
[6/13/2022 1:47:47 PM 1 ERROR PosException] Microsoft.PointOfService.PosControlException: Method TransactionPrint threw an exception. Service Object specific error.
ErrorCode: Failure
ErrorCodeExtended: 0
Stack trace: at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
at System.Environment.get_StackTrace()
at Microsoft.PointOfService.PosException.GetExceptionText(Exception e)
at Microsoft.PointOfService.PosException.LogError()
at Microsoft.PointOfService.PosControlException..ctor(String message, ErrorCode errorCode, Int32 errorCodeExtended)
at Microsoft.PointOfService.Legacy.LegacyProxy.ThrowLegacyMethodException(String methodName, Int32 ResultCode, Exception e)
at Microsoft.PointOfService.Legacy.LegacyProxy.InvokeMethod(String methodName, Object[]& parameters, Boolean[] byRef)
at Microsoft.PointOfService.Legacy.LegacyProxy.InvokeMethodAndCheckImpl(String methodName, Object[]& parameters, Boolean[] byRef)
at Microsoft.PointOfService.Legacy.LegacyProxy.InvokeMethodAndCheck(String methodName, Object param1, Object param2)
at Microsoft.PointOfService.Legacy.LegacyPosPrinter.TransactionPrint(PrinterStation station, PrinterTransactionControl control)
at Test.Devices.UPOSPosPrinter.EndTransaction(PrinterStation station)
at Test.Devices.IPosPrinterExtension.PrintReceipt(IPosPrinter printer, CompositeElement template, ILogger logger)
at Test.Ticket.Controllers.PrinterController.<Print>d__6`1.MoveNext()
at System.Runtime.CompilerServices.AsyncVoidMethodBuilder.Start[TStateMachine](TStateMachine& stateMachine)
at Test.Ticket.Controllers.PrinterController.Print[TBonInfo](TBonInfo bonInfo, PrintLayoutType layoutType, String repeatAction, Nullable`1 layoutId)
at Test.Ticket.Controllers.PrinterController.PrintReceipt(Nullable`1 layoutId)
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 Test.Core.AppCommandPipeline.<>c__DisplayClass11_1.<ResolveAppCommand>b__0(RequestContext context)
at Test.Core.AppCommandPipeline.<<Build>b__16_0>d.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[TStateMachine](TStateMachine& stateMachine)
at Test.Core.AppCommandPipeline.<Build>b__16_0(RequestContext context)
at Test.Core.EventEmitterHandler.Invoke(RequestContext context)
at Test.Core.AppCommandPipelineMiddleware.<>c__DisplayClass3_1`1.<Add>b__1(RequestContext context)
at Test.Ticket.Middleware.ExceptionsHandler.<Invoke>d__3.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[TStateMachine](TStateMachine& stateMachine)
at Test.Ticket.Middleware.ExceptionsHandler.Invoke(RequestContext context)
at Test.Core.AppCommandPipelineMiddleware.<>c__DisplayClass3_1`1.<Add>b__1(RequestContext context)
at Test.Ticket.Middleware.AvailabilityUpdateHandler.Invoke(RequestContext context)
at Test.Core.AppCommandPipelineMiddleware.<>c__DisplayClass3_1`1.<Add>b__1(RequestContext context)
at Test.Ticket.Middleware.PermissionHandler.Invoke(RequestContext context)
at Test.Core.AppCommandPipelineMiddleware.<>c__DisplayClass3_1`1.<Add>b__1(RequestContext context)
at Test.Ticket.Middleware.AuthorizationHandler.Invoke(RequestContext context)
at Test.Core.AppCommandPipelineMiddleware.<>c__DisplayClass3_1`1.<Add>b__1(RequestContext context)
at Test.Ticket.Middleware.TimeOutHandler.Invoke(RequestContext context)
at Test.Core.AppCommandPipelineMiddleware.<>c__DisplayClass3_1`1.<Add>b__1(RequestContext context)
at Test.Core.AppCommandPipeline.ExecuteRequestContext[T](RequestContext requestContext, T& executionResult)
at Test.Core.AppCommandPipeline.Execute[T](AppCommand appCommand, T& executionResult, Object parameters)
at CallSite.Target(Closure , CallSite , AppCommandPipeline , AppCommand , Object& , Object )
at Test.Core.AppCommandPipeline.Execute(AppCommand appCommand, Object parameters)
at Test.Core.AppCommandPipeline.Execute(String appCommandString, Object parameters)
at Test.Core.AppEngine.ExecuteCommand(String appCommand)
at Test.Core.BaseController.<Execute>d__17.MoveNext()
at System.Runtime.CompilerServices.AsyncVoidMethodBuilder.Start[TStateMachine](TStateMachine& stateMachine)
at Test.Core.BaseController.Execute(String appCommand)
at Test.Ticket.Controllers.PaymentController.<Pay>d__11.MoveNext()
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.MoveNextRunner.InvokeMoveNext(Object stateMachine)
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.Runtime.CompilerServices.AsyncMethodBuilderCore.MoveNextRunner.Run()
at System.Threading.Tasks.SynchronizationContextAwaitTaskContinuation.<>c.<.cctor>b__8_0(Object state)
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 MS.Internal.CulturePreservingExecutionContext.CallbackWrapper(Object obj)
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 MS.Internal.CulturePreservingExecutionContext.Run(CulturePreservingExecutionContext 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.Application.RunDispatcher(Object ignore)
at System.Windows.Application.RunInternal(Window window)
at System.Windows.Application.Run(Window window)
at System.Windows.Application.Run()
at Test.Ticket.Desktop.App.Main()
The specification ErrorCode is a value in the range 0 or 101-115.
If the other value(65535) is notified, it is considered that the vendor who created the service object has defined some unique error and notified it.
ErrorCode Enumeration (POS for .NET v1.12 SDK Documentation)
Similarly, the value of ErrorCodeExtended will be vendor own definition.
Please refer to the include file on one of these sites for values.
CommonControlOnjects Current Version
kunif/OPOS-CCO
Please add the vendor and device model that creates the device and service object, as noted in the comments.
If anyone is using the same model from the same vendor, you may be able to share information.
However, you probably need to contact the vendor's support desk for more information.
According to the added vendor and model information:
The vendor page states that OPOS, OPOS.NET, and JavaPOS Driver are supported, but the list of downloads only had JavaPOS.
VKP80III
The problem was that we called
_device.TransactionPrint((UPOSPrinterStation)station, PrinterTransactionControl.Normal);
twice in a row. So we implemented a bool property to check if the printer is in "TransactionMode" or not and only call the TransactionPrint if this is true.
The actual problem why the printer didn't print was that the printer-driver didn't work. We had to reinstall the printer-driver. We assume a windows update was the culprit.
Another strange thing is that in other tests the same mechanism (calling the method twice) didn't produce an error. Very strange...
I try to implement crystal reports for wpf. If the user does not have the required runtime installed, a messagebox should pop up.
private void TryToInitializeReportViewer()
{
try
{
reportViewer = new CrystalReportsViewer
{
ShowExportButton = false,
ShowOpenFileButton = false,
ShowRefreshButton = false,
ShowCopyButton = false,
ShowStatusbar = true,
ShowLogo = false,
Visibility = Visibility.Collapsed
};
ViewerGrid.Children.Add(reportViewer);
}
catch (XamlParseException ex)
{
Log.GetInstance().Error(LogUtil.Customize("ReportViewer konnte nicht initislisiert werden"), ex);
MessageBox.Show(
"Das Ausgabeformat 'REPORT' ist nicht verfügbar, da die CrystalReports Runtime nicht installiert ist", "Achtung", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
For some reason the first MessageBox I want to open leads to a InvalidCastException with the following stacktrace:
bei SAPBusinessObjects.WPF.Viewer.PageNumberDisplayConverter.Convert(Object[] value, Type targetType, Object parameter, CultureInfo culture)
bei System.Windows.Data.MultiBindingExpression.TransferValue()
bei System.Windows.Data.MultiBindingExpression.Transfer()
bei System.Windows.Data.MultiBindingExpression.UpdateTarget(Boolean includeInnerBindings)
bei System.Windows.Data.MultiBindingExpression.AttachToContext(Boolean lastChance)
bei System.Windows.Data.MultiBindingExpression.MS.Internal.Data.IDataBindEngineClient.AttachToContext(Boolean lastChance)
bei MS.Internal.Data.DataBindEngine.Task.Run(Boolean lastChance)
bei MS.Internal.Data.DataBindEngine.Run(Object arg)
bei System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
bei System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
bei System.Windows.Threading.DispatcherOperation.InvokeImpl()
bei System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
bei System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
bei System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
bei System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
bei MS.Internal.CulturePreservingExecutionContext.Run(CulturePreservingExecutionContext executionContext, ContextCallback callback, Object state)
bei System.Windows.Threading.DispatcherOperation.Invoke()
bei System.Windows.Threading.Dispatcher.ProcessQueue()
bei System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
bei MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
bei MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
bei System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
bei System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
bei System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
bei MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
bei MS.Win32.UnsafeNativeMethods.MessageBox(HandleRef hWnd, String text, String caption, Int32 type)
bei System.Windows.MessageBox.ShowCore(IntPtr owner, String messageBoxText, String caption, MessageBoxButton button, MessageBoxImage icon, MessageBoxResult defaultResult, MessageBoxOptions options)
bei System.Windows.MessageBox.Show(String messageBoxText, String caption, MessageBoxButton button, MessageBoxImage icon)
bei SapReportViewer.MainWindow.TryToInitializeReportViewer() in C:\Users\KlammerT\Documents\Visual Studio 2013\Projects\SapReportViewer\WpfApplication8\MainWindow.xaml.cs:Zeile 108.
bei SapReportViewer.MainWindow..ctor() in C:\Users\KlammerT\Documents\Visual Studio 2013\Projects\SapReportViewer\WpfApplication8\MainWindow.xaml.cs:Zeile 73.
If I catch the InvalidCastException and try to show another MessageBox it works perfectly.
Anybody an idea?
ok I have a WPF program that works on one computer but not the another. on the other one, I get this MethodAccessException was unhandled
it is when the problem calls NotifyPropertyChanged():
public abstract class NotifyChanged: INotifyPropertyChanged {
#region INotifyPropertyChanged
/// <summary>
/// PropertyChanged can be triggered whenever a Property changes value.
/// It is also available for classes which inherit from
MachineComponent.
/// </summary>
public virtual event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// NotifyPropertyChanged can be called explicitly, by sending the name
of the property as a string,
/// or implicitly, by calling it without parameters from the Property
that changes.
/// </summary>
/// <param name="info"></param>
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design",
"CA1026:DefaultParametersShouldNotBeUsed" )]
protected void NotifyPropertyChanged( [CallerMemberName] string info = "none passed" ) {
if ( PropertyChanged != null ) {
PropertyChanged( this, new PropertyChangedEventArgs( info ) );
}
}
#endregion
anyone know why ?
I am told this code come from a Microsoft site
Update.. I am adding the full error message. now this is a run time error message
full error message:
System.MethodAccessException was unhandled
HResult=-2146233072
Message=Attempt by method
'Moxtek.XRF.Core.LocationViewModel.set_LocationName(System.String)' to
access method
'Moxtek.Common.Abstract.NotifyChanged.NotifyPropertyChanged(System.String)'
failed.
Source=Moxtek.XRF.Core
StackTrace:
at Moxtek.XRF.Core.LocationViewModel.set_LocationName(String value) in C:\Users\lolsen\Source\XRF\Moxtek.XRF.Core\ViewModels\MeasurementRecipeViewModels\LocationViewModel.cs:line 41
at Moxtek.XRF.Core.LocationViewModel..ctor(XrfLocationSet location, LocationItemViewModel locationItem, MeasurementRecipeItemViewModel recipeItem, IDataObject`1 locationData, IServiceLocator services) in C:\Users\lolsen\Source\XRF\Moxtek.XRF.Core\ViewModels\MeasurementRecipeViewModels\LocationViewModel.cs:line 12
at Moxtek.XRF.Core.LocationItemViewModel.GetItems() in C:\Users\lolsen\Source\XRF\Moxtek.XRF.Core\ViewModels\MeasurementRecipeViewModels\LocationItemViewModel.cs:line 36
at Moxtek.XRF.Core.LocationItemViewModel..ctor(IDataObject`1 locationData, MeasurementRecipeItemViewModel recipeItem, IServiceLocator services) in C:\Users\lolsen\Source\XRF\Moxtek.XRF.Core\ViewModels\MeasurementRecipeViewModels\LocationItemViewModel.cs:line 14
at Moxtek.XRF.Core.XrfViewModel..ctor(ChartingViewModel chart, IServiceLocator services) in C:\Users\lolsen\Source\XRF\Moxtek.XRF.Core\ViewModels\XrfViewModel.cs:line 29
at Moxtek.XRF.WPF.App.OnStartup(StartupEventArgs e) in C:\Users\lolsen\Source\XRF\Moxtek.XRF.WPF\App.xaml.cs:line 46
at System.Windows.Application.<.ctor>b__1_0(Object unused)
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.Application.RunDispatcher(Object ignore)
at System.Windows.Application.RunInternal(Window window)
at System.Windows.Application.Run(Window window)
at System.Windows.Application.Run()
at Moxtek.XRF.WPF.App.Main()
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.Runtime.Hosting.ManifestRunner.Run(Boolean checkAptModel)
at System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly()
at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData)
at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext)
at System.Activator.CreateInstance(ActivationContext activationContext)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()
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:
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Best way to convert pdf files to tiff files
I'm looking for a free library that allows me to convert a PDF document to a (or several) TIFF images. If Tiff is not possible it can also be other images formats.
I read about a way to do this with Ghostscript, but I couldn't find a good explanation. So any hints how to do that?
EDIT:
According to the comment I use this command to execute:
Process.Start("gswin32c", "-dNOPAUSE -q -sDEVICE=tiffg4 -dBATCH -sOutputFile=" + fileName + ".tif " + fileName + ".pdf");
I see that GhostScript is executed in the command line, But I always get an error:
System.ArgumentException was unhandled
Message=The contact with id '16778241' does not currently exist.
Parameter name: contact
Source=Microsoft.Surface.Presentation
ParamName=contact
StackTrace:
at Microsoft.Surface.Presentation.Contacts.CheckIfCanBeCapturedOrReleased(Contact contact)
at Microsoft.Surface.Presentation.Contacts.CaptureContact(Contact contact, IInputElement element)
at Microsoft.Surface.Presentation.Controls.Primitives.ButtonBaseAdapter.OnContactDown(ContactEventArgs e)
at Microsoft.Surface.Presentation.Controls.SurfaceButton.OnContactDown(ContactEventArgs e)
at Microsoft.Surface.Presentation.Controls.SurfaceButton.Microsoft.Surface.Presentation.Controls.IContactEventThunk.OnContactDownThunk(ContactEventArgs e)
at Microsoft.Surface.Presentation.Controls.InputElementAdapter.OnContactDownThunk(Object sender, ContactEventArgs e)
at Microsoft.Surface.Presentation.ContactEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
at System.Windows.Input.InputManager.ProcessStagingArea()
at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
at Microsoft.Surface.Presentation.InputSurfaceProviderBase.DoProcessInput(Object obj)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
at System.Windows.Threading.DispatcherOperation.InvokeImpl()
at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
at System.Threading.ExecutionContext.runTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
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, Boolean isSingleParameter)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter)
at System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg)
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.Threading.Dispatcher.Run()
at System.Windows.Application.RunDispatcher(Object ignore)
at System.Windows.Application.RunInternal(Window window)
at System.Windows.Application.Run(Window window)
at System.Windows.Application.Run()
at Prototype_Concept_2.App.Main() in C:\Users\Roflcoptr\Documents\Visual Studio 2008\Projects\Prototype_Concept_2\Prototype_Concept_2\obj\Debug\App.g.cs:line 0
at System.AppDomain._nExecuteAssembly(Assembly 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)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
Why this?
You cannot use the Process.Start(string filename) overload to supply command line parameters. From MSDN:
This overload does not allow command-line arguments for the process. If you need to specify one or more command-line arguments for the process, use the Process.Start(ProcessStartInfo) or Process.Start(String, String) overloads.
http://msdn.microsoft.com/en-us/library/53ezey2s.aspx
So try the following instead:
Process.Start(#"C:\Users\Roflcoptr\Documents\Visual Studio 2008\Projects\Prototype_Concept_2\Prototype_Concept_2\bin\Debug\gswin32c", "-dNOPAUSE -q -g300x300 -sDEVICE=tiffg4 -dBATCH -sOutputFile=Report_22_02_2011_21_18.tif Report_22_02_2011_21_18.pdf");
Can you post up the Process.Start() line of code?
I am guessing the error of file not found is coming from the path being incorrect. That being missing the quotes. Because of the space in visual and studio it would assume that "C:\Users\Roflcoptr\Documents\Visual" is the directory.
Process.Start(#"\"C:\Users\Roflcoptr\Documents\Visual Studio 2008\Projects\Prototype_Concept_2\Prototype_Concept_2\bin\Debug\gswin32c\" -dNOPAUSE -q -g300x300 -sDEVICE=tiffg4 -dBATCH -sOutputFile=Report_22_02_2011_21_18.tif Report_22_02_2011_21_18.pdf");
The best way to test this, maybe to first fire up a command prompt and see if you can run that command line successfully before using it in Process.Start() method call.
I try to load a assembly into my source code in C#. So i first compile the source file:
private bool testAssemblies(String sourceName)
{
FileInfo sourceFile = new FileInfo(sourceName);
CodeDomProvider provider = null;
bool compileOk = false;
// Select the code provider based on the input file extension.
if (sourceFile.Extension.ToUpper(CultureInfo.InvariantCulture) == ".CS")
{
provider = CodeDomProvider.CreateProvider("CSharp");
}
else if (sourceFile.Extension.ToUpper(CultureInfo.InvariantCulture) == ".VB")
{
provider = CodeDomProvider.CreateProvider("VisualBasic");
}
else
{
Console.WriteLine("Source file must have a .cs or .vb extension");
}
if (provider != null)
{
// Format the executable file name.
// Build the output assembly path using the current directory
// and <source>_cs.exe or <source>_vb.exe.
String exeName = String.Format(#"{0}\{1}.exe",
System.Environment.CurrentDirectory,
sourceFile.Name.Replace(".", "_"));
CompilerParameters cp = new CompilerParameters();
// Generate an executable instead of
// a class library.
cp.GenerateExecutable = true;
// Specify the assembly file name to generate.
cp.OutputAssembly = exeName;
// Save the assembly as a physical file.
cp.GenerateInMemory = false;
// Set whether to treat all warnings as errors.
cp.TreatWarningsAsErrors = false;
// Invoke compilation of the source file.
CompilerResults cr = provider.CompileAssemblyFromFile(cp,
sourceName);
if (cr.Errors.Count > 0)
{
// Display compilation errors.
Console.WriteLine("Errors building {0} into {1}",
sourceName, cr.PathToAssembly);
foreach (CompilerError ce in cr.Errors)
{
Console.WriteLine(" {0}", ce.ToString());
Console.WriteLine();
}
}
else
{
// Display a successful compilation message.
Console.WriteLine("Source {0} built into {1} successfully.",
sourceName, cr.PathToAssembly);
}
// Return the results of the compilation.
if (cr.Errors.Count > 0)
{
compileOk = false;
}
else
{
compileOk = true;
}
}
return compileOk;
}
This works well, but if I later try to load the assembly, I always get an exception:
System.Reflection.TargetInvocationException was unhandled
Message=Exception has been thrown by the target of an invocation.
Source=mscorlib
StackTrace:
at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Delegate.DynamicInvokeImpl(Object[] args)
at Microsoft.Surface.Shell.ApiEventManager.EventSubscriberInfo.InvokeCallback(Object arg)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
at System.Windows.Threading.DispatcherOperation.InvokeImpl()
at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
at System.Threading.ExecutionContext.runTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
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, Boolean isSingleParameter)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter)
at System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg)
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.Threading.Dispatcher.Run()
at System.Windows.Application.RunDispatcher(Object ignore)
at System.Windows.Application.RunInternal(Window window)
at System.Windows.Application.Run(Window window)
at System.Windows.Application.Run()
at Prototype_Ver1.App.Main() in C:\Users\Roflcoptr\Documents\Visual Studio 2008\Projects\Prototype_Ver1\Prototype_Ver1\obj\Debug\App.g.cs:line 0
at System.AppDomain._nExecuteAssembly(Assembly 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)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.IO.FileLoadException
Message=Could not load file or assembly 'C:\\Users\\Roflcoptr\\Desktop\\hello.cs' or one of its dependencies. The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)
Source=mscorlib
FileName=C:\\Users\\Roflcoptr\\Desktop\\hello.cs
FusionLog=""
StackTrace:
at System.Reflection.AssemblyName.nInit(Assembly& assembly, Boolean forIntrospection, Boolean raiseResolveEvent)
at System.Reflection.Assembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection)
at System.Reflection.Assembly.Load(String assemblyString)
at Prototype_Ver1.SurfaceWindow1.OnApplicationActivated(Object sender, EventArgs e) in C:\Users\Roflcoptr\Documents\Visual Studio 2008\Projects\Prototype_Ver1\Prototype_Ver1\MainWindow.xaml.cs:line 91
InnerException:
My loading Method looks like this:
if (testAssemblies("C:\\Users\\Roflcoptr\\Desktop\\hello.cs"))
{
Assembly a = Assembly.Load("C:\\Users\\Roflcoptr\\Documents\\Visual Studio 2008\\Projects\\Prototype_Ver1\\Prototype_Ver1\\bin\\Debug\\hello_cs.exe");
}
Any ideas why it doesnt work?
I think your syntax is wrong. Assembly.load(string) expects the assembly name
Assembly.Load("SampleAssembly, Version=1.0.2004.0, Culture=neutral, PublicKeyToken=8744b20f8da049e3");
Also make sure you're using the right overload for your needs (which usually is indeed Assembly.Load)
Link
EDIT use this:
AssemblyName an = AssemblyName.GetAssemblyName(filePath);
Assembly.Load(an);