Solved

Serializing a Static Object in C#

Posted on 2004-10-20
14
385 Views
Last Modified: 2010-04-15
I can't seem to find anything that is helping me out on this one anywhere on the net.

I have an object that consists of only static data.  I do not initialize any instance of the class except within the class itself.  However, I need to serialize the public or accessible values of this class, and then load them up again (back into the static object).

All references I can find show example of creating a new instance of an object, then serializing that.  Instead of creating a new instance of an object, how can I just serialize all the static values of the class, and then deserialize them back into the class?

Thanks
0
Comment
Question by:duerra
  • 10
  • 2
14 Comments
 
LVL 5

Expert Comment

by:knowlton
ID: 12364994
I am new to C#.  I may not be able to help...but sometimes talking through a problem helps lead to an answer.

Can you post your class code....and explain what you mean by static data and serializing public values?

My understanding is that static data are values that are tracked among several instances of the same class.  This allows you to count how many instances you have created, etc.    Is that correct?

Also...it is just your data members, not methods that are static?

I have a book on C# which states:  "Static methods do not require an instance of an object and, therefore, cannot access the data members of the current class."
0
 
LVL 5

Expert Comment

by:knowlton
ID: 12365101
I created a quick Windows App to test static data members:



using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace WindowsApplicationStaticSerialization
{
      /// <summary>
      /// Summary description for Form1.
      /// </summary>
      public class Form1 : System.Windows.Forms.Form
      {
            /// <summary>
            /// Required designer variable.
            /// </summary>
            private System.ComponentModel.Container components = null;

            public Form1()
            {
                  //
                  // Required for Windows Form Designer support
                  //
                  InitializeComponent();

                  //
                  // TODO: Add any constructor code after InitializeComponent call
                  //
            }

            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            protected override void Dispose( bool disposing )
            {
                  if( disposing )
                  {
                        if (components != null)
                        {
                              components.Dispose();
                        }
                  }
                  base.Dispose( disposing );
            }

            #region Windows Form Designer generated code
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {
                  //
                  // Form1
                  //
                  this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
                  this.ClientSize = new System.Drawing.Size(292, 273);
                  this.Name = "Form1";
                  this.Text = "Form1";
                  this.Load += new System.EventHandler(this.Form1_Load);

            }
            #endregion

            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            [STAThread]
            static void Main()
            {
                  Application.Run(new Form1());
            }

            private void Form1_Load(object sender, System.EventArgs e)
            {
                  TestStatic ts = new TestStatic();
                  MessageBox.Show(ts.longVar.ToString());
                  
            }
      }

      public class TestStatic
      {
            public static long longVarStatic;
            public long longVar;

            public TestStatic()
            {
                  MessageBox.Show("hi from test static");
                  longVar = 5;
            }
      }
}



=================================================

The output is:

hi from test static

5


==================================================

The variable that I declared static did NOT show up as accessible by the ts object!!!!!  I am not sure why this is.
0
 
LVL 5

Expert Comment

by:knowlton
ID: 12365160
As I gained more understanding I modified my code as follows:


using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace WindowsApplicationStaticSerialization
{
      /// <summary>
      /// Summary description for Form1.
      /// </summary>
      public class Form1 : System.Windows.Forms.Form
      {
            /// <summary>
            /// Required designer variable.
            /// </summary>
            private System.ComponentModel.Container components = null;

            public Form1()
            {
                  //
                  // Required for Windows Form Designer support
                  //
                  InitializeComponent();

                  //
                  // TODO: Add any constructor code after InitializeComponent call
                  //
            }

            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            protected override void Dispose( bool disposing )
            {
                  if( disposing )
                  {
                        if (components != null)
                        {
                              components.Dispose();
                        }
                  }
                  base.Dispose( disposing );
            }

            #region Windows Form Designer generated code
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {
                  //
                  // Form1
                  //
                  this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
                  this.ClientSize = new System.Drawing.Size(292, 273);
                  this.Name = "Form1";
                  this.Text = "Form1";
                  this.Load += new System.EventHandler(this.Form1_Load);

            }
            #endregion

            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            [STAThread]
            static void Main()
            {
                  Application.Run(new Form1());
            }

            private void Form1_Load(object sender, System.EventArgs e)
            {
                  TestStatic ts = new TestStatic();
                  TestStatic ts_2 = new TestStatic();            
                  TestStatic ts_3 = new TestStatic();            
                  TestStatic ts_4 = new TestStatic();            
                  TestStatic ts_5 = new TestStatic();            
                  TestStatic ts_6 = new TestStatic();            
                  MessageBox.Show("After 6 instances of TestStatic, count is:  " + ts_6.OutputStaticVarValue().ToString());
            }
      }

      public class TestStatic
      {
            public static long longVarStatic=0;
            public long longVar;

            public TestStatic()
            {                        
                  longVarStatic++;                  
            }

            public long OutputStaticVarValue()
            {
                  return longVarStatic;
            }

      }
}


============================================================


Here is the output:


After 6 instances of TestStatic, count is:  6



So the value of the static data member called longVarStatic is preserved as each instance is created!!!!!!



I know this is basic stuff to you.....I am just trying to understand what you are asking.  :)   Please bear with me.  :)
0
 
LVL 5

Expert Comment

by:knowlton
ID: 12365177
<quote>
 I can't seem to find anything that is helping me out on this one anywhere on the net.

I have an object that consists of only static data.  I do not initialize any instance of the class except within the class itself.  However, I need to serialize the public or accessible values of this class, and then load them up again (back into the static object).

All references I can find show example of creating a new instance of an object, then serializing that.  Instead of creating a new instance of an object, how can I just serialize all the static values of the class, and then deserialize them back into the class?

</quote>


>>>I have an object that consists of only static data.

Okay, now I understand what that means.  :)


>>>I do not initialize any instance of the class except within the class itself

Hmmmm.....you may have to show me how you do this....I'll see what I can come up with....
0
 
LVL 5

Expert Comment

by:knowlton
ID: 12365195
>>>I do not initialize any instance of the class except within the class itself

Ohhhhh.....so you mean you DO NOT do things like this:

TestStatic ts = new TestStatic(<value one>, <value two>);    //HERE.....the object is being initialized with values passed in.

Is that what you mean?


So you only do this:

TestStatic ts = new TestStatic( );  //Here there is no initialization taking place.....except what the constructor may be doing....that is to say....no values are passed in or accepted.

0
 
LVL 5

Expert Comment

by:knowlton
ID: 12365201
I guess I am stuck on this part now:

>>>>>However, I need to serialize the public or accessible values of this class, and then load them up again (back into the static object).
0
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
LVL 5

Expert Comment

by:knowlton
ID: 12365212
From another post here in EE I learned what serialization is:

http://www.experts-exchange.com/Programming/Programming_Languages/C_Sharp/Q_20689551.html?query=serialize&topics=327:

DEFINITION
It is the process of converting an object (an instance of a class) into a stream of bytes which can be passed over a network, and re-assembled at the other end.. or written to a file for later retrieval.


I will proceed based on this definition.

0
 
LVL 5

Expert Comment

by:knowlton
ID: 12365284
Okay.....here is some working code for a Windows Form that demonstrates serialization:

Taken from this online tutorial:  http://www.ondotnet.com/pub/a/dotnet/2002/08/26/serialization.html?page=1


[[NOTE:  Just create a new C# Windows Application.  Replace the skeleton code that C# generates with THIS code.  Compile and run the application.  Should work]]

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;


namespace MyCSharp
{
      /// <summary>
      /// Summary description for Form1.
      /// </summary>
      public class Form1 : System.Windows.Forms.Form
      {
            private System.Windows.Forms.MainMenu mainMenu1;
            private System.Windows.Forms.MenuItem fileMenuItem;
            private System.Windows.Forms.MenuItem fileNewMenuItem;
            private System.Windows.Forms.MenuItem fileOpenMenuItem;
            private System.Windows.Forms.MenuItem fileSaveMenuItem;
            private System.Windows.Forms.MenuItem fileSaveAsMenuItem;
            private System.Windows.Forms.MenuItem fileExitMenuItem;
            private System.Windows.Forms.ToolBar toolBar1;
            private System.Windows.Forms.ToolBarButton lineToolBarButton;
            private System.Windows.Forms.ToolBarButton rectangleToolBarButton;
            private System.Windows.Forms.ToolBarButton ellipseToolBarButton;
            /// <summary>
            /// Required designer variable.
            /// </summary>
            private System.ComponentModel.Container components = null;

            private ArrayList shapes = new ArrayList();
            private enum shapeType
            {
                  line, rectangle, ellipse,
            }

            private shapeType drawnShapeType = shapeType.line;
            private Point startPoint;
            private String filename;

            public Form1()
            {
                  //
                  // Required for Windows Form Designer support
                  //
                  InitializeComponent();

                  //
                  // TODO: Add any constructor code after InitializeComponent call
                  //
            }

            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            protected override void Dispose( bool disposing )
            {
                  if( disposing )
                  {
                        if (components != null)
                        {
                              components.Dispose();
                        }
                  }
                  base.Dispose( disposing );
            }

            #region Windows Form Designer generated code
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {
                  this.mainMenu1 =
                        new System.Windows.Forms.MainMenu();
                  this.fileMenuItem =
                        new System.Windows.Forms.MenuItem();
                  this.fileNewMenuItem =
                        new System.Windows.Forms.MenuItem();
                  this.fileOpenMenuItem =
                        new System.Windows.Forms.MenuItem();
                  this.fileSaveMenuItem =
                        new System.Windows.Forms.MenuItem();
                  this.fileSaveAsMenuItem =
                        new System.Windows.Forms.MenuItem();
                  this.fileExitMenuItem =
                        new System.Windows.Forms.MenuItem();
                  this.toolBar1 =
                        new System.Windows.Forms.ToolBar();
                  this.lineToolBarButton =
                        new System.Windows.Forms.ToolBarButton();
                  this.rectangleToolBarButton =
                        new System.Windows.Forms.ToolBarButton();
                  this.ellipseToolBarButton =
                        new System.Windows.Forms.ToolBarButton();
                  this.SuspendLayout();
                  //
                  // mainMenu1
                  //
                  this.mainMenu1.MenuItems.AddRange(
                        new System.Windows.Forms.MenuItem[] {
                                                                                    this.fileMenuItem});
                  //
                  // fileMenuItem
                  //
                  this.fileMenuItem.Index = 0;
                  this.fileMenuItem.MenuItems.AddRange(
                        new System.Windows.Forms.MenuItem[] {
                                                                                    this.fileNewMenuItem,
                                                                                    this.fileOpenMenuItem,
                                                                                    this.fileSaveMenuItem,
                                                                                    this.fileSaveAsMenuItem,
                                                                                    this.fileExitMenuItem});
                  this.fileMenuItem.Text = "File";
                  //
                  // fileNewMenuItem
                  //
                  this.fileNewMenuItem.Index = 0;
                  this.fileNewMenuItem.Shortcut =
                        System.Windows.Forms.Shortcut.CtrlN;
                  this.fileNewMenuItem.Text =
                        "&New";
                  this.fileNewMenuItem.Click +=
                        new System.EventHandler(this.fileNewMenuItem_Click);
                  //
                  // fileOpenMenuItem
                  //
                  this.fileOpenMenuItem.Index = 1;
                  this.fileOpenMenuItem.Shortcut =
                        System.Windows.Forms.Shortcut.CtrlO;
                  this.fileOpenMenuItem.Text =
                        "&Open";
                  this.fileOpenMenuItem.Click +=
                        new System.EventHandler(this.fileOpenMenuItem_Click);
                  //
                  // fileSaveMenuItem
                  //
                  this.fileSaveMenuItem.Index = 2;
                  this.fileSaveMenuItem.Shortcut =
                        System.Windows.Forms.Shortcut.CtrlS;
                  this.fileSaveMenuItem.Text = "&Save";
                  this.fileSaveMenuItem.Click +=
                        new System.EventHandler(this.fileSaveMenuItem_Click);
                  //
                  // fileSaveAsMenuItem
                  //
                  this.fileSaveAsMenuItem.Index = 3;
                  this.fileSaveAsMenuItem.Text = "Save &As";
                  this.fileSaveAsMenuItem.Click +=
                        new System.EventHandler(this.fileSaveAsMenuItem_Click);
                  //
                  // fileExitMenuItem
                  //
                  this.fileExitMenuItem.Index = 4;
                  this.fileExitMenuItem.Text = "E&xit";
                  this.fileExitMenuItem.Click +=
                        new System.EventHandler(this.fileExitMenuItem_Click);
                  //
                  // toolBar1
                  //
                  this.toolBar1.Buttons.AddRange(
                        new System.Windows.Forms.ToolBarButton[] {
                                                                                           this.lineToolBarButton,
                                                                                           this.rectangleToolBarButton,
                                                                                           this.ellipseToolBarButton});
                  this.toolBar1.DropDownArrows = true;
                  this.toolBar1.Name = "toolBar1";
                  this.toolBar1.ShowToolTips = true;
                  this.toolBar1.Size = new System.Drawing.Size(292, 39);
                  this.toolBar1.TabIndex = 0;
                  this.toolBar1.ButtonClick +=
                        new System.Windows.Forms.ToolBarButtonClickEventHandler(
                        this.toolBar1_ButtonClick);
                  //
                  // lineToolBarButton
                  //
                  this.lineToolBarButton.Text = "Line";
                  //
                  // rectangleToolBarButton
                  //
                  this.rectangleToolBarButton.Text = "Rectangle";
                  //
                  // ellipseToolBarButton
                  //
                  this.ellipseToolBarButton.Text = "Ellipse";
                  //
                  // Form1
                  //
                  this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
                  this.BackColor = System.Drawing.Color.White;
                  this.ClientSize = new System.Drawing.Size(292, 273);
                  this.Controls.AddRange(
                        new System.Windows.Forms.Control[] {
                                                                                 this.toolBar1});
                  this.Menu = this.mainMenu1;
                  this.Name = "Form1";
                  this.Text = "Form1";
                  this.MouseDown +=
                        new System.Windows.Forms.MouseEventHandler(this_MouseDown);
                  this.MouseUp +=
                        new System.Windows.Forms.MouseEventHandler(this_MouseUp);
                  this.ResumeLayout(false);

            }
            #endregion

            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            [STAThread]
            static void Main()
            {
                  Application.Run(new Form1());
            }

            private void fileExitMenuItem_Click(object sender,
                  System.EventArgs e)
            {
                  this.Close();
            }

            private void toolBar1_ButtonClick(object sender,
                  System.Windows.Forms.ToolBarButtonClickEventArgs e)
            {
                  if (e.Button==lineToolBarButton)
                        drawnShapeType = shapeType.line;
                  else if (e.Button==rectangleToolBarButton)
                        drawnShapeType = shapeType.rectangle;
                  else
                        drawnShapeType = shapeType.ellipse;
            }

            private void fileNewMenuItem_Click(object sender,
                  System.EventArgs e)
            {
                  shapes.Clear();
                  this.CreateGraphics().Clear(Color.White);
            }

            private void fileOpenMenuItem_Click(object sender,
                  System.EventArgs e)
            {
                  OpenDocument();
            }

            private void fileSaveMenuItem_Click(object sender,
                  System.EventArgs e)
            {
                  Save();
            }

            private void fileSaveAsMenuItem_Click(object sender,
                  System.EventArgs e)
            {
                  SaveAs();
            }

            private void OpenDocument()
            {
                  OpenFileDialog openFileDialog = new OpenFileDialog();

                  if (openFileDialog.ShowDialog() == DialogResult.OK)
                  {
                        filename = openFileDialog.FileName;
                        Stream myStream = openFileDialog.OpenFile();
                        if (myStream != null)
                        {
                              IFormatter formatter = new BinaryFormatter();
                              shapes = (ArrayList) formatter.Deserialize(myStream);
                              myStream.Close();
                              this.Refresh();
                        }
                  }
            }

            private bool Save()
            {
                  if (filename==null)
                  {
                        return SaveAs();
                  }
                  else
                  {
                        Stream myStream ;
                        myStream = File.OpenWrite(filename);
                        if (myStream != null)
                        {
                              IFormatter formatter =
                                    /*(IFormatter) */ new BinaryFormatter();
                              // serialize shapes
                              formatter.Serialize(myStream, shapes);
                              myStream.Close();
                              return true;
                        }
                  }
                  return false;
            }

            private bool SaveAs()
            {
                  SaveFileDialog saveFileDialog = new SaveFileDialog();
                  if (saveFileDialog.ShowDialog() == DialogResult.OK)
                  {
                        filename = saveFileDialog.FileName;
                        return Save();
                  }
                  return false;
            }

            private void this_MouseDown(object sender,
                  System.Windows.Forms.MouseEventArgs e)
            {
                  if (e.Button==System.Windows.Forms.MouseButtons.Left)
                  {
                        startPoint = new Point(e.X, e.Y);
                  }
            }

            override protected void OnPaint(
                  System.Windows.Forms.PaintEventArgs e)
            {
                  Graphics g = e.Graphics;
                  IEnumerator shapeEnum = shapes.GetEnumerator();
                  while (shapeEnum.MoveNext())
                  {
                        IShape shape = (IShape) shapeEnum.Current;
                        shape.Draw(g);
                  }
            }

            private void this_MouseUp(object sender,
                  System.Windows.Forms.MouseEventArgs e)
            {
                  if (e.Button==System.Windows.Forms.MouseButtons.Left)
                  {
                        Point endPoint = new Point(e.X, e.Y);
                        if (drawnShapeType==shapeType.line)
                        {
                              shapes.Add(new Line(startPoint, endPoint));
                        }
                        else if (drawnShapeType==shapeType.rectangle)
                        {
                              shapes.Add(new Rect(GetRectangleFromPoints(startPoint,
                                    endPoint)));
                        }
                        else
                        {
                              shapes.Add(new Ellipse(GetRectangleFromPoints(startPoint,
                                    endPoint)));
                        }
                  }
                  this.Refresh();
            }

            private Rectangle GetRectangleFromPoints(Point p1, Point p2)
            {
                  int x1, x2, y1, y2;
                  if (p1.X < p2.X)
                  {
                        x1 = p1.X;
                        x2 = p2.X;
                  }
                  else
                  {
                        x1 = p2.X;
                        x2 = p1.X;
                  }

                  if (p1.Y < p2.Y)
                  {
                        y1 = p1.Y;
                        y2 = p2.Y;
                  }
                  else
                  {
                        y1 = p2.Y;
                        y2 = p1.Y;
                  }
                  // x2 > x1 and y2 > y1
                  return new Rectangle(x1, y1, x2 - x1, y2 - y1);
            }

      }
}

namespace MyCSharp
{
      public interface IShape
      {
            void Draw(Graphics g);
      }

      [Serializable]
      public class Line : IShape
      {
            Point startPoint, endPoint;
            public Line(Point startPoint, Point endPoint)
            {
                  this.startPoint = startPoint;
                  this.endPoint = endPoint;
            }
            public void Draw(Graphics g)
            {
                  g.DrawLine(Pens.Black, startPoint, endPoint);
            }
      }

      [Serializable]
      public class Rect : IShape
      {
            Rectangle rect;
            public Rect(Rectangle rect)
            {
                  this.rect = rect;
            }
            public void Draw(Graphics g)
            {
                  g.DrawRectangle(Pens.Black, rect);
            }
      }

      [Serializable]
      public class Ellipse : IShape
      {
            Rectangle rect;
            public Ellipse(Rectangle rect)
            {
                  this.rect = rect;
            }
            public void Draw(Graphics g)
            {
                  g.DrawEllipse(Pens.Black, rect);
            }
      }

}

0
 
LVL 4

Author Comment

by:duerra
ID: 12365468
knowlton, just... stop.  Your 20 posts of whatever are not helping me in any way.



Consider the following class:

      public class Test
      {
            private static int testint = 1;

            public static int TestInt
            {
                  get
                  {
                        return testint;
                  }
                  set
                  {
                        testint = value;
                  }
            }
      }



This class provides only static methods for accessing variables.
Therefore, the following declaration is not valid:

Test mytest = new Test();

I need to take all the publically available values of the class "Test" (in this case, only testint, through TestInt property), and serialize them, even though there is no instance of the object.  I also need to be able to reload the serialized variables into the static class at another point in time, obviously.

I hope this clarifies.
0
 
LVL 4

Author Comment

by:duerra
ID: 12365801
Nevermind.  I figured out a working solution.

For other users out there, look into Singleton patterns.  It's not really possible (as far as I'm aware), to serialize a non-instantiated object, but if you force instantiation, then simply have the instance return a static instance of the object, it works out.....
0
 
LVL 5

Expert Comment

by:knowlton
ID: 12370918
Beautiful!!!  Glad you found an answer, and I received quite an education just trying to understand the QUESTION!!!!  :)

Recommend mark this as PAQ and get your points refunded.

Tom
0
 
LVL 5

Expert Comment

by:knowlton
ID: 12594636
No objections, here.
0
 

Accepted Solution

by:
modulo earned 0 total points
ID: 12632841
PAQed with points refunded (350)

modulo
Community Support Moderator
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Suggested Solutions

In order to hide the "ugly" records selectors (triangles) in the rowheaders, here are some suggestions. Microsoft doesn't have a direct method/property to do it. You can only hide the rowheader column. First solution, the easy way The first sol…
Article by: Najam
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now