CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 17
  1. #1
    Join Date
    Mar 2006
    Posts
    38

    Serializtion problem in C#

    Hi Every Body
    I tried to write phone index Application,but i got a problem with the serialization of my object,and i don't know why can some body help please and below is my code in detail and i attached the error message

    main form code
    Code:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    
    using System.IO;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Formatters.Binary;
    
    
    namespace PHIndex
    {
    public partial class MainFrm : Form
    {
    
    CTeleRecord phoneRecord;
    
    public MainFrm()
    {
    InitializeComponent();
    
    phoneRecord = new CTeleRecord();
    
    phoneRecord.errorEvnt += new errorEventHandler(ErrorHnd);
    
    }
    
    private void button1_Click(object sender, EventArgs e)
    {
    phoneRecord.GSName = textBox1.Text;
    phoneRecord.GShomeNumber = textBox2.Text;
    FileStream outPutSt = new FileStream("test.bin", FileMode.Create, FileAccess.Write);
    BinaryFormatter outBinFormater = new BinaryFormatter();
    outBinFormater.Serialize(outPutSt, phoneRecord);
    }
    
    private void button2_Click(object sender, EventArgs e)
    {
    BinaryFormatter inpuBinFormater = new BinaryFormatter();
    FileStream inPutSt = new FileStream("test.bin", FileMode.Open, FileAccess.Read);
    phoneRecord = (CTeleRecord)inpuBinFormater.Deserialize(inPutSt);
    textBox1.Text= phoneRecord.GSName;
    textBox2.Text= phoneRecord.GShomeNumber;
    }
    void ErrorHnd(object sender, myEventsArg e)
    {
    MessageBox.Show(e.GetErrorMessage,"Error Code"+e.GetErrorCode);
    }
    
    }
    }

    and the telephone Record Class code
    Code:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using PhoneIndex;
    
    namespace PHIndex
    {
    ///class for holding telephone index object
    public delegate void errorEventHandler(object sender, myEventsArg e);
    
    [Serializable]
    class CTeleRecord
    
    {
    
    
    string name;
    string homeNumber;
    string mobileNumber;
    string workNumber;
    string emailAddress;
    bool errorFlag;
    public event errorEventHandler errorEvnt;
    
    /// <summary>
    /// This Fn will fire the error event
    /// </summary>
    /// <param name="e"></param>
    void fireError(myEventsArg e)
    {
    if (errorEvnt != null)
    {
    ///invoke the delegate object
    errorEvnt(this,e);
    }
    }
    
    
    /// <summary>
    /// reset error flag
    /// </summary>
    public void ResetErrorFlag()
    { errorFlag = false; }
    
    public int getRecordLength()
    {
    
    
    return (name.Length + homeNumber.Length + mobileNumber.Length + workNumber.Length
    + emailAddress.Length);
    
    }
    
    public void resetTelRecordObj()
    {
    name = "";
    homeNumber = "";
    mobileNumber = "";
    workNumber = "";
    emailAddress = "";
    }
    
    /// <summary>
    /// Property for Get or Set home phone number
    /// </summary>
    public string GShomeNumber
    {
    get
    {
    return homeNumber;
    }
    set
    {
    if (value.Length > 0)
    try
    {
    //This property for checking validation of number;
    Convert.ToInt64(value);
    }
    
    catch (FormatException)
    {
    
    //errorFlag = true;
    
    myEventsArg e1 = new myEventsArg(1, "Numbers can't be a string");
    fireError(e1);
    }
    
    try
    {
    if (value.Length == 0 || value.Length == 8 || value.Length == 10 || value.Length == 13)
    homeNumber = value;
    else
    throw new Exception("Invalid Home Telephone Number Length (8 or 10 or 13 number)");
    }
    catch (Exception)
    {
    myEventsArg e11 = new myEventsArg(1, "Invalid Home Telephone Number Length");
    fireError(e11);
    }
    
    }
    }
    
    /// <summary>
    /// Property for Get or Set work telephone number
    /// </summary>
    public string GSWorkNumber
    {
    get{return workNumber;}
    
    set
    {
    if (value.Length > 0)
    try
    {
    //This property for checking validation of number;
    Convert.ToInt64(value)
    ;
    }
    
    catch (FormatException)
    {
    
    myEventsArg e3 = new myEventsArg(3, "Numbers can't be a string");
    fireError(e3);
    }
    
    try
    {
    if (value.Length == 0 || value.Length == 8 || value.Length == 10 || value.Length == 13)
    workNumber = value;
    else
    throw new Exception("Invalid Work Telephone Number Length (8 or 10 or 13 number)");
    }
    catch (Exception error)
    {
    
    myEventsArg e33 = new myEventsArg(3, "Invalid Work Telephone Number Length");
    fireError(e33);
    
    }
    
    }
    }
    
    /// <summary>
    /// Property for Get or Set mobile phone number
    /// </summary>
    public string GSmobileNumber
    {
    get
    {
    return mobileNumber;
    }
    set
    {
    if (value.Length > 0)
    try
    {
    //This property for checking validation of number;
    Convert.ToInt64(value)
    ;
    }
    
    catch (FormatException)
    {
    
    myEventsArg e2 = new myEventsArg(2, "Numbers can't be a string");
    fireError(e2);
    }
    
    try
    {
    if (value.Length == 0 || value.Length == 10 || value.Length == 13)
    mobileNumber = value;
    else
    throw new Exception("Invalid Home Telephone Number Length (8 or 10 or 13 number)");
    }
    catch (Exception)
    {
    
    myEventsArg e22 = new myEventsArg(2, "Invalid Home Telephone Number Length");
    fireError(e22);
    }
    }
    }
    /// <summary>
    /// Property for Get or Set user name
    /// </summary>
    public string GSName
    {
    get
    {
    return name;
    }
    
    set
    {
    try
    {
    if (value.Length == 0 || value.Length <= 50)
    name = value;
    else
    throw new Exception("Invalid Name Length (Max 50 Character)");
    }
    catch (Exception)
    {
    
    myEventsArg e0 = new myEventsArg(0, "You Wrote " + value.Length + "char" + " (Max 30 Character)");
    fireError(e0);
    }
    }
    }
    /// <summary>
    /// Property for Get or Set user email
    /// </summary>
    
    public string GSEmail
    {
    get
    {
    return emailAddress;
    }
    set
    {
    try
    {
    if (value.Contains('@') && value.Contains('.') || value.Contains(""))
    emailAddress = value;
    
    else
    throw new Exception("Invalid Email format");
    }
    
    catch (Exception)
    {
    
    myEventsArg e4 = new myEventsArg(4, "Invalid Email format");
    fireError(e4);
    }
    }
    }
    /// <summary>
    /// get error flag status
    /// </summary>
    public bool ErrorFlag
    { get { return errorFlag; } }
    
    /// <summary>
    /// Return the Record Length
    /// </summary>
    public int GetRecordLength
    {get{ return getRecordLength(); }}
    
    
    }
    }
    and event argument class code is
    Code:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    namespace PHIndex
    {
    public class myEventsArg : EventArgs
    {
    public myEventsArg(int ercode,string erCodeMesage)
    {
    errorCode = ercode;
    errorMessage = erCodeMesage;
    }
    private int errorCode;
    private string errorMessage;
    
    public int GetErrorCode
    {get { return errorCode; }}
    
    public string GetErrorMessage
    {get{return errorMessage;}}
    }
    }
    the error in detail
    Code:
    
    System.Runtime.Serialization.SerializationException was unhandled
      Message="Type 'PhoneIndex.Form1' in Assembly 'PhoneIndex, 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 PhoneIndex.Form1.Save() in E:\VC++  & VC# Projects\PhoneIndex\PhoneIndex\Form1.cs:line 264
           at PhoneIndex.Form1.saveToolStripMenuItem_Click(Object sender, EventArgs e) in E:\VC++  & VC# Projects\PhoneIndex\PhoneIndex\Form1.cs:line 225
           at System.Windows.Forms.ToolStripItem.RaiseEvent(Object key, EventArgs e)
           at System.Windows.Forms.ToolStripMenuItem.OnClick(EventArgs e)
           at System.Windows.Forms.ToolStripItem.HandleClick(EventArgs e)
           at System.Windows.Forms.ToolStripItem.HandleMouseUp(MouseEventArgs e)
           at System.Windows.Forms.ToolStripItem.FireEventInteractive(EventArgs e, ToolStripItemEventType met)
           at System.Windows.Forms.ToolStripItem.FireEvent(EventArgs e, ToolStripItemEventType met)
           at System.Windows.Forms.ToolStrip.OnMouseUp(MouseEventArgs mea)
           at System.Windows.Forms.ToolStripDropDown.OnMouseUp(MouseEventArgs mea)
           at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
           at System.Windows.Forms.Control.WndProc(Message& m)
           at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
           at System.Windows.Forms.ToolStrip.WndProc(Message& m)
           at System.Windows.Forms.ToolStripDropDown.WndProc(Message& m)
           at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
           at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
           at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
           at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
           at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
           at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
           at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
           at System.Windows.Forms.Application.Run(Form mainForm)
           at PhoneIndex.Program.Main() in E:\VC++  & VC# Projects\PhoneIndex\PhoneIndex\Program.cs:line 19
           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: 
    
    
    Attached Images Attached Images  
    Last edited by Falcon Eyes; May 13th, 2009 at 07:56 AM. Reason: Enhance my post

  2. #2
    Join Date
    Jun 2008
    Posts
    2,477

    Re: Serializtion problem in C#

    Well, looks to me like you did not mark the class as Serializable. Look into C# attributes (the "Serializable" attribute in particular).

    Also, please use code tags so that we can read your code without our eyes burning.

  3. #3
    Join Date
    Mar 2004
    Location
    33°11'18.10"N 96°45'20.28"W
    Posts
    1,808

    Re: Serializtion problem in C#

    format your code

  4. #4
    Join Date
    Apr 2007
    Location
    Mars NASA Station
    Posts
    1,436

    Re: Serializtion problem in C#

    Please post them in code tag.
    Thanks for your help.

  5. #5
    Join Date
    Mar 2006
    Posts
    38

    Re: Serializtion problem in C#

    sorry
    how to post my code in code tag

  6. #6
    Join Date
    Mar 2006
    Posts
    38

    Re: Serializtion problem in C#

    any way for simplification
    i created a class for holding the user information and make it serialize and call it CTeleRecord the important part of it is below


    ///class for holding telephone index object
    public delegate void errorEventHandler(object sender, myEventsArg e);
    [Serializable]
    class CTeleRecord

    {
    string name;
    string homeNumber;
    string mobileNumber;
    string workNumber;
    string emailAddress;
    bool errorFlag;
    public event errorEventHandler errorEvnt;
    .
    .
    .
    }

    then in the main form i added the follwing statement

    using System.IO;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Formatters.Binary;

    then i declared an object of type CTeleRecord as follow
    CTeleRecord phoneRecord;

    and defineit it in the mainform constructor
    phoneRecord = new CTeleRecord();

    }
    and then compiled the program successfully but when execute it and entering some user data and want to save it i got the included error message

  7. #7
    Join Date
    Nov 2002
    Location
    .NET 3.5 VS2008
    Posts
    1,039

    Re: Serializtion problem in C#

    Hi.

    1. This has been said before but I'll say it again: please use code tags. It is very simple...You can find out how right here...
    You can edit your posts and put those tags. There is no excuse for not using them now.

    2. Well what you've attached doesn't tell the whole story. You need to click the 'Details' button to see the full details of the error. When you get those you'll probably see for yourself what is wrong. Otherwise you can post the full error and someone will help you understand what's going wrong.
    Last edited by nelo; May 13th, 2009 at 05:05 AM.

  8. #8
    Join Date
    Jun 2008
    Posts
    2,477

    Re: Serializtion problem in C#

    Look at this error message carefully:

    Code:
    "Type 'PhoneIndex.Form1' in Assembly 'PhoneIndex, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable."
    You are trying to serialize the MainForm class, not your CTeleRecord class. Serialize only the object marked as serializable as the Form class is not.

  9. #9
    Join Date
    Nov 2002
    Location
    .NET 3.5 VS2008
    Posts
    1,039

    Re: Serializtion problem in C#

    Quote Originally Posted by BigEd781 View Post
    Look at this error message carefully:

    Code:
    "Type 'PhoneIndex.Form1' in Assembly 'PhoneIndex, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable."
    You are trying to serialize the MainForm class, not your CTeleRecord class. Serialize only the object marked as serializable as the Form class is not.
    Well spotted BigEd. Falcon Eyes: I don't think you put the important bit of code (i.e. line 264 or the contents of the Save() method). That's where the serialisation is taken place that's causing the problem.

  10. #10
    Join Date
    Mar 2006
    Posts
    38

    Re: Serializtion problem in C#

    BigEd781
    but i didn't place any Serialization attribute in the main Form class

  11. #11
    Join Date
    Mar 2006
    Posts
    38

    Re: Serializtion problem in C#

    the code for Fn Save s below
    Code:
    private void Save()
            {
                SaveFileDialog saveFileDlg = new SaveFileDialog();
                
                saveFileDlg.Filter = "Index File (*.ind)|*.ind";
                if (saveFileDlg.ShowDialog() == DialogResult.OK)
                {
    
                    FileStream saveFile = new FileStream(saveFileDlg.FileName, FileMode.Create, FileAccess.Write);
                    BinaryFormatter saveBinaryFormatter = new BinaryFormatter();
    
                    for (int ind = 0; ind < TotalNumberofRecords - 1; ind++)
                    {
                        globalPhoneRecord.resetTelRecordObj();
    
                        globalPhoneRecord.GSName = dataGridView1[0, ind].Value is DBNull
                       ? "" : (string)dataGridView1[0, ind].Value;
    
                        globalPhoneRecord.GShomeNumber = dataGridView1[1, ind].Value is DBNull
                     ? "" : (string)dataGridView1[1, ind].Value;
    
                        globalPhoneRecord.GSmobileNumber = dataGridView1[2, ind].Value is DBNull
                     ? "" : (string)dataGridView1[2, ind].Value;
    
                        globalPhoneRecord.GSWorkNumber = dataGridView1[3, ind].Value is DBNull
                     ? "" : (string)dataGridView1[3, ind].Value;
    
                        globalPhoneRecord.GSEmail = dataGridView1[4, ind].Value is DBNull
                     ? "" : (string)dataGridView1[4, ind].Value;
                        
                        saveBinaryFormatter.Serialize(saveFile, globalPhoneRecord);
                        
                    }
    
                    
                    saveFile.Close();
                }
            }

  12. #12
    Join Date
    Jun 2008
    Posts
    2,477

    Re: Serializtion problem in C#

    Quote Originally Posted by Falcon Eyes View Post
    BigEd781
    but i didn't place any Serialization attribute in the main Form class
    ...

    Yes, I know, and the error you get is caused because you are trying to serialize a class not marked as serializable. In your next piece of code, what type of object is globalPhoneRecord (I would guess it is a form).

  13. #13
    Join Date
    Nov 2002
    Location
    .NET 3.5 VS2008
    Posts
    1,039

    Re: Serializtion problem in C#

    Hi Falcon Eyes.

    There's nothing obviously wrong with what you've done. I think I may know the source of the problem. Here's a hint from your code...
    Code:
    phoneRecord.errorEvnt += new errorEventHandler(ErrorHnd);
    Here you are registering a handler for the errorEvnt. I think you need to un-register it before you do the serialization...I think the syntax is...
    Code:
    phoneRecord.errorEvnt -= new errorEventHandler(ErrorHnd);
    But you'll have to check that...Of course if turns out to be the cause of the problem you'll have to do it for all instances of CTeleRecord

  14. #14
    Join Date
    Mar 2006
    Posts
    38

    Re: Serializtion problem in C#

    Thannnnnnnnnnnnnnx nelo very much you are right
    at the beginging code for serialization i un-register the error handler fn and after closing the file i re-register it once again and it work.
    thanks

  15. #15
    Join Date
    Jun 2008
    Posts
    2,477

    Re: Serializtion problem in C#

    Very nice catch nelo

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured