2012-11-07 52 views
0

我有一個WPF應用程序掛鉤到我也在寫入的DLL。該DLL掃描第三方應用程序的數據文件夾並處理其中的所有數據解釋。 WPF將提供一個很好的GUI;我將它們分開,因爲它將來也可能需要爲它寫一個命令行界面。c#序列化類 - WPF主窗口異常發生

對數據文件夾的掃描需要一些時間,所以我想保存對象(一個Repository)的狀態並打開它,而不是數據文件夾已被掃描並保留相同的「上次修改」狀態。我已經將Repository對象標記爲[Serializable],但是當我試圖保存狀態(來自WPF或DLL)時,我得到一個WPF MainWindow不是[Serializable]的異常。

如果我讀了創建的.dat文件,它確實有一些(不知道是否全部)來自該類的信息。

我不明白爲什麼它會試圖保存有關WPF窗口的任何信息。我試圖將該窗口標記爲[Serializable],只是爲了嘗試該類不允許它。在網上搜索讓我看着AppDomain,因爲我正在加載一個DLL以及應用程序,但這有點超出我的想象。以下是我目前正在嘗試實施它的方式。編輯:對序列化的調用是在WPF代碼的底部。

我應該提到,我在WPF名稱空間內創建了一個內聯類,並且能夠成功將其序列化爲一個文件。

任何幫助表示讚賞。

這是DLL:

namespace HPOO_XML_Parser 
{ 
[Serializable] 
public class HPOORepository 
{ 

    string _version; 
    string _path; 
    string _library; 
    string _uuid; 


    [NonSerialized] 
    BackgroundWorker bWorker = new BackgroundWorker(); 
    [NonSerialized] 
    XElement _xmlRepo;  


    int _nodeCount; 
    List<Node> nodes; 
    ... 
    Rest of properties and methods 
} 

並調用它

namespace HPOO_Repository_Scanner 
{ 
/// <summary> 
/// Interaction logic for MainWindow.xaml 
/// </summary> 
public partial class MainWindow : Window 
{ 
    HPOORepository repo; 

    public MainWindow() 
    { 
     InitializeComponent(); 
     StatusVisibility(); // Simply hides progress bar/cancel button 
    } 

    private void OpenRepository(object sender, RoutedEventArgs e) 
    { 

     string ooHome; 
     using (FolderBrowserDialog browser = new FolderBrowserDialog()) 
     { 
      ooHome = Environment.GetEnvironmentVariable("ICONCLUDE_HOME"); 
      if (ooHome != null) 
      { 
       browser.SelectedPath = ooHome; 
      } 
      browser.ShowNewFolderButton = false; 
      browser.Description = "Select a repository to open..."; 

      if (browser.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
      { 
       try 
       { 
        repo = new HPOORepository(browser.SelectedPath); 
       } 
       catch (Exception ex) 
       { 
        System.Windows.MessageBox.Show(ex.Message, "Invalid Repository Selected", MessageBoxButton.OK, MessageBoxImage.Error); 

       } 
      } 
      repo.ProgressChanged += new ProgressChangedEventHandler(repo_ProgressChanged); 

      prgStatus.Maximum = 100; 

      repo.ReadRepository(); 

     } 

    } 
private void mnuSave_Click(object sender, RoutedEventArgs e) 
    { 
     SaveRepo(repo); 
    } 

    public void SaveRepo(object repository) 
    { 
     BinaryFormatter binFormat = new BinaryFormatter(); 

     using (Stream fStream = new FileStream("test" + ".dat", 
      FileMode.Create, FileAccess.Write, FileShare.None)) 
     { 
      binFormat.Serialize(fStream, repository); 
     } 
    } 

編輯WPF:最後例外:

System.Runtime.Serialization.SerializationException was unhandled 
Message=Type 'HPOO_Repository_Scanner.MainWindow' in Assembly 'HPOO Repository Scanner, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable. 
Source=mscorlib 
StackTrace: 


    at System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers(RuntimeType type) 
     at System.Runtime.Serialization.FormatterServices.GetSerializableMembers(Type type, StreamingContext context) 
     at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitMemberInfo() 
     at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter) 
     at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.Serialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter) 
     at System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Write(WriteObjectInfo objectInfo, NameInfo memberNameInfo, NameInfo typeNameInfo) 
     at System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(Object graph, Header[] inHeaders, __BinaryWriter serWriter, Boolean fCheck) 
     at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph, Header[] headers, Boolean fCheck) 
     at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph) 
     at HPOO_Repository_Scanner.MainWindow.SaveRepo(Object repository) in \\tsclient\D\Dropbox\_Work\Visual Studio Projects\HPOO Repository Scanner\HPOO Repository Scanner\HPOO Repository Scanner\MainWindow.xaml.cs:line 179 
     at HPOO_Repository_Scanner.MainWindow.mnuSave_Click(Object sender, RoutedEventArgs e) in \\tsclient\D\Dropbox\_Work\Visual Studio Projects\HPOO Repository Scanner\HPOO Repository Scanner\HPOO Repository Scanner\MainWindow.xaml.cs:line 168 
     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 e) 
     at System.Windows.Controls.MenuItem.InvokeClickAfterRender(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 HPOO_Repository_Scanner.App.Main() in \\tsclient\D\Dropbox\_Work\Visual Studio Projects\HPOO Repository Scanner\HPOO Repository Scanner\HPOO Repository Scanner\obj\x86\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: 

回答

0

我覺得自己像個白癡;今天早上我能弄明白。

我不得不從我的回購對象中分離ProgressChanged事件處理程序。

將其粘貼在創建對象

repo.ProgressChanged += new ProgressChangedEventHandler(repo_ProgressChanged); 

現在刪除保存對象狀態

private void mnuSave_Click(object sender, RoutedEventArgs e) 
{ 
    repo.ProgressChanged -= repo_ProgressChanged; 
    SaveRepo(repo); 
} 

希望幫助別人誰運行到同樣的問題之前。

0

假設那您正在使用XML編碼器。你應該顯示序列化代碼。另外,在獲取異常時,顯示異常和堆棧跟蹤。用這個信息確定上下文要容易得多。

如果是這樣,您必須使用[XmlIgnore]而不是[NonSerialized]屬性。

+0

序列化代碼位於方法'SaveRepo'中的WPF代碼的底部。它使用二進制序列化。 我會將異常粘貼到OP中。 – user1586644