Network programming in C#, Network Programming in VB.NET, Network Programming in .NET
Available now!
Buy at Amazon US or
Buy at Amazon UK



Articles

1.Windows API reference
2.HTML to WML Converter
3.Webcam streaming in VB.NET
4.Remoting with firewalls
5.RSA from first principles
6.Key & MouseLogger in .NET
7.Networking Resource Kit for .NET
8.Automatic Reboot with .NET
9.XAML Schema
10.Migrating VB6 Winsock to VB.NET
11.Migrating C++ sockets to C#
12.RFC Reference guide
13.Lingua - Localization webservice
14.COM Reference guide
15.WMI Reference guide
16.SQL stored procedures
17.TCP & UDP port reference
18..NET Framework reference
19.Ethernet Type codes
21.MAC address assignments
22.DLL entry point reference
23.WHOIS server list
24. Turing Numbers
25. Boost SQL performance
26. Progress Bar in ASP.NET
27. OleDb WebService
27. Internet Explorer

Contact us

ViewState for Windows Forms applications



Many developers familiar with asp.net will be aware of the viewstate feature, a hidden variable on each page named __VIEWSTATE. The contents of this variable enables the server to re-populate form values with values entered by the user. This means that whenever a page posts-back to itself, all the form elements are maintained, a feat that would otherwise take significant programming effort is completed automatically.

This example shows how a viewstate technique can be used for windows forms applications. It can be used to maintain the state of user controls after if the application is shut down and restarted. This is particularly useful for storing user preferences and settings, so that each option need not be stored in a seperate variable, and read in and out of the registry (or from file) one-by-one. Since it usually takes 2 lines of code to save and load any setting, this makes for very repetive coding. Another use of this code could be crash recovery, where the state could be saved routinely, and deleted on a clean exit. If the application starts up, and an older viewstate is available on-disk, then it could resume at that point, with minimal data lost.

To demonstrate how easy it is to use this system, create a new windows form app in visual studio (or sharpdevelop), and draw some textboxes, checkboxes, scroll bars, labels, option buttons, date boxes etc on it. (unfortunately, the code below doesn't work with listboxes, listviews or treeviews). Then add two buttons, one saying save view state, the other saying load view state, and attach the following code to them:
        void Button1Click(object sender, System.EventArgs e)
        {            
            viewState.saveViewState(this);
        }
        
        void BtnLoadViewStateClick(object sender, System.EventArgs e)
        {
            viewState.loadViewState(this);
        }


You'll need to add a reference To System.Runtime.Serialization.Formatters.Soap, do this by clicking on projects > add reference, then selecting the assembly, and pressing ok. Then add a class called viewState, and add the following code to it:
/*
 * Created by SharpDevelop.
 * User: Fiach
 * Date: 03/10/2004
 * Time: 17:20
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using System.Windows.Forms;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Soap;
using System.IO;
using System.Collections;

namespace DefaultNamespace
{
    /// <summary>
    /// Description of viewState.
    /// </summary>
    [Serializable()]public class formData
    {
        public ArrayList ar = new ArrayList();        
        
    }
    
    [Serializable()]public class formControl 
    {
        public Type controlType;        
        public int controlIndex;
        public PropertyInfo  [] pi;
        public object [] piValues;
        public FieldInfo [] fi;
        public object [] fiValues;
    }
    
    
    public class viewState
    {
        public viewState()
        {            
        }
        public static void saveViewState(Form anyForm)
        {

            string appPath;
               appPath = Application.StartupPath;
            
            formData instanceOfFromData = new formData();            
            int controlIndex =0;
            foreach (Control ctrl in anyForm.Controls)
            {
                formControl controlData = new formControl();
                Type t = ctrl.GetType();                
                controlData.fi = t.GetFields (BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
                controlData.pi = t.GetProperties (BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);                                            
                controlData.piValues = new object[controlData.pi.Length];
                controlData.controlType = t;
                controlData.controlIndex = controlIndex++;
                for(int i=0;i<controlData.pi.Length;i++)
                {
                    
                    try
                    {
                        object val = controlData.pi[i].GetValue(ctrl,null);
                        if (isReserializable(val))
                        {
                            controlData.piValues[i]=val;
                        }
                    }catch{}                    
                }
                controlData.fiValues = new object[controlData.fi.Length];
                for(int i=0;i<controlData.fi.Length;i++)
                {
                    try
                    {
                        object val = controlData.fi[i].GetValue(ctrl);
                        if (isReserializable(val)) controlData.fiValues[i]=val;
                    }catch{}
                }        
                instanceOfFromData.ar.Add(controlData);
            }

            SoapFormatter sf = new SoapFormatter();
            FileStream fs = File.Create(appPath+ anyForm.Name + ".xml");            
            sf.Serialize(fs,instanceOfFromData);
            fs.Close();
        }
        public static void loadViewState(System.Windows.Forms.Form anyForm)
        {
            string appPath;
               appPath = Application.StartupPath;

            FileStream fs = File.OpenRead(appPath+anyForm.Name + ".xml");
            SoapFormatter sf = new SoapFormatter();
            formData instanceOfFromData = (formData)sf.Deserialize(fs);
            
            foreach (formControl ctrl in instanceOfFromData.ar)
            {
                Control c = anyForm.Controls[ctrl.controlIndex];
                
                for(int i=0;i<ctrl.pi.Length;i++)
                {                    
                    try
                    {
                        if (ctrl.piValues[i]!=null)
                        {
                            
                            ctrl.controlType.InvokeMember(ctrl.pi[i].Name,
                            BindingFlags.SetProperty,
                            null, c, 
                            new object [] {ctrl.piValues[i]});
                        }
                        
                    }catch{}                    
                }
                
                for(int i=0;i<ctrl.fi.Length;i++)
                {                    
                    try
                    {    
                        if (ctrl.fiValues[i]!=null)
                        {
                            
                            ctrl.controlType.InvokeMember(ctrl.fi[i].Name,
                            BindingFlags.SetField,
                            null, c, 
                            new object [] {ctrl.fiValues[i]});
                        }
                    }catch{}                    
                }    
            }
            
            
        }
        private static bool isReserializable(Object obj)
        {
            Type t=obj.GetType();
            if (!t.IsSerializable) return false;
            MemoryStream s = new MemoryStream();
            SoapFormatter sf = new SoapFormatter();
            
            try
            {
                sf.Serialize(s,obj);
                s.Position=0;
                Object copy = (Object)sf.Deserialize(s);
                
                return true;
            }
            catch(Exception e)
            {                
                return false;
            }
        }
        
    }
}
Run the application, change a few values, press save, restart the application, and press load, and the values will be restored. You can look at the generated SOAP XML file, by going to the location where application is running from, and looking for an xml file there.



Google

Copyright 2012 Open Merchant Account Ltd.
Free SMS UK Free SMS Ireland SMS Gratis Norway SMS Gratis Sverige Ilmainen SMS Suomi SMS Gratis Danmark SMS Tasuta Eestisse SMS Nemokamai Lietuva SMS Bezmaksas Latviju Darmowe smsy Polska SMS Zdarma Ceské SMS Zdarma Slovensko SMS Gratis Deutschland SMS Gratis Schweiz SMS Gratis Österreich SMS Gratuit Belgique SMS Gratis Nederland SMS Gratuit France SMS Gratis Espańa SMS Gratis Portugal Free SMS South Africa Free SMS USA SMS Percuma Malaysia Free SMS Hong Kong