Tải bản đầy đủ - 0 (trang)
10-15. Process the Content of an Atom or RSS Feed

10-15. Process the Content of an Atom or RSS Feed

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

CHAPTER 10 ■ NETWORKING



To load feed data for processing, use the SyndicationFeedFormatter.ReadFrom method and pass it a

System.Xml.XmlReader that provides access to the feed data. Once loaded with feed data, the

SyndicationFeedFormatter.Feed property provides access to a SyndicationFeed object allowing you to

use the properties listed in Table 10-5 to access the feed attributes.

Table 10-5. Properties of the SyndicatedFeed Class



Property



Description



Authors



Gets a collection of authors from the feed



BaseUri



Gets the base URI from the feed



Categories



Gets a collection of categories from the feed



Description



Gets the description from the feed



Id



Gets the ID from the feed



ImageUrl



Gets the image URL from the feed



Items



Gets the collection of items contained in the feed



Language



Gets the language from the feed



LastUpdatedTime



Gets the last updated time from the feed



Links



Gets a collection of links associated with the feed



Title



Gets the title from the feed



The SyndicationFeed.Items property provides access to the set of items contained in the feed. Each

item is represented by a SyndicationItem. Table 10-6 lists the properties that provide access to the

attributes of a feed item.



535



www.it-ebooks.info



CHAPTER 10 ■ NETWORKING



Table 10-6. Properties of the SyndicationItem Class



Property



Description



Authors



Gets a collection of authors from the feed item



BaseUri



Gets the base URI from the feed item



Categories



Gets a collection of categories from the feed item



Content



Gets the content from the feed item



Id



Gets the ID from the feed item



Language



Gets the language from the feed item



LastUpdatedTime



Gets the last updated time from the feed item



Links



Gets a collection of links associated with the feed



Summary



Gets the summary from the feed item



Title



Gets the title from the feed item



The Code

The following example takes the URL of a feed as a command-line argument, downloads the feed,

determines whether it is an RSS or Atom feed, and parses it using the appropriate

SyndicationFeedFormatter. The output from running the example contains the title and description of

the overall feed, and then the title, summary, and publication date of each item in the feed.

using

using

using

using



System;

System.Net;

System.ServiceModel.Syndication;

System.Xml.Linq;



namespace Apress.VisualCSharpRecipes.Chapter10

{

class Recipe10_15

{

static void Main(string[] args)

{

Uri feedUrl = null;



536



www.it-ebooks.info



CHAPTER 10 ■ NETWORKING



if (args.Length == 0 || String.IsNullOrEmpty(args[0])

|| !Uri.TryCreate(args[0], UriKind.RelativeOrAbsolute,

out feedUrl))

{

// Error and wait to continue.

Console.WriteLine("Invalid feed URL. Press Enter.");

Console.ReadLine();

return;

}

// Create the web request based on the URL provided for the feed.

WebRequest req = WebRequest.Create(feedUrl);

// Get the data from the feed.

WebResponse res = req.GetResponse();

// Simple test for the type of feed: Atom 1.0 or RSS 2.0.

SyndicationFeedFormatter formatter = null;

XElement feed = XElement.Load(res.GetResponseStream());

if (feed.Name.LocalName == "rss")

{

formatter = new Rss20FeedFormatter();

}

else if (feed.Name.LocalName == "feed")

{

formatter = new Atom10FeedFormatter();

}

else

{

// Error and wait to continue.

Console.WriteLine("Unsupported feed type: "

+ feed.Name.LocalName);

Console.ReadLine();

return;

}

// Read the feed data into the formatter.

formatter.ReadFrom(feed.CreateReader());

// Display feed level data:

Console.WriteLine("Title: " + formatter.Feed.Title.Text);

Console.WriteLine("Description: "

+ formatter.Feed.Description.Text);

Console.Write(Environment.NewLine);

Console.WriteLine("Items: ");



537



www.it-ebooks.info



CHAPTER 10 ■ NETWORKING



// Display the item data.

foreach (var item in formatter.Feed.Items)

{

Console.WriteLine("\tTitle: " + item.Title.Text);

Console.WriteLine("\tSummary: " + item.Summary.Text);

Console.WriteLine("\tPublish Date: " + item.PublishDate);

Console.Write(Environment.NewLine);

}

// Wait to continue.

Console.WriteLine(Environment.NewLine);

Console.WriteLine("Main method complete. Press Enter.");

Console.ReadLine();

}

}

}



10-16. Manipulate URIs

Problem

You need to construct a well-formed URI or extract the component parts of a provided URI.



Solution

Use the System.Uri class to extract the component parts of an existing URI and the System.UriBuilder

class to construct a new well-formed URI.



How It Works

When doing web or network programming, you will regularly need to manipulate URIs and their closely

related derivatives: URNs and URLs. For example, you may need to construct URLs that represent

servers and network resources you want to access, or extract information like the host, port, or protocol

specified in an externally provided URI.

The System.Uri class provides an object representation of a URI and implements properties that

allow you to extract the various elements that constitute the URI. To create a Uri, pass the string

representing the URI you want to parse to the Uri constructor. A number of constructor overloads allow

you to handle both absolute and relative URIs. However, if the URI string is invalid, the constructor will

throw a System.UriFormatException. To avoid this, you can use the static method Uri.TryCreate, which

returns true if the parse was successful and false otherwise.

Once you have a Uri object, you can use its properties to extract specific components of the URI.

Table 10-7 contains some commonly used properties of the Uri class.



538



www.it-ebooks.info



CHAPTER 10 ■ NETWORKING



Table 10-7. Commonly Used Members of the Uri Class



Property



Description



AbsolutePath



Gets a string that contains the absolute path of the URI



AbsoluteUri



Gets a string representation of the full URI as an absolute address



Host



Gets a string containing the host name specified in the URI



IsDefaultPort



Gets a bool indicating whether the specified port is the default port for the URI

scheme



OriginalString



Gets the original string used to construct the Uri



Port



Gets an int containing the port number specified in the URI



Query



Gets a string containing the query string specified in the URI



Scheme



Gets a string containing the scheme specified in the URI



The Uri class is read-only, so if you want to create a new well-formed URI, you should use the

UriBuilder class. You can specify the key elements of the URI in various overloads of the UriBuilder

constructor, or you can configure a new UriBuilder object via its properties. Table 10-8 describes the

properties of the UriBuilder class.

Table 10-8. Properties of the UriBuilder Class



Property



Description



Fragment



Gets or sets a string specifying the fragment element of the URI. This is the part after the

hash symbol (#) found at the end of URLs.



Host



Gets or sets a string specifying the host element of the URI.



Password



Gets or sets a string specifying the password to use with the URI.



Path



Gets or sets a string specifying the path element of the URI.



Port



Gets or sets an int specifying the port element of the URI.



Query



Gets or sets a string specifying the query string element of the URI.



539



www.it-ebooks.info



CHAPTER 10 ■ NETWORKING



Property



Description



Scheme



Gets or sets a string specifying the scheme element of the URI.



UserName



Gets or sets a string containing the username to use with the URI.



Once you have configured the UriBuilder, you obtain an appropriately configured Uri object

representing the URI via the UriBuilder.Uri property. Many methods that require URIs take Uri

instances, but if you need a string representation of the URI you can use the Uri.AbsolutePath property.



The Code

The following code demonstrates the use of the Uri and UriBuilder classes.

using

using

using

using



System;

System.Collections.Generic;

System.Linq;

System.Text;



namespace Apress.VisualCSharpRecipes.Chapter10

{

class Recipe10_16

{

private static string defualtUrl

= "http://www.apress.com:80/book/view/9781430225256";

static void Main(string[] args)

{

Uri uri = null;

// Extract information from a string URL passed as a

// command line argument or use the default URL.

string strUri = defualtUrl;

if (args.Length > 0 && !String.IsNullOrEmpty(args[0]))

{

strUri = args[0];

}

// Safely parse the url

if (Uri.TryCreate(strUri, UriKind.RelativeOrAbsolute, out uri))

{

Console.WriteLine("Parsed URI: " + uri.OriginalString);

Console.WriteLine("\tScheme: " + uri.Scheme);

Console.WriteLine("\tHost: " + uri.Host);

Console.WriteLine("\tPort: " + uri.Port);

Console.WriteLine("\tPath and Query: " + uri.PathAndQuery);

}



540



www.it-ebooks.info



CHAPTER 10 ■ NETWORKING



else

{

Console.WriteLine("Unable to parse URI: " + strUri);

}

// Create a new URI.

UriBuilder newUri = new UriBuilder();

newUri.Scheme = "http";

newUri.Host = "www.apress.com";

newUri.Port = 80;

newUri.Path = "book/view/9781430225256";

Console.WriteLine(Environment.NewLine);

Console.WriteLine("Created URI: " + newUri.Uri.AbsoluteUri);

// Wait to continue.

Console.WriteLine(Environment.NewLine);

Console.WriteLine("Main method complete. Press Enter.");

Console.ReadLine();

}

}

}



541



www.it-ebooks.info



www.it-ebooks.info



C H A P T E R 11

■■■



Security and Cryptography

Prior to version 4.0, the .NET Framework incorporated two complementary security models that

addressed user and code security: role-based security (RBS) and code access security (CAS). With version

4.0, CAS has been deprecated. The previous edition of this book included a number of CAS recipes (11-1

through to 11-7), and we have included them in this new version because of the number of developers

still using .NET 3.5 or earlier, where CAS still has a significant function. The C# compiler will show

deprecation warnings if you use CAS in a project. You can prevent these errors by targeting your project

at an earlier version of the .NET Framework on the Application tab. You can enable CAS in your .NET 4.0

projects with the NetFx40_LegacySecurityPolicy configuration element in the app.config file—for

example:













RBS remains current in .NET 4.0 and allows you to make runtime decisions based on the identity

and roles of the user on whose behalf an application is running. On the Windows operating system, this

equates to making decisions based on the Windows username and the Windows groups to which that

user belongs. However, RBS provides a generic security mechanism that is independent of the

underlying operating system, allowing you (with some development) to integrate with any user account

system.

An important aspect of the security features provided by the .NET Framework is cryptography.

Cryptography is one of the most complex aspects of software development that any developer will use.

The theory of modern cryptographic techniques is extremely difficult to understand and requires a level

of mathematical knowledge that relatively few people have or need. Fortunately, the Microsoft .NET

Framework class library provides easy-to-use implementations of the most commonly used

cryptographic techniques and support for the most popular and well-understood algorithms.

This chapter provides a wide variety of recipes that cover some of the more commonly used security

capabilities provided by the .NET Framework. As you read the recipes in this chapter and think about

how to apply the techniques to your own code, keep in mind that individual security features are rarely

effective when implemented in isolation. In particular, cryptography does not equal security; the use of

cryptography is merely one small element of creating a secure solution.



543



www.it-ebooks.info



CHAPTER 11 ■ SECURITY AND CRYPTOGRAPHY



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





Develop strongly named assemblies that can still be called by partially trusted

code (recipe 11-1)







Configure the .NET Framework security policy to turn off CAS completely or turn

off only execution permission checks (recipes 11-2 and 11-3)







Request specific code access permissions for your assemblies, determine at

runtime what permissions the current assembly has, and inspect third-party

assemblies to determine what permissions they need in order to run correctly

(recipes 11-4, 11-5, 11-6, and 11-7)







Control inheritance and member overrides using CAS (recipe 11-8)







Inspect the evidence presented by an assembly to the runtime when the assembly

is loaded (recipe 11-9)







Integrate with Windows security to determine if a user is a member of a specific

Windows group, restrict which users can execute your code, and impersonate

other Windows users (recipes 11-10, 11-11, and 11-12)







Generate random numbers that are nondeterministic and are suitable for use in

security-sensitive applications (recipe 11-13)







Use hash codes and keyed hash codes to store user passwords and determine if

files have changed (recipes 11-14, 11-15, 11-16, and 11-17)







Use encryption to protect sensitive data both in memory and when it is stored to

disk (recipes 11-18 and 11-19)



11-1. Allow Partially Trusted Code to Use Your Strongly

Named Assembly

Problem

You need to write a shared assembly that is accessible to partially trusted code. (By default, the runtime

does not allow partially trusted code to access the types and members contained in a strongly named

assembly.)



Solution

Apply the assembly-level attribute System.Security.AllowPartiallyTrustedCallersAttribute to your

shared assembly.



544



www.it-ebooks.info



CHAPTER 11 ■ SECURITY AND CRYPTOGRAPHY



■ Note CAS is deprecated in .NET 4.0.



How It Works

To minimize the security risks posed by malicious code, the runtime does not allow assemblies granted

only partial trust to access strongly named assemblies. This restriction dramatically reduces the

opportunity for malicious code to attack your system, but the reasoning behind such a heavy-handed

approach requires some explanation.

Assemblies that contain important functionality that is shared between multiple applications are

usually strongly named and are often installed in the Global Assembly Cache (GAC). This is particularly

true of the assemblies that constitute the .NET Framework class library. Other strongly named

assemblies from well-known and widely distributed products are in the GAC and accessible to managed

applications. The high chance that certain assemblies will be present in the GAC, their easy accessibility,

and their importance to many different applications make strongly named assemblies the most likely

target for any type of subversive activity by malicious managed code.

Generally, the code most likely to be malicious is that which is loaded from remote locations over

which you have little or no control (such as over the Internet). Under the default security policy of the

.NET Framework, all code run from the local machine has full trust, whereas code loaded from remote

locations has only partial trust. Stopping partially trusted code from accessing strongly named

assemblies means that partially trusted code has no opportunity to use the features of the assembly for

malicious purposes, and cannot probe and explore the assembly to find exploitable holes. Of course, this

theory hinges on the assumption that you correctly administer your security policy. If you simply assign

all code full trust, not only will any assembly be able to access your strongly named assembly, but the

code will also be able to access all of the functionality of the .NET Framework and even Win32 or any

COM object through P/Invoke and COM Interop. That would be a security disaster!



■ Note If you design, implement, and test your shared assembly correctly using CAS to restrict access to

important members, you do not need to impose a blanket restriction to prevent partially trusted code from using

your assembly. However, for an assembly of any significance, it’s impossible to prove there are no security holes

that malicious code can exploit. Therefore, you should carefully consider the need to allow partially trusted code to

access your strongly named assembly before applying AllowPartiallyTrustedCallersAttribute. However, you

might have no choice. If you are exposing public classes that provide events, you must apply this attribute. If you

do not, an assembly that is not strongly named will be allowed to register a handler for one of your events, but

when it is called, a security exception will be thrown. Code in an assembly that is not strongly named is not

allowed to call code in a strongly named assembly.



The runtime stops partially trusted code from accessing strongly named assemblies by placing an

implicit LinkDemand for the FullTrust permission set on every public and protected member of every

publicly accessible type defined in the assembly. This means that only assemblies granted the

permissions equivalent to the FullTrust permission set are able to access the types and members from



545



www.it-ebooks.info



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

10-15. Process the Content of an Atom or RSS Feed

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

×