Page d'Accueil

Introduction à la Sérialisation

 

Introduction

Considérez le programme suivant :

using System;
using System.IO;

class Program
{
    static int Main(string[] args)
    {
        string Make  = "Ford";
        string Model = "Escort";
        uint Year    = 1998;
        byte Color   = 1;

        FileStream stmCar   =
		 new FileStream("Car1.car",
                                FileMode.Create);
        BinaryWriter bnwCar = new BinaryWriter(stmCar);

        try
        {
            bnwCar.Write(Make);
            bnwCar.Write(Model);
            bnwCar.Write(Year);
            bnwCar.Write(Color);
        }
        finally
        {
            bnwCar.Close();
            stmCar.Close();
        }

        return 0;
    }
}

C'est un exemple des techniques que nous avons utilisées dans des leçons précédentes pour sauvegarder différentes données des types primitifs :

Saving the variables in a method

Les valeurs peuvent être recherchées avec le code suivant :

using System;
using System.IO;

class Program
{
    static int Main(string[] args)
    {
        string Make  = "Ford";
        string Model = "Escort";
        uint Year    = 1998;
        byte Color   = 1;

        FileStream stmCar   = new FileStream("Car1.car",
                                             FileMode.Open);
        BinaryReader bnrCar = new BinaryReader(stmCar);

        try
        {
            Console.WriteLine("Make:  {0}", bnrCar.ReadString());
            Console.WriteLine("Model: {0}", bnrCar.ReadString());
            Console.WriteLine("Year:  {0}", bnrCar.ReadUInt32());
            Console.Write("Color: ");
            byte  clr = bnrCar.ReadByte();
            switch (clr)
            {
                case 1:
                    Console.WriteLine("Black");
                    break;
                case 2:
                    Console.WriteLine("Gray");
                    break;
                case 3:
                    Console.WriteLine("White");
                    break;
                case 4:
                    Console.WriteLine("Red");
                    break;
                case 5:
                    Console.WriteLine("Blue");
                    break;
            }
        }
        finally
        {
            bnrCar.Close();
            stmCar.Close();
        }

        return 0;
    }
}

Ceci produirait :

Make:  Ford
Model: Escort
Year:  1998
Color: Black
Press any key to continue . . .

De la même manière, nous avons appris à sauvegarder les différents champs d'une classe :

Saving the individual parts of an object

Voici un exemple :

using System;
using System.IO;

public class Car
{
    public string Make  = "Toyota";
    public string Model = "Corolla";
    public uint   Year  = 2002;
    public byte   Color = 2;
}

class Program
{
    static int Main(string[] args)
    {
        Car vehicle = new Car();
        
        FileStream stmCar   = File.Create("Car2.car");
        BinaryWriter bnwCar = new BinaryWriter(stmCar);

        try
        {
            bnwCar.Write(vehicle.Model);
            bnwCar.Write(vehicle.Year);
            bnwCar.Write(vehicle.Color);
        }
        finally
        {
            bnwCar.Close();
            stmCar.Close();
        }

        return 0;
    }
}

Quand il s'agit d'une classe, le problème concernant la sauvegarde les champs individuels est que vous pourriez oublier de sauvegaeder un des champs. Par exemple, en considérant la classe Car, si vous ne sauvegarser pas l'information Marque (Make) de l'objet Car et recherchez ou ouvrez l'objet sauvgardé sur un autre ordinateur, l'utilisateur de réception manquerait certaines informations et le Car ne pourrait pas être complètement identifiable. Une alternative est de sauvegarder en entier l'objet Car.

La sérialisation d'un d'objet consiste à sauvegarser un objet entier comme un, au lieu de ses champs individuels :

Serialization

En d'autres termes, une variable déclarée d'une classe peut être sauvegardée en un jet et alors l'objet sauvé peut être reccupéré plus tard ou sur un autre ordinateur. .NET Framework soutient deux types de sérialisation d'objet : binaire et SOAP.

Étude pratique : Présentation de la sérialisation

  1. Commencez Microsoft Visual C# et créez une application de console appelée GeorgetownCleaningServices6
  2. Sauvegarsez le projet, sur la barre d'outils standard, cliquez le bouton Enregistrer tout 
  3. Accepte tous par défauts et cliquez Enregistrer
  4. Pour créer une nouvelle classe, dans Explorateur de solution, droit-cliquez GeorgetownCleaningServices6 - > Ajouter - > classe…
  5. Placez le nom BusinessManagement et appuyez Enter
  6. Changez le fichier comme suit :
     
    using System;
    using System.IO;
    
    namespace GeorgetownCleaningServices6
    {
        public static class BusinessManagement
        {
            public static void HireEmployee()
            {
                FileStream fsEmployee = null;
                BinaryWriter bwEmployee = null;
    
                // Ask the clerk to enter an employee number
                // using the format 00-000
                Console.Write("Enter Employee Number (00-000): ");
                string emplNumber = Console.ReadLine();
    
                string strPath = @"C:\Georgetown Cleaning Services\Employees\" +
                                 @"\" + emplNumber + ".gce";
    
                if (File.Exists(strPath))
                {
                    Console.Write("\nEither the employee has already been hired, ");
        Console.WriteLine("or there is already another employee with that number.");
                    return;
                }
                else // If no employee with that number was found, create it
                {
                    try
                    {
                 // If there is not yet a directory named Employees, then create it
        Directory.CreateDirectory(@"C:\Georgetown Cleaning Services\Employees");
                    }
                    catch (DirectoryNotFoundException)
                    {
                        Console.WriteLine("The folder could not be created");
                    }
    
                    try
                    {
                        fsEmployee = File.Create(strPath);
                        bwEmployee = new BinaryWriter(fsEmployee);
                        Console.Write("Enter Employee First Name: ");
                        string emplFName = Console.ReadLine();
                        Console.Write("Enter Employee Last Name:  ");
                        string emplLName = Console.ReadLine();
                        Console.Write("Enter Hourly Salary: ");
                        double emplSalary = double.Parse(Console.ReadLine());
    
                        // The minimum salary in this company is 7.50
                        if (emplSalary < 7.50D)
                            emplSalary = 7.50D;
    
                        bwEmployee.Write(emplNumber);
                        bwEmployee.Write(emplFName);
                        bwEmployee.Write(emplLName);
                        bwEmployee.Write(emplSalary);
                    }
                    finally
                    {
                        bwEmployee.Close();
                        fsEmployee.Close();
                    }
                }
                
                Console.WriteLine();
            }       
        }
    }
  7. Accédez au fichier Program.cs et changez le comme suit :
     
    using System;
    
    namespace GeorgetownCleaningServices6
    {
        public static class Program
        {
            static int Main(string[] args)
            {
                char answer = '0';
    
                do
                {
                    try
                    {
                        Console.WriteLine("What do you want to do?");
                        Console.WriteLine("0. Quit");
                        Console.WriteLine("1. Hire a new employee");
                        Console.WriteLine("2. Process a payroll");
                        Console.Write("Your Choice: ");
                        answer = char.Parse(Console.ReadLine());
                    }
                    catch (FormatException)
                    {
                        Console.WriteLine("Invalid Answer!");
                    }
    
                    switch (answer)
                    {
                        case '1':
                            BusinessManagement.HireEmployee();
                            break;
    
                        case '2':
                            break;
    
                        default:
                            break;
                    }
    
                } while (answer == '1' || answer == '2');
    
                Console.WriteLine();
                return 0;
            }
        }
    }
  8. Exécutez l'application et examinez la. Voici un exemple :
     
    What do you want to do?
    0. Quit
    1. Hire a new employee
    2. Process a payroll
    Your Choice: 1
    Enter Employee Number (00-000): 86-025
    Enter Employee First Name: Anne
    Enter Employee Last Name: Harang
    Enter Hourly Salary: 6.75
    
    What do you want to do?
    0. Quit
    1. Hire a new employee
    2. Process a payroll
    Your Choice: 1
    Enter Employee Number (00-000): 42-713
    Enter Employee First Name: Peter
    Enter Employee Last Name: Lansome
    Enter Hourly Salary: 12.45
    
    What do you want to do?
    0. Quit
    1. Hire a new employee
    2. Process a payroll
    Your Choice: 1
    Enter Employee Number (00-000): 29-368
    Enter Employee First Name: Gertrude
    Enter Employee Last Name: Monay
    Enter Hourly Salary: 10.85
    
    What do you want to do?
    0. Quit
    1. Hire a new employee
    2. Process a payroll
    Your Choice: 0
    
    Press any key to continue . . .
  9. Fermez la fenêtre DOS

Sérialisation

La sérialisation binaire fonctionne en traitant un objet plutôt que de naviguer dans ses différentes variables membres. Ceci signifie que, pour l'utiliser, vous définissez un objet et l'initialisez, ou « le remplissez », de valeurs nécessaires et de n'importe quelle information que vous jugez nécessaire. Ceci crée un « état » de l'objet. C'est cet état que vous vous préparez à sérialiser. Quand vous sauvegardez l'objet, il est converti en flot (Stream).

Pour effectuer la sérialisation binaire, il y a quelques étapes que vous devez suivrent. Quand vous créez une classe dont les objets seraient sérialisés, la commencer avec l'attribut [Serializable]. Voici un exemple :

[Serializable]
public class Car
{
    public string Make;
    public string Model;
    public uint   Year;
    public byte   Color;
}

Avant la sérialisation d'un objet, vous devriez référencer le namespace System.Runtime.Serialization.Formatters.Binary. La classe responsable de la sérialisation binaire s'appelle BinaryFormatter. Cette classe est équipée de deux constructeurs. Le constructeur par défaut est habitué à créer simplement un objet. Après la déclaration de la variable, pour sérialiser réellement un objet, appelez la méthode serialize () de classe BinaryFormatter. La méthode est prise en charge dans deux versions. Une des versions de cette méthode utilise la syntaxe suivante :

public void Serialize(Stream serializationStream, object graph);

Le premier argument de cette méthode doit être un objet d'une classe basée sur le Stream. Dans les leçons précédentes, nous avons vu comment créer des objets Stream (par exemple en utilisant la classe FileStream).

Le deuxième argument doit être l'objet à sérialiser. Ceci signifie que, avant d'appeler cette méthode, vous devriez avoir établi l'objet.

Voici un exemple :

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

[Serializable]
public class Car
{
    public string Make;
    public string Model;
    public uint   Year;
    public byte   Color;
}

class Program
{
    static int Main(string[] args)
    {
        Car vehicle = new Car();

        vehicle.Make  = "Lexus";
        vehicle.Model = "LS";
        vehicle.Year  = 2007;
        vehicle.Color = 4;

        FileStream stmCar   = new FileStream("Car3.car",
                                             FileMode.Create);
        BinaryFormatter bfmCar = new BinaryFormatter();
        
        bfmCar.Serialize(stmCar, vehicle);

        return 0;
    }
}

Étude pratique : Sérialiser un objet

  1. Pour créer une nouvelle classe, dans Affichage de classe, droit-cliquez GeorgetownCleaningServices6 - > Ajouter - > classe…
  2. Placez le nom PayrollInformation et cliquez OK
  3. Changez le fichier comme suit :
     
    using System;
    
    namespace GeorgetownCleaningServices6a
    {
        [Serializable]
        public class PayrollInformation
        {
            private string number;
            private string fname;
            private string lname;
            private double salary;
            private DateTime start;
    
            public string EmployeeNumber
            {
                get { return this.number; }
                set { this.number = value; }
            }
    
            public string FirstName
            {
                get { return this.fname; }
                set { this.fname = value; }
            }
    
            public string LastName
            {
                get { return this.lname; }
                set { this.lname = value; }
            }
    
            public double HourlySalary
            {
                get { return this.salary; }
                set { this.salary = value; }
            }
    
            public DateTime StartPeriod
            {
                get { return this.start; }
                set { this.start = value; }
            }
    
            public DateTime EndPeriod
            {
                get { return start.AddDays(13D); }
            }
    
            public double Week1Monday;
            public double Week1Tuesday;
            public double Week1Wednesday;
            public double Week1Thursday;
            public double Week1Friday;
            public double Week2Monday;
            public double Week2Tuesday;
            public double Week2Wednesday;
            public double Week2Thursday;
            public double Week2Friday;
    
            public double RegularHours;
            public double OvertimeHours;
            public double RegularAmount;
            public double OvertimeAmount;
    
            public double TotalEarnings;
        }
    }
  4. Accédez au fichier BusinessManagement.cs et changez le comme suit :
     
    using System;
    using System.IO;
    using System.Runtime.Serialization.Formatters.Binary;
    
    namespace GeorgetownCleaningServices6a
    {
        public static class BusinessManagement
        {
            public static void HireEmployee()
            {
                FileStream fsEmployee = null;
                BinaryWriter bwEmployee = null;
    
                // Ask the clerk to enter an employee number
                // using the format 00-000
                Console.Write("Enter Employee Number (00-000): ");
                string emplNumber = Console.ReadLine();
    
                string strPath = @"C:\Georgetown Cleaning " +
                                 @"Services\Employees\" +
                                 @"\" + emplNumber + ".gce";
    
                if (File.Exists(strPath))
                {
                    Console.Write("\nEither the employee has " +
                                  "already been hired, ");
                    Console.WriteLine("or there is already another " +
                                      "employee with that number.");
                    return;
                }
                // If no employee with that number 
                // was found, create it
                else 
                {
                    try
                    {
                        // If there is not yet a directory named 
                        // Employees, then create it
                        Directory.CreateDirectory(@"C:\Georgetown " +
                            @"Cleaning Services\Employees");
                    }
                    catch (DirectoryNotFoundException)
                    {
                        Console.WriteLine("The folder could " +
                                          "not be created");
                    }
    
                    try
                    {
                        fsEmployee = File.Create(strPath);
                        bwEmployee = new BinaryWriter(fsEmployee);
    
                        Console.Write("Enter Employee First Name: ");
                        string emplFName = Console.ReadLine();
                        Console.Write("Enter Employee Last Name:  ");
                        string emplLName = Console.ReadLine();
                        Console.Write("Enter Hourly Salary:       ");
                        double emplSalary =
                            double.Parse(Console.ReadLine());
    
                        // The minimum salary in this company is 7.50
                        if (emplSalary < 7.50D)
                            emplSalary = 7.50D;
    
                        bwEmployee.Write(emplNumber);
                        bwEmployee.Write(emplFName);
                        bwEmployee.Write(emplLName);
                        bwEmployee.Write(emplSalary);
                    }
                    finally
                    {
                        bwEmployee.Close();
                        fsEmployee.Close();
                    }
                }
    
                Console.WriteLine();
            }
    
            public static void CreatePayroll()
            {
                FileStream   fsPayroll = null;
                BinaryReader brPayroll = null;
                DateTime dteStartDate;
    
                PayrollInformation payroll =
                    new PayrollInformation();
    
                double monday1 = 0.00D, tuesday1 = 0.00D,
                       wednesday1 = 0.00D, thursday1 = 0.00D,
                       friday1 = 0.00D, monday2 = 0.00D,
                       tuesday2 = 0.00D, wednesday2 = 0.00D,
                       thursday2 = 0.00D, friday2 = 0.00D;
                double totalHoursWeek1 = 0.00D,
                       totalHoursWeek2 = 0.00D;
    
                double regHours1 = 0.00D, regHours2 = 0.00D,
                       ovtHours1 = 0.00, ovtHours2 = 0.00;
                double regAmount1 = 0.00D, regAmount2 = 0.00D,
                       ovtAmount1 = 0.00D, ovtAmount2 = 0.00D;
                double regularHours = 0.00D, overtimeHours = 0.00D;
                double regularAmount = 0.00D,
                       overtimeAmount = 0.00D,
                       totalEarnings = 0.00D;
    
                Console.Write("Enter Employee Number: ");
                string emplNumber = Console.ReadLine();
    
                string strEmployeePath = @"C:\Georgetown " +
                                         @"Cleaning Services\Employees\" +
                                         @"\" + emplNumber + ".gce";
    
                if (!File.Exists(strEmployeePath))
                {
                    Console.WriteLine("There is no employee with " +
                                      "that number in our records");
                    return;
                }
                // If an employee with that number was found,
                // continue with the payroll
                else {
                    try
                    {
                        fsPayroll = new FileStream(strEmployeePath,
                                                   FileMode.Open,
                                                   FileAccess.Read);
                        brPayroll = new BinaryReader(fsPayroll);
    
                        payroll.EmployeeNumber = brPayroll.ReadString();
                        payroll.FirstName = brPayroll.ReadString();
                        payroll.LastName = brPayroll.ReadString();
                        payroll.HourlySalary = brPayroll.ReadDouble();
    
                        Console.WriteLine("\n------------------------" +
                                          "------------------------");
                        Console.WriteLine("Employee #:    {0}",
                                          payroll.EmployeeNumber);
                        Console.WriteLine("Full Name:     {0}, {1}",
                                          payroll.FirstName,
                                          payroll.LastName);
                        Console.WriteLine("Hourly Salary: {0:C}",
                                          payroll.HourlySalary);
                        Console.WriteLine("-------------------------" +
                                          "-----------------------\n");
                    }
                    finally
                    {
                        brPayroll.Close();
                        fsPayroll.Close();
                    }
    
                    try
                    {
                        do
                        {
                            Console.Write("Enter Payroll Start " +
                                          "Date (mm/dd/yyyy): ");
                            dteStartDate =
                                DateTime.Parse(Console.ReadLine());
                            if (dteStartDate.DayOfWeek !=
                                DayOfWeek.Sunday)
                            {
                                Console.WriteLine("Invalid Date Entry");
                                Console.WriteLine("Payrolls start " +
                                                  "on a Sunday");
                            }
                        } while (dteStartDate.DayOfWeek !=
                              DayOfWeek.Sunday);
    
                        payroll.StartPeriod = dteStartDate;
                    }
                    catch (FormatException)
                    {
                        Console.WriteLine("Invalid Date Entry");
                    }
                }
    
                // Retrieve the value of each day worked
                Console.WriteLine("\nEnter the time worked " +
                                  "for each day (0.00)");
                Console.WriteLine("=-= Week 1 =-=");
                try
                {
                    Console.Write("{0}: ",
                        payroll.StartPeriod.AddDays(1).ToString("D"));
                    monday1 = double.Parse(Console.ReadLine());
                }
                catch (FormatException)
                {
                    Console.WriteLine("You typed an invalid value");
                }
                try
                {
                    Console.Write("{0}: ",
                        payroll.StartPeriod.AddDays(2).ToString("D"));
                    tuesday1 = double.Parse(Console.ReadLine());
                }
                catch (FormatException)
                {
                    Console.WriteLine("You typed an invalid value");
                }
                try
                {
                    Console.Write("{0}: ",
                        payroll.StartPeriod.AddDays(3).ToString("D"));
                    wednesday1 = double.Parse(Console.ReadLine());
                }
                catch (FormatException)
                {
                    Console.WriteLine("You typed an invalid value");
                }
                try
                {
                    Console.Write("{0}: ",
                        payroll.StartPeriod.AddDays(4).ToString("D"));
                    thursday1 = double.Parse(Console.ReadLine());
                }
                catch (FormatException)
                {
                    Console.WriteLine("You typed an invalid value");
                }
                try
                {
                    Console.Write("{0}: ",
                        payroll.StartPeriod.AddDays(5).ToString("D"));
                    friday1 = double.Parse(Console.ReadLine());
                }
                catch (FormatException)
                {
                    Console.WriteLine("You typed an invalid value");
                }
    
                Console.WriteLine("=-= Week 2 =-=");
                try
                {
                    Console.Write("{0}: ",
                        payroll.StartPeriod.AddDays(8).ToString("D"));
                    monday2 = double.Parse(Console.ReadLine());
                }
                catch (FormatException)
                {
                    Console.WriteLine("You typed an invalid value");
                }
                try
                {
                    Console.Write("{0}: ",
                        payroll.StartPeriod.AddDays(9).ToString("D"));
                    tuesday2 = double.Parse(Console.ReadLine());
                }
                catch (FormatException)
                {
                    Console.WriteLine("You typed an invalid value");
                }
                try
                {
                    Console.Write("{0}: ",
                        payroll.StartPeriod.AddDays(10).ToString("D"));
                    wednesday2 = double.Parse(Console.ReadLine());
                }
                catch (FormatException)
                {
                    Console.WriteLine("You typed an invalid value");
                }
                try
                {
                    Console.Write("{0}: ",
                        payroll.StartPeriod.AddDays(11).ToString("D"));
                    thursday2 = double.Parse(Console.ReadLine());
                }
                catch (FormatException)
                {
                    Console.WriteLine("You typed an invalid value");
                }
                try
                {
                    Console.Write("{0}: ",
                        payroll.StartPeriod.AddDays(12).ToString("D"));
                    friday2 = double.Parse(Console.ReadLine());
                }
                catch (FormatException)
                {
                    Console.WriteLine("You typed an invalid value");
                }
    
                // Calculate the total number of hours for each week
                totalHoursWeek1 = monday1 + tuesday1 + wednesday1 +
                                  thursday1 + friday1;
                totalHoursWeek2 = monday2 + tuesday2 + wednesday2 +
                                  thursday2 + friday2;
    
                // The overtime is paid time and half
                double ovtSalary = payroll.HourlySalary * 1.5D;
    
                // If the employee worked under 40 hours,
                // there is no overtime
                if (totalHoursWeek1 < 40)
                {
                    regHours1 = totalHoursWeek1;
                    regAmount1 = payroll.HourlySalary * regHours1;
                    ovtHours1 = 0.00D;
                    ovtAmount1 = 0.00D;
                } // If the employee worked over 40 hours,
                  // calculate the overtime
                else if (totalHoursWeek1 >= 40)
                {
                    regHours1 = 40;
                    regAmount1 = payroll.HourlySalary * 40;
                    ovtHours1 = totalHoursWeek1 - 40;
                    ovtAmount1 = ovtHours1 * ovtSalary;
                }
    
                if (totalHoursWeek2 < 40)
                {
                    regHours2 = totalHoursWeek2;
                    regAmount2 = payroll.HourlySalary * regHours2;
                    ovtHours2 = 0.00D;
                    ovtAmount2 = 0.00D;
                }
                else if (totalHoursWeek2 >= 40)
                {
                    regHours2 = 40;
                    regAmount2 = payroll.HourlySalary * 40;
                    ovtHours2 = totalHoursWeek2 - 40;
                    ovtAmount2 = ovtHours2 * ovtSalary;
                }
    
                regularHours = regHours1 + regHours2;
                overtimeHours = ovtHours1 + ovtHours2;
                regularAmount = regAmount1 + regAmount2;
                overtimeAmount = ovtAmount1 + ovtAmount2;
                totalEarnings = regularAmount + overtimeAmount;
    
                payroll.Week1Monday = monday1;
                payroll.Week1Tuesday = tuesday1;
                payroll.Week1Wednesday = wednesday1;
                payroll.Week1Thursday = thursday1;
                payroll.Week1Friday = friday1;
    
                payroll.Week2Monday = monday2;
                payroll.Week2Tuesday = tuesday2;
                payroll.Week2Wednesday = wednesday2;
                payroll.Week2Thursday = thursday2;
                payroll.Week2Friday = friday2;
    
                payroll.RegularHours = regularHours;
                payroll.OvertimeHours = overtimeHours;
                payroll.RegularAmount = regularAmount;
                payroll.OvertimeAmount = overtimeAmount;
                payroll.TotalEarnings = totalEarnings;
    
                ShowPayroll(payroll);
    
                Console.Write("Do you want to save " +
                              "the payroll (y/n): ");
                string strAnswer = Console.ReadLine();
    
                if (strAnswer.ToUpper() == "Y")
                    SavePayroll(payroll);
            }
    
            public static void SavePayroll(PayrollInformation pay)
            {
                // We will need this value to create the
                // name of the payroll file
                string strMonth = "0", strDay = "0", strYear = "0";
    
                // We want the month and day to include 0 if necessary
                strMonth = pay.StartPeriod.Month.ToString();
                if (pay.StartPeriod.Month < 10)
                    strMonth = "0" + pay.StartPeriod.Month.ToString();
                strDay = pay.StartPeriod.Day.ToString();
                if (pay.StartPeriod.Day < 10)
                    strDay = "0" + pay.StartPeriod.Day.ToString();
                strYear = pay.StartPeriod.Year.ToString();
    
                string strPayrollFilename = @"C:\Georgetown " +
                                            @"Cleaning Services\Payrolls\" +
                                            @"\" + pay.LastName[0] +
                                            pay.FirstName[0] +
                                            strMonth + strDay +
                                            strYear + ".epr";
                try
                {
                    // If there is not yet a directory for the 
                    // payrolls, then create it
                    Directory.CreateDirectory(@"C:\Georgetown Cleaning " +
                                              @"Services\Payrolls");
                }
                catch (DirectoryNotFoundException)
                {
                    Console.WriteLine("The employee payroll file " +
                                      "could not be created");
                }
    
                if (File.Exists(strPayrollFilename))
                {
                    Console.WriteLine("The employee's payroll " +
                                      "for that period exists already");
                }
    
                FileStream fsEmployeePayroll =
                                     new FileStream(strPayrollFilename,
                                     FileMode.Create);
                BinaryFormatter bfEmployeePayroll =
                    new BinaryFormatter();
    
                bfEmployeePayroll.Serialize(fsEmployeePayroll, pay);
                fsEmployeePayroll.Close();
            }
    
            public static void ViewPayroll()
            {
                
            }
    
            public static void ShowPayroll(PayrollInformation payed)
            {
                Console.WriteLine("\n=============================" +
                                  "===================");
                Console.WriteLine("=$= Payroll summary =$=");
                Console.WriteLine("-------------------------------" +
                                  "-----------------");
                Console.WriteLine("Employee #:    {0}",
                                  payed.EmployeeNumber);
                Console.WriteLine("Full Name:     {0}, {1}",
                                  payed.FirstName, payed.LastName);
                Console.WriteLine("Hourly Salary: {0:C}",
                                  payed.HourlySalary);
                Console.WriteLine("Start Period:  {0:D}",
                                  payed.StartPeriod);
                Console.WriteLine("End Period:    {0:D}",
                                  payed.EndPeriod);
                Console.WriteLine("--------------------------------" +
                                  "----------------");
                Console.WriteLine("        Monday Tuesday Wednesday " +
                                  "Thursday Friday");
                Console.WriteLine("Week 1:  {0:F}   {1:F}     " +
                                  "{2:F}      {3:F}    {4:F}",
                                  payed.Week1Monday, payed.Week1Tuesday,
                                  payed.Week1Wednesday, payed.Week1Thursday,
                                  payed.Week1Friday);
                Console.WriteLine("Week 2:  {0:F}   {1:F}     " +
                                  "{2:F}      {3:F}    {4:F}",
                                  payed.Week2Monday, payed.Week2Tuesday,
                                  payed.Week2Wednesday, payed.Week2Thursday,
                                  payed.Week2Friday);
                Console.WriteLine("-------------------------------" +
                                  "-----------------");
                Console.WriteLine("Monetary Summary");
                Console.WriteLine("            Hours   Amount");
                Console.WriteLine("Regular:   {0,6}   {1,6}",
                                  payed.RegularHours.ToString("F"),
                                  payed.RegularAmount.ToString("F"));
                Console.WriteLine("Overtime:  {0,6}   {1,6}",
                                  payed.OvertimeHours.ToString("F"),
                                  payed.OvertimeAmount.ToString("F"));
                Console.WriteLine("-------------------------------" +
                                  "-----------------");
                Console.WriteLine("Net Pay:   {0:F}",
                                  payed.TotalEarnings);
                Console.WriteLine("===============================" +
                                  "=================\n");
            }
        }
    }
  5. L'Accédez au fichier Program.cs et changez le comme suit :
     
    using System;
    
    namespace GeorgetownCleaningServices6a
    {
        public static class Program
        {
            static int Main(string[] args)
            {
                char answer = '0';
    
                Console.WriteLine("========================" +
                                  "========================");
                Console.WriteLine("Georgetown Cleaning Services");
                Console.WriteLine("========================" +
                                  "========================");
    
                do
                {
                    try
                    {
                        Console.WriteLine("\nWhat do you want to do?");
                        Console.WriteLine("0. Quit");
                        Console.WriteLine("1. Hire a new employee");
                        Console.WriteLine("2. Process a payroll");
                        Console.WriteLine("3. View an employee's payroll");
                        Console.Write("Your Choice: ");
                        answer = char.Parse(Console.ReadLine());
                        Console.WriteLine();
                    }
                    catch (FormatException)
                    {
                        Console.WriteLine("Invalid Answer!");
                    }
    
                    switch (answer)
                    {
                        case '1':
                            BusinessManagement.HireEmployee();
                            break;
                        case '2':
                            BusinessManagement.CreatePayroll();
                            break;
                        case '3':
                            BusinessManagement.ViewPayroll();
                            break;
                        default:
                            break;
                    }
    
                } while( (answer == '1') ||
                         (answer == '2') ||
                         (answer == '3') );
    
                return 0;
            }
        }
    }
  6. Exécutez l'application et examinez la. Voici un exemple :
     
    ================================================
    Georgetown Cleaning Services
    ================================================
    
    What do you want to do?
    0. Quit
    1. Hire a new employee
    2. Process a payroll
    3. View an employee's payroll
    Your Choice: 2
    
    Enter Employee Number: 29-368
    
    ------------------------------------------------
    Employee #:    29-368
    Full Name:     Gertrude, Monay
    Hourly Salary: $10.85
    ------------------------------------------------
    
    Enter Payroll Start Date (mm/dd/yyyy): 11/12/05
    Invalid Date Entry
    Payrolls start on a Sunday
    Enter Payroll Start Date (mm/dd/yyyy): 11/12/06
    
    Enter the time worked for each day (0.00)
    =-= Week 1 =-=
    Monday, November 13, 2006: 8.00
    Tuesday, November 14, 2006: 8.50
    Wednesday, November 15, 2006: 9.50
    Thursday, November 16, 2006: 8
    Friday, November 17, 2006: 8.50
    =-= Week 2 =-=
    Monday, November 20, 2006: 6.50
    Tuesday, November 21, 2006: 7.00
    Wednesday, November 22, 2006: 8
    Thursday, November 23, 2006: 6.00
    Friday, November 24, 2006: 7.00
    
    ================================================
    =$= Payroll summary =$=
    ------------------------------------------------
    Employee #:    29-368
    Full Name:     Gertrude, Monay
    Hourly Salary: $10.85
    Start Period:  Sunday, November 12, 2006
    End Period:    Saturday, November 25, 2006
    ------------------------------------------------
            Monday Tuesday Wednesday Thursday Friday
    Week 1:  8.00   8.50     9.50      8.00    8.50
    Week 2:  6.50   7.00     8.00      6.00    7.00
    ------------------------------------------------
    Monetary Summary
                Hours   Amount
    Regular:    74.50   808.33
    Overtime:    2.50    40.69
    ------------------------------------------------
    Net Pay:   849.01
    ================================================
    
    Do you want to save the payroll (y/n): Y
    
    What do you want to do?
    0. Quit
    1. Hire a new employee
    2. Process a payroll
    3. View an employee's payroll
    Your Choice: 0
    
    Press any key to continue . . .
  7. Fermez la fenêtre DOS
  8. Exécutez l'application encore et traitez une autre fiche de paie. Voici un exemple :
     
    ================================================
    Georgetown Cleaning Services
    ================================================
    
    What do you want to do?
    0. Quit
    1. Hire a new employee
    2. Process a payroll
    3. View an employee's payroll
    Your Choice: 2
    
    Enter Employee Number: 86-025
    
    ------------------------------------------------
    Employee #:    86-025
    Full Name:     Anne, Harang
    Hourly Salary: $7.50
    ------------------------------------------------
    
    Enter Payroll Start Date (mm/dd/yyyy): 11/26/2006
    
    Enter the time worked for each day (0.00)
    =-= Week 1 =-=
    Monday, November 27, 2006: 8.00
    Tuesday, November 28, 2006: 6.50
    Wednesday, November 29, 2006: 8.50
    Thursday, November 30, 2006: 8.00
    Friday, December 01, 2006: 8.00
    =-= Week 2 =-=
    Monday, December 04, 2006: 9.00
    Tuesday, December 05, 2006: 8.50
    Wednesday, December 06, 2006: 8.00
    Thursday, December 07, 2006: 9.50
    Friday, December 08, 2006: 8.00
    
    ================================================
    =$= Payroll summary =$=
    ------------------------------------------------
    Employee #:    86-025
    Full Name:     Anne, Harang
    Hourly Salary: $7.50
    Start Period:  Sunday, November 26, 2006
    End Period:    Saturday, December 09, 2006
    ------------------------------------------------
            Monday Tuesday Wednesday Thursday Friday
    Week 1:  8.00   6.50     8.50      8.00    8.00
    Week 2:  9.00   8.50     8.00      9.50    8.00
    ------------------------------------------------
    Monetary Summary
                Hours   Amount
    Regular:    79.00   592.50
    Overtime:    3.00    33.75
    ------------------------------------------------
    Net Pay:   626.25
    ================================================
    
    Do you want to save the payroll (y/n): y
    
    What do you want to do?
    0. Quit
    1. Hire a new employee
    2. Process a payroll
    3. View an employee's payroll
    Your Choice: 0
    
    Press any key to continue . . .
  9. Fermez la fenêtre DOS

Désérialisation

Comme la sérialisation est le processus de stockage d'un objet dans un médium, l'opposé de sérialisation est utilisé pour rechercher un objet d'un flot (Stream). Pour soutenir ceci, la classe BinaryFormatter est équipée de la méthode Deserialize (). Comme Serialize (), la méthode Deserialize () est prise en charge dans deux versions. L'une d'entre elles utilise la syntaxe suivante :

public object Deserialize(Stream serializationStream);

Cette méthode prend comme argument un objet basé sur Stream, tel qu'une variable de FileStream, qui indique où le fichier a localisé la méthode Deserialize (). La méthode Deserialize () renvoie un objet objet. Comme but, vous voulez que la méthode Deserialize () produise le type d'objet qui a été sauvgardé ainsi vous pouvez rechercher les valeurs que l'objet retourné contient. Puisque la méthode renvoie une valeur objet, vous devez mouler la valeur retournée au type de votre classe.

Une fois que la méthode Deserialize () a renvoyé l'objet désiré, vous pouvez accéder à ses valeurs. Voici un exemple :

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

[Serializable]
public class Car
{
    public string Make;
    public string Model;
    public uint Year;
    public byte Color;
}

class Program
{
    static int Main(string[] args)
    {
        FileStream stmCar   = new FileStream("Car3.car",
                                             FileMode.Open);
        BinaryFormatter bfmCar = new BinaryFormatter();
        Car vehicle = (Car)bfmCar.Deserialize(stmCar);

        Console.WriteLine("Make:  {0}", vehicle.Make);
        Console.WriteLine("Model: {0}", vehicle.Model);
        Console.WriteLine("Year:  {0}", vehicle.Year);
        byte clr = vehicle.Color;
        
        switch (clr)
        {
        case 1:
            Console.WriteLine("Black");
            break;
        case 2:
            Console.WriteLine("Gray");
            break;
        case 3:
            Console.WriteLine("White");
            break;
        case 4:
            Console.WriteLine("Red");
            break;
        case 5:
            Console.WriteLine("Blue");
            break;
        }
        
        stmCar.Close();

        return 0;
    }
}

Étude pratique : Désérialiser un objet

  1. Accédez au fichier BusinessManagement.cs et appliquez la méthode ViewPayroll () comme suit :
     
    using System;
    using System.IO;
    using System.Runtime.Serialization.Formatters.Binary;
    
    namespace GeorgetownCleaningServices6a
    {
        public static class BusinessManagement
        {
            public static void HireEmployee()
            {
                . . . No Change
            }
    
            public static void CreatePayroll()
            {
                . . . No Change
            }
    
            public static void SavePayroll(PayrollInformation pay)
            {
                . . . No Change
            }
    
            public static void ViewPayroll()
            {
                string strEmplNumber, strFName, strLName;
                string strMonth, strDay, strYear;
    
                // Ask the clerk to enter an employee number
                // using the format 00-000
                Console.Write("Enter Employee Number (00-000): ");
                strEmplNumber = Console.ReadLine();
    
                string strFilename = @"C:\Georgetown Cleaning " +
                                     @"Services\Employees\" +
                                     @"\" + strEmplNumber + ".gce";
    
                if (!File.Exists(strFilename))
                {
                    Console.Write("There is no employee " +
                                  "with that number.");
                }
                else
                {
                    FileStream fsEmployee = null;
                    BinaryReader brEmployee = null;
    
                    try
                    {
                        // We need to formally open the file 
                        // because we need the employees initials
                        fsEmployee = new FileStream(strFilename,
                                                    FileMode.Open,
                                                    FileAccess.Read);
                        brEmployee = new BinaryReader(fsEmployee);
    
                        // Read the file, mainly to get the 
                        // employee's name
                        strEmplNumber = brEmployee.ReadString();
                        strFName = brEmployee.ReadString();
                        strLName = brEmployee.ReadString();
                    }
                    finally
                    {
                        brEmployee.Close();
                        fsEmployee.Close();
                    }
    
                    Console.Write("Enter the start date of the " +
                                  "payroll you want to see (mm/dd/yyyy): ");
                    DateTime dteStartDate =
                        DateTime.Parse(Console.ReadLine());
    
                    // We want the month and day to include 0 if necessary
                    strMonth = dteStartDate.Month.ToString();
                    if (dteStartDate.Month < 10)
                        strMonth = "0" + dteStartDate.Month.ToString();
                    strDay = dteStartDate.Day.ToString();
                    if (dteStartDate.Day < 10)
                        strDay = "0" + dteStartDate.Day.ToString();
                    strYear = dteStartDate.Year.ToString();
    
                    strFilename = @"C:\Georgetown Cleaning " +
                                  @"Services\Payrolls\" +
                                  @"\" + strLName[0] +
                                  strFName[0] + strMonth +
                                  strDay + strYear + ".epr";
                    if (!File.Exists(strFilename))
                    {
                        Console.Write("{0}, {1} doesn't have a " +
                                      "payroll in that time frame",
                                      strLName, strFName);
                    }
                    else
                    {
                        // Open the payroll and display it
                        FileStream fsPayroll =
                            new FileStream(strFilename,
                                           FileMode.Open);
                        BinaryFormatter bfPayroll =
                            new BinaryFormatter();
                        PayrollInformation pay =
                            (PayrollInformation)bfPayroll.Deserialize(fsPayroll);
    
                        ShowPayroll(pay);
                    }
                }
            }
    
            public static void ShowPayroll(PayrollInformation payed)
            {
                . . . No Change
            }
        }
    }
  2. Exécutez l'application et examinez la. Voici un exemple :
     
    ================================================
    Georgetown Cleaning Services
    ================================================
    
    What do you want to do?
    0. Quit
    1. Hire a new employee
    2. Process a payroll
    3. View an employee's payroll
    Your Choice: 3
    
    Enter Employee Number (00-000): 29-368
    Enter the start date of the payroll you want to see (mm/dd/yyyy): 11/12/2006
    
    ================================================
    =$= Payroll summary =$=
    ------------------------------------------------
    Employee #:    29-368
    Full Name:     Gertrude, Monay
    Hourly Salary: $10.85
    Start Period:  Sunday, November 12, 2006
    End Period:    Saturday, November 25, 2006
    ------------------------------------------------
            Monday Tuesday Wednesday Thursday Friday
    Week 1:  8.00   8.50     9.50      8.00    8.50
    Week 2:  6.50   7.00     8.00      6.00    7.00
    ------------------------------------------------
    Monetary Summary
                Hours   Amount
    Regular:    74.50   808.33
    Overtime:    2.50    40.69
    ------------------------------------------------
    Net Pay:   849.01
    ================================================
    
    
    What do you want to do?
    0. Quit
    1. Hire a new employee
    2. Process a payroll
    3. View an employee's payroll
    Your Choice: 3
    
    Enter Employee Number (00-000): 86-025
    Enter the start date of the payroll you want to see (mm/dd/yyyy): 11/26/06
    
    ================================================
    =$= Payroll summary =$=
    ------------------------------------------------
    Employee #:    86-025
    Full Name:     Anne, Harang
    Hourly Salary: $7.50
    Start Period:  Sunday, November 26, 2006
    End Period:    Saturday, December 09, 2006
    ------------------------------------------------
            Monday Tuesday Wednesday Thursday Friday
    Week 1:  8.00   6.50     8.50      8.00    8.00
    Week 2:  9.00   8.50     8.00      9.50    8.00
    ------------------------------------------------
    Monetary Summary
                Hours   Amount
    Regular:    79.00   592.50
    Overtime:    3.00    33.75
    ------------------------------------------------
    Net Pay:   626.25
    ================================================
    
    
    What do you want to do?
    0. Quit
    1. Hire a new employee
    2. Process a payroll
    3. View an employee's payroll
    Your Choice: 0
    
    Press any key to continue . . .
  3. Fermez la fenêtre DOS
  

Accueil Copyright © 2007-2008, Yevol