Tuesday, August 24, 2010

Binary serialization - c#, asp.net example

Markup:
<%@ Page Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head2" runat="server">
</head>
<body>
    <form id="form1" runat="server">
        <asp:GridView runat="server" ID="grvItems" />
        <asp:Panel runat="server" ID="pnlAddCar">
            Modal: <asp:TextBox runat="server" ID="txtModal" />
            Color: <asp:TextBox runat="server" ID="txtColor" />
            <asp:Button runat="server" ID="btnSave" Text="Save Car" OnClick="SaveCar" />
        </asp:Panel>
    </form>
</body>
</html>
Code:
public partial class Test : Page
{
    private string fileName;
    public List<Car> Cars
    {
        get { return ViewState["Items"as List<Car>; }
        set { ViewState["Items"] = value; }
    }
    public Test()
    {
        fileName = Server.MapPath("~/Data.bin");
    }
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        if (!this.IsPostBack)
            this.LoadCars();
    }
    protected void SaveCar(object sender, EventArgs e)
    {
        if (this.Cars == nullthis.Cars = new List<Car>();
        Car car = new Car() { Color = this.txtColor.Text, Modal = this.txtModal.Text };
        this.Cars.Add(car);
        Stream stream = File.Open(fileName, FileMode.Create);
        BinaryFormatter bFormatter = new BinaryFormatter();
        bFormatter.Serialize(stream, this.Cars);
        stream.Close();
        this.grvItems.DataSource = this.Cars;
        this.grvItems.DataBind();
    }
    protected void LoadCars()
    {
        List<Car> cars;
        if (File.Exists(this.fileName))
        {
            Stream stream = File.Open(fileName, FileMode.Open);
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            cars = (List<Car>)binaryFormatter.Deserialize(stream);
            stream.Close();
            this.Cars = cars;
        }
        if (this.Cars != null)
        {
            this.grvItems.DataSource = this.Cars;
            this.grvItems.DataBind();
        }
    }
}
[Serializable]
public class Car
{
    #region Properties
        
    public string Modal { getset; }
    public string Color { getset; }
 
    #endregion
 
    #region Methods
 
    #endregion
}

No comments:

iPhone Launch Screen Sizes

iPhone Portrait iOS 8 Retina HT 5.5 = 1242 X 2208 Retna HD 4.7 = 750 X 1134 iPhone Landscape iOS 8 Retina HD 5.5  2208 X 1242 iPho...