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

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

Embed Size (px)

Citation preview

Windows Programming Using C#

Windows Services, Serialization, and Isolated Storage

2

Contents

Windows Services Serialization Isolated Storage

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

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

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

ServiceBase Methods

void OnContinue()This resumes normal processing after the

service has been paused void OnStop()

This attempts to stop the serviceThe service might be started again at a later

time

7

ServiceBase Properties

ServiceNameAllows the name of the service to be set or

retrieved CanStop

Boolean indicating whether the service can be stopped

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

Service1

The constructorpublic Service1()

{

InitializeComponent();

this.ServiceName = "WindowsService1";

}

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

Service1

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

12

Service1

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

DateTime.Now); } }

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

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

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

Installing the Service

To install the serviceStart a command prompt and go to the

directory containing the service assembly installutil WindowsService1.exe

To start the serviceStart the services control panel and click start

To uninstall the service installutil /u WindowsService1.exe

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

Serialization

You can serialize Any primitiveAny object marked with the Serializable

attribute that contains only serializable methods

Any graph of objects which refer to one another

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

Uses of Serialization

Serialization is used forSaving objects to diskTransmitting objects across a networkTransmitting objects as parameters of remote

procedure calls

21

Serialization Formats

Serialized data can be in several formatsBinary

Compact binary representation of the data

XML XML representation of data

SOAP Format suitable for use with web services

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

Serializable Classes

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

…}

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

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

Transient Data

Transient data is data which should not be serializedData which can be calculated when the object

is deserializedStatic dataData which is not useful to save

File objects Current date or time

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

Transient Data

To deal with transient dataMark transient fields [NonSerializable]The class must implement IDeserializableThe class must provide the method

public virtual void OnDeserialization(Object sender)

This method will recreate missing data * see transient_demo

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

XML Serialization

A class used with the XML serializer mustBe declared SerializableHave a parameterless constructorDeclare all fields which are to be serialized as

publicContain only XML serializable fields

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

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

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

Isolated Storage

Applications need to store configuration settingsRecently opened filesLast screen positionUser’s preferred color

In the past, these have been stored in .ini filesThe registry

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

Writing Isolated Storage

The classes are in the namespaceSystem.IO.IsolatedStorage

To create a file

IsolatedStorageFileStream isf = new IsolatedStorageFileStream(“tst.cfg”, FileMode.Create);

StreamWriter writer = new StreamWriter(isf);

writer.WriteLine(“color=red”);

37

Reading Isolated Storage

IsolatedStorageFileStream isf = new IsolatedStorageFileStream(“tst.cfg”, FileMode.Open);

StreamReader reader = new StreamReader(isf);

string line = reader.ReadLine();