Presentation is loading. Please wait.

Presentation is loading. Please wait.

Windows Programming Using C# Windows Services, Serialization, and Isolated Storage.

Similar presentations


Presentation on theme: "Windows Programming Using C# Windows Services, Serialization, and Isolated Storage."— Presentation transcript:

1 Windows Programming Using C# Windows Services, Serialization, and Isolated Storage

2 2 Contents Windows Services Serialization Isolated Storage

3 3 Windows Services A Windows service is a long-running program It is designed to run as a background task with no interaction with the screen UNIX calls these processes daemons They often implement key system tasks such as  Indexing, DNS, time synchronization, IIS, etc.

4 4 ServiceBase Class The ServiceBase class is in the System.ServiceProcess namespace All services are derived from this class It provides several methods which should be overloaded to define the actions of the service

5 5 ServiceBase Methods void OnStart(string[] args)  This is sent by the system when the service is started  Normally, the work performed by the service will be done by this method void OnPause()  Called when the service is paused  A service is usually resumed after a pause and it is not necessary to release all resources held by the service

6 6 ServiceBase Methods void OnContinue()  This resumes normal processing after the service has been paused void OnStop()  This attempts to stop the service  The service might be started again at a later time

7 7 ServiceBase Properties ServiceName  Allows the name of the service to be set or retrieved CanStop  Boolean indicating whether the service can be stopped

8 8 Sample Service We will now write a sample service We must provide  A service  A main program for the service  A service installer Our sample service will periodically write the time to a file *see WindowsService1

9 9 Service1 The constructor public Service1() { InitializeComponent(); this.ServiceName = "WindowsService1"; }

10 10 Service1 protected override void OnStart(string[] args) { try { writer = File.CreateText(@"c:\service1.log"); timer = new System.Threading.Timer(new System.Threading.TimerCallback(TimerHandler), null, 1000, 10000); } catch (Exception e1) { }

11 11 Service1 protected override void OnStop() { if (writer != null) { try { writer.Close(); writer = null; } catch (Exception e2) { }

12 12 Service1 void TimerHandler(object info) { if (writer != null) { writer.WriteLine("It is now {0}", DateTime.Now); }

13 13 Main Every service must have a Main method to run the service static void Main() { ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new Service1() }; ServiceBase.Run(ServicesToRun); }

14 14 Installing the Service Before you can install the service, you must write an installer This extends System.Configuration.Install.Installer It is included in the same assembly as the service it should install It installs the service by using the service name, which must be set in the service

15 15 Installing the Service To install the service use installutil which is located in  C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727  Where the final numbers are the build number and might change

16 16 Installing the Service To install the service  Start a command prompt and go to the directory containing the service assembly  installutil WindowsService1.exe To start the service  Start the services control panel and click start To uninstall the service  installutil /u WindowsService1.exe

17 17 Serialization Often, you want to store and object on disk and retrieve it later This is a sufficiently common operation that support has been provided for it in the.NET framework Serialization can  Create a self-describing data stream from an object  Reconstitute this stream back into the object

18 18 Serialization You can serialize  Any primitive  Any object marked with the Serializable attribute that contains only serializable methods  Any graph of objects which refer to one another

19 19 Graph Serialization When one object contains a reference to another, a graph is formed Sometimes, one object references another that references the first, creating a cycle Serialization is able to serialize an entire graph If there are cycles, it ensures that each object is only serialized once

20 20 Uses of Serialization Serialization is used for  Saving objects to disk  Transmitting objects across a network  Transmitting objects as parameters of remote procedure calls

21 21 Serialization Formats Serialized data can be in several formats  Binary Compact binary representation of the data  XML XML representation of data  SOAP Format suitable for use with web services

22 22 Serializable Classes A serializable class is marked so and contains only serializable members [Serializable] public class Person { string name; int age; Address address; … }

23 23 Serializable Classes The Address class must also be Serializable [Serializable] public class Address { string street; string city; string postCode; … }

24 24 Serializing an Object To serialize an object in binary, we use a BinaryFormatter Person p = new Person("Billy Bob", 42, "123 Main St.", "Toronto", "M2P 4D5"); FileStream fout = new FileStream("Person.bin", FileMode.Create); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(fout, p);

25 25 Deserializing an Object A BinaryFormatter is also used to deserialize an object FileStream fin = new FileStream("Person.bin", FileMode.Open); Person p1 = (Person)bf.Deserialize(fin); * See serial_demo

26 26 Transient Data Transient data is data which should not be serialized  Data which can be calculated when the object is deserialized  Static data  Data which is not useful to save File objects Current date or time

27 27 Transient Data Data which is transient can be marked NonSerializable I have extended the person class to store the gender and added a field for an honorific, Mr. or Ms. The honorific can be calculated from the gender so does not need to be serialized

28 28 Transient Data To deal with transient data  Mark transient fields [NonSerializable]  The class must implement IDeserializable  The class must provide the method public virtual void OnDeserialization( Object sender)  This method will recreate missing data * see transient_demo

29 29 XML Serialization The namespace  System.XML.Serialization Provides formatters which can serialize data as XML The main class is  XmlSerializer This class works the same as the BinaryFormatter

30 30 XML Serialization A class used with the XML serializer must  Be declared Serializable  Have a parameterless constructor  Declare all fields which are to be serialized as public  Contain only XML serializable fields

31 31 XML Serialization The XML generated can be altered by specifying attributes before the fields  [XmlAttribute(“newAttribName")] Uses the new name in XML instead of the primitive field name  [XmlElement(ElementName="activeProject")] Renames a complex element (class) rather than a primitive * see xml_serial_demo

32 32 XML Serialization Lists or ArrayLists are not serializable To serialize them, you must indicate the type as an array and then specify the type of the elements in the array [XmlArray(ElementName="Projects")] [XmlArrayItem(ElementName="Project")] public ArrayList projectList = new ArrayList();

33 33 Isolated Storage Applications often have to store data on the file system This can encounter several problems  The application does not have permission to write to the file system  Several users use the application and each wants to save their own settings  The data files are visible and can be corrupted by anyone with a text editor

34 34 Isolated Storage Applications need to store configuration settings  Recently opened files  Last screen position  User’s preferred color In the past, these have been stored in .ini files  The registry

35 35 Isolated Storage Isolated storage provides  A limited amount of storage which can be read or written by any program regardless of security settings  A data compartment for each user which can hold one or more data stores  A data store is a miniature file system  Every assembly / user combination has a data store created for it  This means that every user of an application has a directory to store their configuration files

36 36 Writing Isolated Storage The classes are in the namespace  System.IO.IsolatedStorage To create a file IsolatedStorageFileStream isf = new IsolatedStorageFileStream(“tst.cfg”, FileMode.Create); StreamWriter writer = new StreamWriter(isf); writer.WriteLine(“color=red”);

37 37 Reading Isolated Storage IsolatedStorageFileStream isf = new IsolatedStorageFileStream(“tst.cfg”, FileMode.Open); StreamReader reader = new StreamReader(isf); string line = reader.ReadLine();


Download ppt "Windows Programming Using C# Windows Services, Serialization, and Isolated Storage."

Similar presentations


Ads by Google