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

Slides:



Advertisements
Similar presentations
Slide 10.1 Advanced Programming 2004, based on LY Stefanus’s Slides Object Serialization Object serialization: the process of converting an object into.
Advertisements

CSC 243 – Java Programming, Spring 2013 March 26, 2013 Week 8, java.lang.Clonable & java.io.Serializable Interfaces.
SIVA PRASAD SANDIREDDY.  YzdS4.
Operating-System Structures
C# and Windows Programming Application Domains and Remoting.
The Android Activity Lifecycle. Slide 2 Introduction Working with the Android logging system Rotation and multiple layouts Understanding the Android activity.
Object Oriented Programming Files and Streams Dr. Mike Spann
C# - Files and Streams Outline Files and Streams Classes File and Directory Creating a Sequential-Access File Reading Data from a Sequential-Access.
Files & Streams. Files Introduction Files are used for long-term retention of large amounts of data, even after the program that created the data terminates.
Serialization objects created in a program reside in RAM through references object o; heap stack content.
Application Fundamentals. See: developer.android.com/guide/developing/building/index.html.
Chapter 12 File Management Systems
ASP.NET Programming with C# and SQL Server First Edition
Creating Sequential-Access File  Serializable attribute indicates to the compiler that objects of a class can be serialized– written to or read from a.
Sequential-access file Create, read and write an object into a sequential-access file Serialize and deserialize the object to write and read from a data.
Lesson 46: Using Information From the Web copy and paste information from a Web site print a Web page download information from a Web site customize Web.
CHAPTER 4: INTRODUCTION TO COMPUTER ORGANIZATION AND PROGRAMMING DESIGN Lec. Ghader Kurdi.
Classes and objects Practice 2. Basic terms  Classifier is an element of the model, which specifies some general features for a set of objects. Features.
WINDOWS SERVICES. Introduction You often need programs that run continuously in the background Examples: – servers –Print spooler You often need.
1 Binary Files ผศ. ดร. หมัดอามีน หมันหลิน Faculty of IST, MUT
1 Chapter 12 File Management Systems. 2 Systems Architecture Chapter 12.
 Wallace B. McClure  Scalable Development, Inc. Scalable Development, Inc. Building systems today that perform tomorrow. Designing & Building Windows.
Lector: Aliyev H.U. Lecture №5 Telecommunication network software design with.NET. Using streams for network programming TASHKENT UNIVERSITY OF INFORMATION.
Serialization  What is Serialization?  System.Serialization  Scenarios in Serialization  Basic Serialization  Custom Serialization.
File I/O 11_file_processing.ppt
Lecture 2 COM - Example. Integrate the web Webcam functionality using.Net and COM First let's explain what we should do exactly. First let's explain what.
Serialization. Serialization is the process of converting an object into an intermediate format that can be stored (e.g. in a file or transmitted across.
Java Threads. What is a Thread? A thread can be loosely defined as a separate stream of execution that takes place simultaneously with and independently.
Reference: Lecturer Lecturer Reham O. Al-Abdul Jabba lectures for cap211 Files and Streams- I.
Object Persistence and Object serialization CSNB534 Asma Shakil.
Serialization What is Serialization Serialization is the process of converting an object, or a connected graph of objects, stored within computer memory,
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
Module 5: Implementing Printing. Overview Introduction to Printing in the Windows Server 2003 Family Installing and Sharing Printers Managing Access to.
CSC1401 Classes - 1. Learning Goals Computing concepts Identifying objects and classes Declaring a class Declaring fields Default field values.
Object Oriented Software Development 10. Persistent Storage.
10-Nov-15 Java Object Oriented Programming What is it?
Lecture 19 Serialization Richard Gesick. Serialization Sometimes it is easier to read or write entire objects than to read and write individual fields.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
CS360 Windows Programming
Method Overloading  Methods of the same name can be declared in the same class for different sets of parameters  As the number, types and order of the.
BIM313 – Advanced Programming File Operations 1. Contents Structure of a File Reading/Writing Texts from/to Files File and Directory Operations 2.
 Pearson Education, Inc. All rights reserved Files and Streams.
ASP.NET Web Services.  A unit of managed code installed under IIS that can be remotely invoked using HTTP.
Object Serialization.  When the data was output to disk, certain information was lost, such as the type of each value.  If the value "3" is read from.
Lecture 18 Windows – NT File System (NTFS)
IBM TSpaces Lab 2 Customizing tuples and fields. Summary Blocking commands Tuple Expiration Extending Tuples (The SubclassableTuple) Reading/writing user.
Serialization CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
©SoftMoore ConsultingSlide 1 Serialization. ©SoftMoore ConsultingSlide 2 Serialization Allows objects to be written to a stream Can be used for persistence.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Input and Output 23: Input and Output
CSC 298 Streams and files.
Spring 2008 Mark Fontenot CSE Honors Principles of Computer Science I Note Set 20.
Files and Streams. What is a file? Up until now, any stored data within a program is lost when the program closes. A file is a permanent way to store.
Files and Streams. Objectives Learn about the classes that support file input/output Understand the concept of abstraction and how it related to the file.
CHAPTER 9 File Storage Shared Preferences SQLite.
1 CSE 331 Memento Pattern and Serialization slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
1 Handling Errors and Exceptions Chapter 6. 2 Objectives You will be able to: 1. Use the try, catch, and finally statements to handle exceptions. 2. Raise.
Chapter 2: System Structures
Activities and Intents
18 Files and Streams.
The Android Activity Lifecycle
Serialization.
Lectures 12 Files & Streams Dr. Eng. Ibrahim El-Nahry.
Files and Streams.
Files and Streams Lect3 CT1411.
CSE 331 Memento Pattern slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Fundaments of Game Design
by Santosh Reddy Vuppala
Files and Streams.
Chapter 11 Saving Data and Objects In Files
Presentation transcript:

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 service  The service might be started again at a later time

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 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 constructor public Service1() { InitializeComponent(); this.ServiceName = "WindowsService1"; }

10 Service1 protected override void OnStart(string[] args) { try { writer = 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\v  Where the final numbers are the build number and might change

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 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 primitive  Any 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 for  Saving objects to disk  Transmitting objects across a network  Transmitting objects as parameters of remote procedure calls

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 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 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 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 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 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 must  Be declared Serializable  Have a parameterless constructor  Declare all fields which are to be serialized as public  Contain 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 settings  Recently opened files  Last screen position  User’s preferred color In the past, these have been stored in .ini files  The 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 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 Reading Isolated Storage IsolatedStorageFileStream isf = new IsolatedStorageFileStream(“tst.cfg”, FileMode.Open); StreamReader reader = new StreamReader(isf); string line = reader.ReadLine();