Load assembly doesn't worked correctly - c#

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

Related

TransactionPrint Method of POSPrinter throws Exception

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...

VS2015 XAML Designer always System.UnauthorizedAccessException

I having VS2015 and experiencing XAML Designer error of System.UnauthorizedAccessException. I am running on Windows 10 build 10586.
I don't experience the error when I deleted some of the files from the Project. Once I build the project, the UWP app running and the debugger and XAML Designer start to throw error like below:
System.UnauthorizedAccessException
Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
at System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMarkHandle stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName, ObjectHandleOnStack type)
at System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName)
at System.Runtime.DesignerServices.WindowsRuntimeDesignerContext.GetType(String typeName)
at Microsoft.VisualStudio.DesignTools.Utility.WindowsRuntimeService.WindowsRuntimeContext.GetTypeFromWindowsRuntimeDesignerContext(String name)
at Microsoft.VisualStudio.DesignTools.Utility.WindowsRuntimeService.GetRuntimeType(String typeFullName)
at Microsoft.VisualStudio.DesignTools.XamlDesigner.Metadata.MockTypes.EmitContext.GetTypeFromRuntimeService(Type type)
at Microsoft.VisualStudio.DesignTools.XamlDesigner.Metadata.MockTypes.EmitContext.GetPlatformTypeInternal(Type type, Func`2 getPlatformType)
at Microsoft.VisualStudio.DesignTools.XamlDesigner.Metadata.MockTypes.EmitContext.GetPlatformTypeInternal(Type type)
at Microsoft.VisualStudio.DesignTools.XamlDesigner.Metadata.MockTypes.EmitContext.GetPlatformType(Type type)
at Microsoft.VisualStudio.DesignTools.XamlDesigner.Metadata.MockTypes.MockTypeGenerator.GetKnownType(Type type)
at Microsoft.VisualStudio.DesignTools.XamlDesigner.Metadata.MockTypes.MockTypeGenerator.DefineType(Type type)
at Microsoft.VisualStudio.DesignTools.XamlDesigner.Metadata.MockTypes.MockTypeGenerator.MockType(Type type)
at Microsoft.VisualStudio.DesignTools.XamlDesigner.Metadata.MockType.InitializeMockType()
at Microsoft.VisualStudio.DesignTools.XamlDesigner.Metadata.MockType.get_RuntimeType()
at Microsoft.VisualStudio.DesignTools.Platform.Metadata.ProjectContextType.InitializeClass()
at Microsoft.VisualStudio.DesignTools.Platform.Metadata.MemberCollection.get_AttachedPropertyIndex()
at Microsoft.VisualStudio.DesignTools.Platform.Metadata.MemberCollection.CreateAttachedProperty(String propertyName, MemberKey& key)
at Microsoft.VisualStudio.DesignTools.Platform.Metadata.MemberCollection.CreateMember(MemberType memberTypes, String memberName, MemberKey& key)
at Microsoft.VisualStudio.DesignTools.Platform.Metadata.MemberCollection.TryGetCachedMember(MemberType memberTypes, String memberName, Boolean create, IMember& member)
at Microsoft.VisualStudio.DesignTools.Platform.Metadata.MemberCollection.GetMember(MemberType memberTypes, String memberName, MemberAccessTypes access)
at Microsoft.VisualStudio.DesignTools.Platform.Metadata.ProjectContextType.GetMember(MemberType memberTypes, String memberName, MemberAccessTypes access)
at Microsoft.VisualStudio.DesignTools.Designer.UI.PropertyMerger.GetPropertiesFromSelection(IEnumerable`1 selectedSceneNodes, Boolean includeStatics)
at Microsoft.VisualStudio.DesignTools.Designer.UI.PropertyMerger.GetMergedProperties(IEnumerable`1 selectedSceneNodes, Boolean includeStatics)
at Microsoft.VisualStudio.DesignTools.Designer.UI.PropertyInspector.PropertyInspectorModel.GetPropertiesToShowInternal(IReadOnlyList`1 selectedObjects)
at Microsoft.VisualStudio.DesignTools.Designer.UI.PropertyInspector.PropertyInspectorModel.GetRenderedProperties(IReadOnlyList`1 selectedObjects)
at Microsoft.VisualStudio.DesignTools.Designer.UI.PropertyInspector.PropertyInspectorModel.UpdateOnSelectionChanged(Boolean forceUpdate, Boolean shouldCloseOpenTransactions, Boolean clearAddedProperties)
at Microsoft.VisualStudio.DesignTools.Designer.UI.PropertyInspector.PropertyInspectorModel.UpdateSelectionCore(Boolean forceUpdate, Boolean shouldCloseOpenTransactions, Boolean clearAddedProperties)
at Microsoft.VisualStudio.DesignTools.Designer.UI.PropertyInspector.PropertyInspectorModel.UpdateSelection(Boolean forceUpdate, Boolean shouldCloseOpenTransactions, Boolean clearAddedProperties)
at Microsoft.VisualStudio.DesignTools.Designer.UI.PropertyInspector.PropertyInspectorModel.PropertyManager_MultiplePropertyReferencesChanged(Object sender, MultiplePropertyReferencesChangedEventArgs args)
at Microsoft.VisualStudio.DesignTools.Designer.Properties.PropertyManager.FireAllPropertyChangedEvents(SceneUpdatePhaseEventArgs args)
at Microsoft.VisualStudio.DesignTools.Designer.Properties.PropertyManager.SelectionManager_LateActiveSceneUpdatePhase(Object sender, SceneUpdatePhaseEventArgs args)
at Microsoft.VisualStudio.DesignTools.Designer.ViewModel.SceneUpdatePhaseEventHandler.Invoke(Object sender, SceneUpdatePhaseEventArgs e)
at Microsoft.VisualStudio.DesignTools.Designer.Selection.SelectionManager.FireLateActiveSceneUpdatePhase(SceneUpdatePhaseEventArgs args)
at Microsoft.VisualStudio.DesignTools.Designer.View.SceneViewUpdateScheduleTask.UpdateLate()
at Microsoft.VisualStudio.DesignTools.Utility.Scheduler.ScheduleTask.Update()
at Microsoft.VisualStudio.DesignTools.Utility.Scheduler.SchedulingService.DispatchTasksAtPriority(DispatcherPriority priority)
at Microsoft.VisualStudio.DesignTools.Utility.Scheduler.SchedulingService.DispatcherToken.Dispatch(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.Application.RunDispatcher(Object ignore)
at System.Windows.Application.RunInternal(Window window)
at System.Windows.Application.Run(Window window)
at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.DesignerProcess.RunApplication()
at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.DesignerProcess.DesignProcessViewProvider.AppContainerDesignerProcessRun(String[] activationContextArgs)
at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.DesignerProcess.DesignProcessViewProvider.<>c__DisplayClass3_0.<applicationView_Activated>b__0()
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()
I am not able to see the properties of the element Grid even the syntax as simple as below:
<Page
x:Class="mstesting.BlankPage1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:mstesting"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
</Grid>
</Page>
I already enabled Developer Mode at the Windows 10.
Update to VS2015 Update 1 definitely fixed up this issue.
From the error message, the user does not have the permission. You could let the application pool under a suitable account (such as LocalSystem).
Here is a Link about this quesiton.

How to convert PDF to TIF with GhostScript? [duplicate]

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.

XamlParseException was unhandled C# app

I received this error randomly and I don't know how to fix it seeming as the cause of the problem happened out of random.
Can anyone guide me on what I should be looking for, I think it points to my XAML code but I don't know what I should be looking at.
System.Windows.Markup.XamlParseException was unhandled
Message=Cannot create instance of 'MainWindow' defined in assembly 'Shutdown Timer, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null'. Exception has been thrown by the target of an invocation. Error in markup file 'Shutdown Timer;component/MainWindow.xaml'.
Source=PresentationFramework
LineNumber=0
LinePosition=0
StackTrace:
at System.Windows.Markup.XamlParseException.ThrowException(String message, Exception innerException, Int32 lineNumber, Int32 linePosition, Uri baseUri, XamlObjectIds currentXamlObjectIds, XamlObjectIds contextXamlObjectIds, Type objectType)
at System.Windows.Markup.XamlParseException.ThrowException(ParserContext parserContext, Int32 lineNumber, Int32 linePosition, String message, Exception innerException)
at System.Windows.Markup.BamlRecordReader.CreateInstanceFromType(Type type, Int16 typeId, Boolean throwOnFail)
at System.Windows.Markup.BamlRecordReader.GetElementAndFlags(BamlElementStartRecord bamlElementStartRecord, Object& element, ReaderFlags& flags, Type& delayCreatedType, Int16& delayCreatedTypeId)
at System.Windows.Markup.BamlRecordReader.BaseReadElementStartRecord(BamlElementStartRecord bamlElementRecord)
at System.Windows.Markup.BamlRecordReader.ReadElementStartRecord(BamlElementStartRecord bamlElementRecord)
at System.Windows.Markup.BamlRecordReader.ReadRecord(BamlRecord bamlRecord)
at System.Windows.Markup.BamlRecordReader.Read(Boolean singleRecord)
at System.Windows.Markup.TreeBuilderBamlTranslator.ParseFragment()
at System.Windows.Markup.TreeBuilder.Parse()
at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
at System.Windows.Application.LoadBamlStreamWithSyncInfo(Stream stream, ParserContext pc)
at System.Windows.Application.DoStartup()
at System.Windows.Application.<.ctor>b__0(Object unused)
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.DispatcherOperation.InvokeImpl()
at System.Threading.ExecutionContext.runTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
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.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter)
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.TranslateAndDispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Application.RunInternal(Window window)
at Shutdown_Timer.App.Main() in D:\Documents\Expression\Blend 4\Projects\Shutdown Timer\Shutdown Timer\obj\x64\Release\App.g.cs:line 0
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.Reflection.TargetInvocationException
Message=Exception has been thrown by the target of an invocation.
Source=mscorlib
StackTrace:
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache)
at System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.Windows.Markup.BamlRecordReader.CreateInstanceFromType(Type type, Int16 typeId, Boolean throwOnFail)
InnerException: System.NullReferenceException
Message=Object reference not set to an instance of an object.
Source=Shutdown Timer
StackTrace:
at Shutdown_Timer.MainWindow..ctor() in D:\Documents\Expression\Blend 4\Projects\Shutdown Timer\Shutdown Timer\MainWindow.xaml.cs:line 128
InnerException:
Thanks in advance.
You have a bug on line 128 of your code-behind.
EDIT: pinFix is probably null.

WPF ProgressBar - TargetParameterCountException

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)

Categories

Resources