Visual C # Implement the design of custom components

xiaoxiao2021-03-06  73

One. Foreword

Visual C # As an emerging programming language, many other languages ​​cannot match the advantages. It has both VB fast and simple, and it is not a high performance of C , and as a component-based language, it has considerable powerful and perfect features in component programming. This article describes a POP3 mail receiving component by using Visual C #, introduces you how to use Visual C # to make component programming and some methods and techniques during programming, and finally give the Windows Forms program that tests the POP3 component.

two. Fundamental

To complete a POP3 component, you should complete the design of the property, method, method (Method), and events (Event). Attribute is an important feature of a component, one component generally has multiple properties. We can get and set values ​​for each attribute through GET and SET. The settings of each attribute are completed, and we can perform the appropriate operations through various methods of the component. And the event is triggered under certain messages. In C #, we use the DELEGATE statement.

In this POP3 component, we add host name (host), port number (port), username, password, number of mail, mail size, etc., by ReceiveMessage () And ReceiveMessageASync () methods Complete functions such as connectivity, communication, and end sessions, etc., after calling the method, we can get information in the mailbox from the number of emails and mail size, and then use the component Easily develop programs such as mail letter history. At the same time, the component also includes an onmailReceived () event that is triggered after the message is completed.

During the design of the component, the connection communication with the host is the core part of the component, so we may wish to design a connection with the host's connection class -POP3Connection class, which is mainly used by TCPCLIENT classes, and the host is established based on TCP / IP network protocol connection. After the connection is completed, you can communicate with the host. After the communication is complete, turn off the connection with the host. After the implementation principle, the following is the specific implementation method.

three. Implementation

First, open VS.NET, create a new Visual C # item: Select "Visual C # item" in the project type, select "Class Library" in the template, and name "POP3COM" (this is generated by the project) The namespace of the component is POP3COM), as shown below:

1. POP3CONNECTION Class:

In this way, the project wizard is completed, then we will rename the original class1.cs to pop3.cs, and add a class POP3Connection (file name may be POP3Connection.cs).

As mentioned above, the POP3Connection class completes features such as connectivity, communication, and closing connections to the host, so we must call the class library of network communication in the .NET framework, where we use the TCPClient class as a customer end. At the same time, the control of the input and output stream is inevitably in communication with the host's communication process. So, when we design this class, we first have to add the following namespace: use system.io; useing system.net.sockets; member variables of the Pop3Connection class include the following: Private TcpClient Socket; Private StreamReader Reader; Private streamwriter Writer Private bool connection;

Among them, the BOOL type Connected variable is used to determine whether to connect with the host, it is an attribute of such a class, and the operation is as follows:

The main method of public Bool Connected;}} POP3Connection class includes the following: Internal Void Open (String Host, INT Port) {if (Host == Null || host.trim (). Length == 0 || port <= 0) {throw new system.ArgumentException ("INVALID Argument Found.");} Socket.connect (Host, Port); Reader = New StreamReader (Socket.getStream (), System.Text.Encoding.ascii ); Writer = new streamwriter (socket.getStream (), system.text.encoding.ascii; connection = true;} Internal void sendcommand (String cmd); Writer.Flush ();} Internal Void getReply (Out string reply, out amount) {reply = reader.readLine (); code = reply == null? -1: int32.parse (reply.substring (0, 3));} Internal void close () {Reader.close (); writer.flush (); Writer.close (); reader = null; writer = null; socket.close (); connezE;

Based on the names of these methods, we don't really know their role. The first method Open () is based on the host name and port number acquisition and the server's connection. Once the connection is successful, you can get the network communication stream through the TCPClient class and create a streamReader object and a StreamWriter object. It goes without saying that the role of these two objects is to control the output and input of network communication. Finally, set the Connected property to True. The second method SendCommand () is based on the object Writer of the STREAMWRITER class above to enter the network socket. The third method getReply () is just the opposite, it is used to get information from the network socket. The last method close () is to close the output, input stream, and then call the TCPClient class's object close () method and set the connect property to false to turn off the connection and end the session. 2. POP3 class:

In this way, we have completed the design and coding of the POP3Connection class, and the most critical part of the entire component is completed. Next, we design the POP3 class on the basis of this class. The POP3 class contains basic properties, methods, and events necessary for mail communications.

First, let's design the properties. This class should include attributes such as host name, port number, user name, password, number of mail, total mail, mail content, status information. The first four attributes are readable and writable, and the last four attributes are readable. The specific settings are as follows:

///

/// CPU name

///

Public String Host

{

Get {return host;}

set

{

IF (value == null || value.trim (). Length == 0)

{

Throw new ArgumentException ("Invalid Host Name.");

}

Host = Value;

}

}

///

/// The port number

///

Public int port

{

Get {return port;}

set

{

IF (Value <= 0)

{

Throw New ArgumentException ("Invalid Port.");

}

Port = value;

}

}

///

/// username

///

Public String Username

{

Get {returna usrname;}

set

{

IF (value == null || value.trim (). Length == 0)

{

Throw new ArgumentException ("Invalid User Name);

}

Username = value;

}

}

///

/// password

///

Public String Password

{

Get {return password;}

set

{

IF (value == null)

{

Throw New ArgumentException ("Invalid Password.");

}

Password = Value;

}

}

///

/// mail quantity

///

Public Int Numofmails

{

Get {return numofmails;

}

///

/// The total volume of mail

///

Public Double Totalsize

{

Get {returnotateize;}

}

///

/// content of email///

Public String Body

{

Get {return body;}

}

///

/// status information

///

Public String Status

{

Get {return status;}

}

Complete the properties design of this class, we will then complete the method design of this class. The main method of this class is a receivedMessage (), as the name referphy is the meaning of receiving mail information. In this method, we use the objects of the Pop3Connection class above. Through this object, we can more conveniently perform the operation of network communication. However, before the implementation of this method, I first introduced you to the basic principles of mail.

The basic principles are as follows:

Attack, the client is connected to the server. However, before the client is connected to the server, pay attention to set the port to the POP3 protocol default 110.

After the client is successfully connected, the server will return the following information:

OK ...

Character OK is the return information of the POP3 protocol. Its response information is not represented by a rich variety of numbers like the SMTP protocol, only two: OK or -ERR. Among them, OK indicates that the connection is successful, and -ERR indicates the connection failure.

Next, the client enters User

This command tells the server your username. Note that some servers will distinguish between letters.

After the server returns OK, the client enters Pass

After the server returns OK, it also returns some mailbox statistics, such as: OK 1 Message (s) [1304 Byte (s)]

The information format returned by the different servers is not the same, so we can use the stat command to view the mailbox. There are two numbers in the response of the stat command, indicating the number of messages, and the size of the message.

If there is a letter in the mailbox, you can use the RETR command to get the body of the message. The RETR command has the format:

Retr

If the return result is the first line is OK information, it is successful. The second line is the body of the mail. Last row and SMTP protocol are a separate English sentence, indicating the end of the email.

Use the dele command to delete the email in the mailbox with the dele command, otherwise the original message will continue to keep on the server. Once you have more messages, your mailbox is burst. The format of the Dele command is:

Dele

If you are wrong, you can use the RSET command to restore all deleted messages. The condition is that you haven't quit yet, once you quit, then everything is BYE BYE. After all completed, enter the Quit command to exit the POP3 server.

On the basis of understanding the basic principles of mail reception, I will introduce you to the specific implementation of the receiveMessage () method:

///

// / receive mail information

///

Public void receiveMessage ()

{

/ / Avoid thread conflicts

LOCK (this)

{

/ / Set the initial connection

Con = new pop3connection ();

IF (port <= 0) port = 110;

Con.open (Host, Port);

Stringbuilder buf = new stringbuilder ();

String response;

Int code;

// Get welcome information

Con. GetReply (Out Response, Out Code);

STATUS = response;

// Log in to the server process

BUF.Append ("User"); buf.append (username);

BUF.Append (CRLF);

Con.sendCommand (buf.tostring ());

Con. GetReply (Out Response, Out Code);

STATUS = response;

BUF.LENGTH = 0;

BUF.Append ("pass");

BUF.Append (Password);

BUF.Append (CRLF);

Con.sendCommand (buf.tostring ());

Con. GetReply (Out Response, Out Code);

STATUS = response;

/ / Send a STAT command to the server to get information about the mailbox: the number of emails and the size

BUF.LENGTH = 0;

BUF.Append ("stat");

BUF.Append (CRLF);

Con.sendCommand (buf.tostring ());

Con. GetReply (Out Response, Out Code);

STATUS = response;

// Separate the total number of emails and email

String [] TotalStat = response.split (new char [] {''});

Numofmails = int32.parse (TotalStat [1]);

Totalsize = (double) int32.parse (TotalStat [2]);

For (int x = 0; x

{

/ / Get the corresponding message from the server according to the mail number

BUF.LENGTH = 0;

BUF.Append ("retr");

BUF.Append (x.toString ());

BUF.Append (CRLF);

Con.sendCommand (buf.tostring ());

Con. GetReply (Out Response, Out Code);

IF (Response [0]! = '-')

{

/ / Continuously read the email content, only to the end sign: English

While (Response! = ".")

{

Body = response;

Con. GetReply (Out Response, Out Code);

}

}

Else

STATUS = response;

}

/ / Send a quit command to the server to end and the session of the POP3 server

BUF.LENGTH = 0;

BUF.Append ("quit");

BUF.Append (CRLF);

Con.sendCommand (buf.tostring ());

Con. GetReply (Out Response, Out Code);

STATUS = response;

C. close ();

// Email the event that is triggered after success

IF (OnMailReceived! = NULL)

{

OnmailReceived ();

}

}

}

According to the basic principles and comments received by the message, I want to read the reader to understand the code above. However, the following point still has to be explained: where CRLF is "/ r / n", its role is to add a newline after each command. In addition, there is a sentence at the beginning of the method: LOCK (this), its role is to avoid thread conflicts. Considering that the process of receiving mail is relatively long and the occupied resources, I use a multi-thread when designing (for multi-threaded data readers can refer to the related books or articles, here is not described herein). In the actual program, the above method is actually called another method receiveMessageAseys () as a separate thread call. The method is as follows: //// Receive mail /// public void receivingMessageasync () {New Threadstart (ReceiveMessage)). Start ();

Finally, at the end of the receiveMessge () method, it calls the event handler onmailReceived (). In C #, the statement of the event is completed by the representative, first we declare the beginning of the POP3 class:

Public Delegate void mailreceiveddelegate ();

Then, the statement of the event:

Public Event mailreceiveddelegate onmailreceive;

Thus, as long as the onmailReceived () event is called in the application, the onmailReceived () event will be triggered after the message is successfully received.

To this end, we have completed the design of the attributes, methods, and events of the core class -POP3 class, so the entire component is completed (press Ctrl Shift B to generate a solution). However, since it is a component, we must not run directly, we must be a test program to test. Below I use this component to make a simple mail history, it can report the number of new mail in the mailbox.

four. The test program first adds a new project on the basis of the original solution. The project type is "Visual C # item", the template is "Windows Application", the name may wish to "Mailnotifier".

Then, the design main interface is as follows:

After designing the main interface, we have a code design. First, add a reference to the components -POP3COM on the above. Select Add Reference Under the Item menu, the Add Reference dialog box appears, add the POP3COM component to this item under the Projects page. The illustration is as follows:

At the same time, add a reference at the beginning of the code: USING POP3COM. This way, we can complete the corresponding functionality in the method of calling the classes in the POP3COM component in this program. Below is the "Start Check" button event handler:

Private void Checkbtn_Click (Object Sender, System.Eventargs E)

{

/ / Correctness check

IF (Host == Null || Host.Text.trim (). Length == 0)

{

MessageBox.show ("Please fill in server address!");

}

Else

IF (username == null || username.text.trim (). Length == 0) {

Messagebox.show ("Please fill in user name!");

}

Else

IF (Password == Null || Password.Text.trim (). Length == 0)

{

Messagebox.show ("Please fill in the password!");

}

Else

{

MAILER = New POP3 ();

MAILER.HOST = host.text;

MAILER.PORT = Int32.Parse (port.text);

MAILER.USERNAME = UserName.Text;

Mailer.password = password.text;

Statusbar.Text = "Receive information ...";

Mailer.onmailReceived = new pop3.mailreceiveddelegate (OnMailReceive);

Mailer.RecEiveMessageAsync ();

}

}

Among them, MAILER is an instance object of the POP3 class, which is the core object that completes the email check. At the same time, the ONMAILRECEIVED () event function is as follows:

Private void onlineReceived ()

{

STATUSBAR.TEXT = "Mail is received!"

Messagebox.show ("You have" mailer.numofmails.toString () "An email!", "Information",

MessageboxButtons.ok, MessageBoxicon.information;

}

In this way, the test program-mail history is also completed. Finally, pressing Ctrl F5 to run our program as follows:

Fives. summary:

Through the design of the POP3COM component, I want the reader to program the component programming under Visual C # should have a basic understanding. The design of the properties, methods, and events of the class should also be quite clear. Component programming is a strong term of Visual C #, so I hope the reader can learn further. At the same time, for the above components, the reader can also try to further improve, and may wish to use it in its own application, allowing it to play its powerful reuse.

Click

Download source code

转载请注明原文地址:https://www.9cbs.com/read-87559.html

New Post(0)