Chapter 8 use C # To write Components

Source: Internet
Author: User
Tags send cookies

Chapter 8 use C # To write Components

This chapter describes how to use C # To write components. You learned how to write a component, compile it, and use it in a client program. A further step is to use namespace to organize your applications.
This chapter consists of two major sections:
. Your first component
. Work with namespace

8.1 your first component
So far, the examples mentioned in this book all use a class directly in the same application. Class and its users are included in the same execution file. Now we will separate classes from users into components and customers, which are located in different binary files (executable files ).
Although you still create a DLL for the component, the steps differ greatly from writing a COM component in C ++. You seldom involve the underlying structure. The following sections describe how to build a component and its customers:

. Build Components
. Compile Components
. Create a simple customer application

8.1.1 build component
Because I am a fan of examples, I decided to create a related Web class for your convenience. It returns a Web page and stores it in a string
Variable for later reuse. All of these are written in reference to the. NET Framework help documentation.
The class name is RequestWebPage. It has two constructors: one attribute and one method. The property is named URL and stores the Web location of the webpage.
Address, Which is returned by the GetContent method. This method does all the work for you (see Listing 8.1 ).

Listing 8.1 RequestWebPage class used to return HTML webpages from the Web Server

1: using System;
2: using System. Net;
3: using System. IO;
4: using System. Text;
5:
6: public class RequestWebPage
7 :{
8: private const int BUFFER_SIZE = 128;
9: private string m_strURL;
10:
11: public RequestWebPage ()
12 :{
13 :}
14:
15: public RequestWebPage (string strURL)
16 :{
17: m_strURL = strURL;
18 :}
19:
20: public string URL
21 :{
22: get {return m_strURL ;}
23: set {m_strURL = value ;}
24 :}
25: public void GetContent (out string strContent)
26 :{
27: // check the URL
28: if (m_strURL = "")
29: throw new ArgumentException ("URL must be provided .");
30:
31: WebRequest theRequest = (WebRequest) WebRequestFactory. Create (m_strURL );
32: WebResponse theResponse = theRequest. GetResponse ();
33:
34: // set the byte buffer for the response
35: int BytesRead = 0;
36: Byte [] Buffer = new Byte [BUFFER_SIZE];
37:
38: Stream ResponseStream = theResponse. GetResponseStream ();
39: BytesRead = ResponseStream. Read (Buffer, 0, BUFFER_SIZE );
40:
41: // use StringBuilder to accelerate the allocation process
42: StringBuilder strResponse = new StringBuilder ("");
43: while (BytesRead! = 0)
44 :{
45: strResponse. Append (Encoding. ASCII. GetString (Buffer, 0, BytesRead ));
46: BytesRead = ResponseStream. Read (Buffer, 0, BUFFER_SIZE );
47 :}
48:
49: // assign the parameter to the output
50: strContent = strResponse. ToString ();
51 :}
52 :}

This should have been done using a non-parameter constructor, but I decided to initialize the URL in the constructor, which may be useful. When you decide to change the URL
-- In order to return the second webpage, for example, it is made public through the get and set access flag of the URL attribute.
The interesting thing starts with the GetContent method. First, the Code implements a very simple check on the URL. If it is not suitable, it will trigger
ArgumentException exception. Then, I request WebRequestFactory to create a WebRequest object based on the URL passed to it.
Because I do not want to send cookies, append headers, and query strings, I can access WebResponse (row 32nd) immediately ). If you need to request any of the above
Yes, they must be implemented before this line.
Lines 35th and 36 initialize a byte buffer, which is used to read data from the returned stream. Temporarily ignore the StringBuilder class, as long as there are still
The while loop will simply repeat the read data. The last read operation returns zero, so the loop ends.
Now I want to return to the StringBuilder class. Why use the instance of this class instead of simply merging the byte buffer into a string variable? See the following
Example:
StrMyString = strMyString + "some more text ";
It is clear that you are copying the value. Constant "some more text" is framed as a string variable type, and a new
. Then it is assigned to strMyString. There are many copies, right?
But you may be controversial.
StrMyString + = "some more text ";
Do not show off such behavior. Sorry, this is a wrong answer for C. The operation is exactly the same as the value assignment operation.
The StringBuilder class is used to avoid this problem. It uses a buffer to work, and then, in the absence of the copy I described
You can perform append, insert, delete, and replace operations. This is why I use it in the class to merge the content that is read from the buffer.
This buffer brings me into this class the encoding conversion of the last important code snippet-row 45th. It only involves the character set in which I get the request.
Finally, when all the content is read and converted, I explicitly requested a String object from StringBuilder and assigned it to the output variable. I
Will still lead to another copy operation.

8.1.2 compile Components
So far, your work is no different from writing a class in a normal application. The difference is the compilation process. You must create
Databases instead of applications:
Csc/r: System. Net. dll/t: library/out: wrq. dll webrequest. cs
Compile switch/t: the library tells C # To compile. Instead of searching for a static Main method, create a library. Similarly, because I am using
System. Net namespace, so you must reference (/r :) its library, which is System. Net. dll.
Your library is named wrq. dll. Now it is ready for use in a customer application. Because in this chapter I only use private components to work, you do not have
Copy to a special location, but copy to the client application directory.

8.1.3 create a simple customer application
When a component is written and compiled successfully, all you need to do is use it in the customer application. I created a simple command line interface again.
It returns the homepage of a development site I maintain (see listing 8.2 ).

Listing 8.2 using the RequestWebPage class to return a simple webpage

1: using System;
2:
3: class TestWebReq
4 :{
5: public static void Main ()
6 :{
7: RequestWebPage wrq = new RequestWebPage ();
8: wrq. URL = "http://www.alphasierrapapa.com/iisdev ";
9:
10: string strResult;
11: try
12 :{
13: wrq. GetContent (out strResult );
14 :}
15: catch (Exception e)
16 :{
17: Console. WriteLine (e );
18: return;
19 :}
20:
21: Console. WriteLine (strResult );
22 :}
Member

Note: I have included the call to GetContent in a try catch statement. One of the reasons is that GetContent may trigger
ArgumentException exception. In addition, the. NET Framework class that I call inside the component can also cause exceptions. Because I cannot handle these exceptions within the class,
So I have to process them here.
The rest of the code is just the use of simple components-call standard constructors, access an attribute, and execute a method. But wait: you need
Pay attention to when to compile the application. Make sure to tell the compiler to reference your new component library DLL:
Csc/r: wrq. dll wrclient. cs
Now everything is ready. You can test the program. The output results will be rolled out, but you can see that the application is working. You can also
Add code to parse the returned HTML and extract information based on your personal preferences. I expected to use the new SSL (Secure Socket Layer) of this class ),
For ASP + network

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.