Tải bản đầy đủ - 0 (trang)
5-25. Process a Log File

5-25. Process a Log File

Tải bản đầy đủ - 0trang

CHAPTER 5 ■ FILES, DIRECTORIES, AND I/O



foreach (string entry in somedata)

{

Console.WriteLine("Error entry: {0}", entry);

}

// Read selected lines and write only the first character.

IEnumerable chardata = File.ReadLines("all_entries.log").Where(e

=> !e.StartsWith("Error")).Select(e => e[0]);

foreach (char entry in chardata)

{

Console.WriteLine("Character entry: {0}", entry);

}

}

}

}



5-26. Communicate Between Processes

Problem

You need to send and receive data from one process to another.



Solution

Use named pipes. You create an instance of System.IO.Pipes.NamedPipeServerStream and call the

WaitForConnection method in one of your processes. In the other process, create an instance of

System.IO.Pipes.NamedPipeClientStream and call the Connect method. This creates a two-way data

stream between your processes that you can use to read and write data.



How It Works

Named pipes are an interprocess communication mechanism that allows processes to exchange data.

Each pipe is created by a server and can accept multiple client connections—once the connection is

established (using the WaitForConnection and Connect methods described previously), the server and

client can communicate using the normal .NET Framework streams mechanism—see the other recipes

in this chapter to learn more about streams. You must use the same name for both the server and client

pipes.



The Code

The following example contains both a pipe server and a pipe client in one class—if the executable is

started with the command-line argument client, then the pipe client will operate; otherwise, the pipe

server will run. The server creates a named pipe and waits for a client to connect. When the client

connects, the server writes ten messages to the client, and then reads ten responses.



257



www.it-ebooks.info



CHAPTER 5 ■ FILES, DIRECTORIES, AND I/O



■ Note Named pipes can be used to communicate between processes running on different computers. See the

.NET Framework documentation for details.



using

using

using

using

using

using



System;

System.Collections.Generic;

System.Linq;

System.Text;

System.IO;

System.IO.Pipes;



namespace Recipe05_26

{

class Recipe05_26

{

static void Main(string[] args)

{

if (args.Length > 0 && args[0] == "client")

{

pipeClient();

}

else

{

pipeServer();

}

}

static void pipeServer()

{

// Create the server pipe.

NamedPipeServerStream pipestream = new

NamedPipeServerStream("recipe_05_26_pipe");

// Wait for a client to connect.

Console.WriteLine("Waiting for a client connection");

pipestream.WaitForConnection();

Console.WriteLine("Received a client connection");

// Wrap a stream writer and stream reader around the pipe.

StreamReader reader = new StreamReader(pipestream);

StreamWriter writer = new StreamWriter(pipestream);

// Write some data to the pipe.

for (int i = 0; i < 10; i++)

{

Console.WriteLine("Writing message ", i);

writer.WriteLine("Message {0}", i);

writer.Flush();

}



258



www.it-ebooks.info



CHAPTER 5 ■ FILES, DIRECTORIES, AND I/O



// Read data from the pipe.

for (int i = 0; i < 10; i++)

{

Console.WriteLine("Received: {0}", reader.ReadLine()); ;

}

// Close the pipe.

pipestream.Close();

}

static void pipeClient()

{

// Create the client pipe.

NamedPipeClientStream pipestream = new

NamedPipeClientStream("recipe_05_26_pipe");

// connect to the pipe server

pipestream.Connect();

// Wrap a reader around the stream.

StreamReader reader = new StreamReader(pipestream);

StreamWriter writer = new StreamWriter(pipestream);

// Read the data.

for (int i = 0; i < 10; i++)

{

Console.WriteLine("Received: {0}", reader.ReadLine());

}

// Write data to the pipe.

for (int i = 0; i < 10; i++)

{

Console.WriteLine("Writing response ", i);

writer.WriteLine("Response {0}", i);

writer.Flush();

}

// Close the pipe.

pipestream.Close();

}

}

}



259



www.it-ebooks.info



www.it-ebooks.info



CHAPTER 6

■■■



XML Processing

One of the most remarkable aspects of the Microsoft .NET Framework is its deep integration with XML.

In many .NET applications, you won’t even be aware you’re using XML technologies—they’ll just be

used behind the scenes when you serialize a Microsoft ADO.NET DataSet, call a web service, or read

application settings from a Web.config configuration file. In other cases, you’ll want to work directly with

the System.Xml namespaces to manipulate Extensible Markup Language (XML) data. Common XML

tasks don’t just include parsing an XML file, but also include validating it against a schema, applying an

Extensible Stylesheet Language (XSL) transform to create a new document or Hypertext Markup

Language (HTML) page, and searching intelligently with XPath.

In .NET 3.5, Microsoft added LINQ to XML, which integrates XML handling into the LINQ model for

querying data sources. You can use the same keywords and syntax to query XML as you would a

collection or a database.

The recipes in this chapter describe how to do the following:





Read, parse, and manipulate XML data (recipes 6-1, 6-2, 6-3, and 6-7)







Search an XML document for specific nodes, either by name (recipe 6-4), by

namespace (recipe 6-5), or by using XPath (recipe 6-6)







Validate an XML document with an XML schema (recipe 6-8)







Serialize an object to XML (recipe 6-9), create an XML schema for a class (recipe 610), and generate the source code for a class based on an XML schema (recipe 611)







Transform an XML document to another document using an XSL Transformations

(XSLT) stylesheet (recipe 6-12)







Use LINQ to XML to load, create, query and modify XML trees (recipes 6-13, 6-14,

6-15, and 6-16).



6-1. Show the Structure of an XML Document in a TreeView

Problem

You need to display the structure and content of an XML document in a Windows-based application.



261



www.it-ebooks.info



CHAPTER 6 ■ XML PROCESSING



Solution

Load the XML document using the System.Xml.XmlDocument class. Create a reentrant method that

converts a single XmlNode into a System.Windows.Forms.TreeNode, and call it recursively to walk through

the entire document.



How It Works

The .NET Framework provides several different ways to process XML documents. The one you use

depends in part upon your programming task. One of the most fully featured classes is XmlDocument,

which provides an in-memory representation of an XML document that conforms to the W3C Document

Object Model (DOM). The XmlDocument class allows you to browse through the nodes in any direction,

insert and remove nodes, and change the structure on the fly. For details of the DOM specification, go to

www.w3c.org.



■ Note The XmlDocument class is not scalable for very large XML documents, because it holds the entire XML

content in memory at once. If you want a more memory-efficient alternative, and you can afford to read and

process the XML piece by piece, consider the XmlReader and XmlWriter classes described in recipe 6-7.



To use the XmlDocument class, simply create a new instance of the class and call the Load method with

a file name, a Stream, a TextReader, or an XmlReader object. It is also possible to read the XML from a

simple string with the LoadXML method. You can even supply a string with a URL that points to an XML

document on the Web using the Load method. The XmlDocument instance will be populated with the tree

of elements, or nodes, from the source document. The entry point for accessing these nodes is the root

element, which is provided through the XmlDocument.DocumentElement property. DocumentElement is an

XmlElement object that can contain one or more nested XmlNode objects, which in turn can contain more

XmlNode objects, and so on. An XmlNode is the basic ingredient of an XML file. Common XML nodes

include elements, attributes, comments, and contained text.

When dealing with an XmlNode or a class that derives from it (such as XmlElement or XmlAttribute),

you can use the following basic properties:





ChildNodes is an XmlNodeList collection that contains the first level of nested

nodes.







Name is the name of the node.







NodeType returns a member of the System.Xml.XmlNodeType enumeration that

indicates the type of the node (element, attribute, text, and so on).







Value is the content of the node, if it’s a text or CDATA node.







Attributes provides a collection of node objects representing the attributes

applied to the element.







InnerText retrieves a string with the concatenated value of the node and all nested

nodes.



262



www.it-ebooks.info



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

5-25. Process a Log File

Tải bản đầy đủ ngay(0 tr)

×