Difficulties in Visual C ++ programming (1)

Source: Internet
Author: User
Tags in domain

Reference: http://www.yesky.com/20030211/1651565.shtml

[Preface:] There are a lot of problems encountered in programming, and good programmers won't have any problems, but many solutions are drowned in the vast "water" of the Forum, to facilitate the simultaneous query and save these benefits, I will collect common issues in actual programming and excellent post replies in the Forum for presentation in the form of topics. All questions and answers in this article are from the Forum.

Question 1: How to enable the pop-up of the optical drive with the specified drive letter

The key is here:

Void ctrl_cdrom_door (
Lpctstr drivename, // The drive name, such as F.
Bool fopen file: // use True in pop-up and false in pop-up
)
{
Tchar devstr [2, 128], ctrlstr [2, 128];
Wsprintf (devstr, _ T ("Open % S type cdaudio alias mycd wait"), drivename );
Wsprintf (ctrlstr, _ T ("set mycd door % s wait"), fopen? _ T ("open"): _ T ("closed "));
Mcisendstring (devstr, null, 0, null );
Mcisendstring (ctrlstr, null, 0, null );
Mcisendstring (_ T ("Close mycd wait"), null, 0, null );
}
File: // sample code for testing.
Void cmainframe: ontestopen ()
{
// Todo: add your command handler code here
Ctrl_cdrom_door ("F:", true );
}
Void cmainframe: ontestclose ()
{
// Todo: add your command handler code here
Ctrl_cdrom_door ("F:", false );
}
  
Question 2: How to implement traditional simplified interchange?

The key is here:
// J2f. cpp: simplified (GB) ==> traditional => big5 Process
// Reverse conversion is similar.
// Note that big5 cannot correspond to each other directly from simplified --> big5. Is there a lot? Appears,
// Convert it to traditional Chinese and then to big5.
// I think this method should be consistent with the conciseness or character set conversion provided by winnt or office.
# Include "stdafx. H"
Using namespace STD;
Void j2f (const string & S)
{
Int n = S. Length ();
Int r = lcmapstring (
Makelcid (makelangid (lang_chinese, sublang_chinese_simplified), sort_chinese_prc ),
Lcmap_traditional_chinese,
S. c_str (), S. Length (), null, 0 );
If (! R) cout <"error:" <getlasterror () <Endl;
Char * Ft = new char [R + 1];
R = lcmapstring (
Makelcid (makelangid (lang_chinese, sublang_chinese_simplified), sort_chinese_prc ),
Lcmap_traditional_chinese,
S. c_str (), S. Length (), FT, R + 1); // This API is used to convert simplified to traditional Chinese.
If (r ){
FT [R] = 0;
Cout <ft <Endl;
Wchar_t * PWS = new wchar_t [R + 1];
Int R1 = multibytetowidechar (936,0, FT, R, PWS, R + 1 );
Bool F = false;
R1 = widechartomultibyte (950,0, PWS, R1, FT, R + 1 ,"? ", & F); // code page switch to activate GB-> big5
FT [R1] = 0;
Cout <ft <"(";
For (INT I = 0; I <R1; I ++ ){
Cout <"";
Printf ("0x % 02x", (byte) ft [I]);
}
Cout <")" <Endl;
Delete [] PWS;
}

Delete [] ft;
}
// Enter the Simplified Chinese standard from the standard input --> big5 traditional Chinese standard output, enter two blank lines to exit
Int main (INT argc, char * argv [])
{

For (;;){
Char line [1024];
Cin. Getline (line, sizeof (line ));
String S (line );
If (! Cin | S. Length () = 0) break;
J2f (s );
}
_ Getch ();
Return 0;
}
  
Question 3: How to obtain the view pointer in multiple threads?

Here: There are two ways to meet your requirements:

1) Method 1:

If multithreading does not appear in APP. cpp, add extern cyourapp theapp to the multithreaded. cpp;

// Obtain the document template:
Position curtemplatepos = theapp. getfirstdoctemplateposition ();
Cdoctemplate * m_doc = theapp. getnextdoctemplate (curtemplatepos );
File: // obtain the document:
Curtemplatepos = m_doc-> getfirstdocposition ();
Cyourdoc * m_pdoc = (ca8doc *) m_doc-> getnextdoc (curtemplatepos );

File: // obtain the View:
Curtemplatepos = m_pdoc-> getfirstviewposition ();
Cyourview * m_pview = (cyourview *) m_pdoc-> getnextview (curtemplatepos );
File: // call the view function:
M_pview-> put ();
2) Method 2:
// Obtain the form pointer:
Cmainframe * pframe = (cmainframe *) afxgetapp ()-> m_pmainwnd;
File: // obtain the view that matches the form:
Cyourview * m_pview = (cyourview *) pframe-> getactiveview ();
File: // call the view function:
M_pview-> put ();

Question 4: How can I prevent a program from creating a new document at startup?

The key is here:
Before the processshellcommand function in the initinstance of the program, add:

Using info. m_nshellcommand = ccommandlineinfo: filenothing
  
Question 5: How to get all views in the MDI program?

The key is here:

The following functions must be used:
Cdocument: getfirstviewposition (); // doccore. cpp
Cdocument: getnextview (); // doccore. cpp
Cmultidoctemplate: getfirstdocposition (); // docmulti. cpp
Cmultidoctemplate: getnextdoc (); // docmulti. cpp
It also needs to deal with the cwinapp member m_templatelist.

Question 6: How does one obtain the number of all tables in a database in ado?

The key is here:
Hresult hR = s_ OK;
_ Connectionptr pconnection = NULL;
_ Catalogptr pcatalog = NULL;
_ Bstr_t strcnn ("provider = sqloledb; Data Source = myserver ;"
"Initial catalog = pubs; user id = sa; Password = ;");
Try
{
File: // define a command object for a stored procedure.
Pconnection. createinstance (_ uuidof (connection ));
HR = pcatalog. createinstance (_ uuidof (Catalog ));
HR = pconnection-> open (strcnn, "", "", adconnectunspecified );
Pcatalog-> putactiveconnection (_ variant_t (idispatch *) pconnection ));
Long ntbcount = pcatalog-> tables-> count; // This is the number of tables you want.
Pconnection-> close ();
Pconnection = NULL;
}
Catch (_ com_error & E)
{
....
}
  
Question 7: What is the difference between blocking and non-blocking sockets from the application perspective?

The key is here:
In terms of system performance, non-blocking socket is more efficient and performance, but programming is more complex, especially when you use events or messages. However, you can manage more than 100 socket connections through four working threads, which is very efficient and does not require each working thread to manage only one socket connection. Blocking is simple, but when many clients consume too much system resources.

The so-called use of four threads to manage more than 100 sockets is just the idea: to create a thread pool, when there is a socket event to be processed, take a thread from the thread pool for execution, after execution, return the thread to the thread pool. This method will work better under the following conditions:
(1) Each socket connection lasts for a long time and constantly interacts with the server.

(2) The socket for each connection is not a specific implementation method for sending and receiving data every moment: (I implemented it in windows, and I am studying it on Linux) Overlaped Io can be used, or the port (compeleteio)

Question 8: how to set the stack size?

The key is here:

Method 1: stacksize defines the. Def File
Syntax: stacksize reserve [, commit]

Reserve: stack size; Commit: option, which is related to the operating system. The physical memory size is allocated only once on NT.
Method 2: Set/stack
Open the project and choose Project> setting> link, select output from category, and set the maximum value and commit of the stack in reserve.
Note: The default reserve value is 1 MB, and the minimum value is 4 bytes. Commit is stored in the page file of the virtual memory, which is relatively
The conference opened up a large value for the stack, which may increase the memory overhead and startup time.

Question 9: how to obtain the UDP port in use on the local machine?

The key is here:

It can be achieved through port scanning technology.

Port Scanning)
  
Port Scan is to connect to the TCP or UDP ports of the target system to determine which services are running. Generally, port scanning has three purposes:

* Identifies TCP and UDP services running on the target system.
* Identify the operating system type of the target system (Windows 9x, Windows NT, or UNIX, etc ).
* Identifies the version number of an application or a specific service.
  
Port Scanning Technology:

1. TCP connect scan: This method is the simplest. It connects directly to the target port and completes a complete three-way handshake (syn, SYN/ack, and ACK ). The disadvantage is that it is easy to be detected by the target system.

2. tcp syn scan: this technique is also called "half-open scanning" because it has not completed a complete TCP connection. This method sends a SYN group (packet) to the target port. If the target port returns SYN/ack, it is sure that the port is in the listening status; otherwise, RST/ack is returned. This method is more concealed than the first method, and may not leave scanning marks in the target system.

3. tcp fin scan: This method sends a fin group to the target port. According to rfc793 (http://www.ietf.org/rfc/rfc0793.txt), the target system should return the RST flag for all closed ports. This method is usually used in UNIX-based TCP/IP stack.

4. tcp xmas tree scan: This method sends a group containing the fin, URG, and push flag to the target port. According to rfc793, the target system should return the RST flag for all closed ports.

5. tcp null scan: This method sends a group that does not contain any flag to the target port. According to rfc793, the target system should return the RST flag for all closed ports.

6. UDP scan: This method sends a UDP group to the target port. If the target port responds with an "ICMP port unreachable" message, it indicates that the port is closed. Otherwise, if the "ICMP port unreachable" response message is not received, it is certain that the port is open. Because UDP is a connectionless protocol, the accuracy of this scanning technique is highly dependent on network performance and system resources. In addition, if the target system uses a large number of grouping filtering technologies, the UDP scan process will become very slow. If you want to perform a UDP scan on the internet, you cannot expect reliable results.
  
In addition, some system's IP protocol is implemented in this way. For all scan ports, whether they are in the closed or listening status, the RST flag is returned (we know, this does not comply with rfc793 ). Therefore, different scanning techniques may obtain different scanning results when scanning such a system.
  
Port scanning tool:
  
* Strobe

Strobe is one of the oldest port scanning tools and the fastest and most reliable TCP scanning tools. The disadvantage is that there is no UDP scan function.
URL: ftp.win.or.jp/pub/network/misc/strobe-1.05.tar.gz
  
* Udp_scan

Udp_scan was originally from Satan (security administrator tool for analyzing networks, a network analysis tool for security administrators, Satan's new version called Saint, released by the http://wwdsilx.wwdsi.com ). Udp_scan is one of the most reliable UDP scanning tools, but it is difficult to conceal and is easily detected by the target system.

URL: ftp://ftp.technotronic.com/unix/network-sanners/udpscan.c
  
* Netcat

Netcat is one of the most useful network tools and has many functions. It is called the Swiss army knife in the Network Security Toolkit. Netcat provides basic TCP and UDP scanning functions.

URL: http://www.l0pht.com/netcat
  
* Portpro and portscan

It is one of the fastest port scanning tools on Windows NT. Portscan can specify a scan range. portpro can only scan progressively, and neither of them can scan multiple IP addresses at a time.

URL: portpro: http://www.securityfocus.com
  
* Network mapper (NMAP)

NMAP is an advanced port scanning tool that provides multiple scanning methods. NMAP has some interesting functions, such as fragment TCP Header (that is, a TCP header is decomposed into multiple groups for sending) to bypass some firewalls with simple grouping filtering. Another interesting feature of NMAP is that it can send spoofing address scans. The specific implementation method is: send a large number of SYN groups to the target system with forged IP addresses, and mix them with SYN groups with real addresses, this causes the target system to spend a lot of time responding to forged groups, resulting in denial of service (Denial of Service). This is called SYN flood attacks.

URL: http://www.insecure.org/nmap

Question 10: How to Use the directoryentry component to view the network

The key is here:

The directoryentry component provides the path attribute. According to the document, this attribute specifies the object name used to access the object in Directory Service. The format is as follows:
Protocol: // SERVERNAME: Port Number/Distinguished Name
The first part of this statement defines the Protocol to be used for access, as shown in figure
LDAP: (Lightweight Directory Access Protocol)
IIS: (provides IIS metadata to read and configure Internet infomation server)
Winnt: (provides access to Windows NT domains with very limited performance)
NDS: (provides access to the Novell Directory Service)
And so on (For details, refer to msdn ).
Accordingly, we construct a directoryentry instance and set its path to "winnt :", all the domains (and working groups) on the network are discovered through enumeration of all its subitems ). In this way, the subitem of the discovered domain (and Working Group) can be enumerated to discover all computers on the network. The following console applet demonstrates this.
Using system;
Using system. directoryservices;
Class tempclass
{
Static void main ()
{
Enumcomputers ();
}
Static void enumcomputers ()
{
Using (directoryentry root = new directoryentry ("winnt :"))
{
Foreach (directoryentry domain in root. Children)
{
Console. writeline ("domain | Workgroup: \ t" + domain. Name );
Foreach (directoryentry computer in domain. Children)
{
Console. writeline ("COMPUTER: \ t" + computer. Name );
}
}
}
}
}
The two nested foreach loops in the above Code do not look very good, and the console display effect is not so beautiful. Next, I will make some changes to the Code and port it to winform.
Create a Windows application [C #] and add a Treeview to the form, named treeview1.

Add the following functions:
// Construct a node with the specified text, add it as a child node with the parant parameter, and return the newly constructed Node
Private treenode addnode (treenode parant, string text)
{
Treenode node = new treenode (text );
Parant. nodes. Add (node );
Return node;
}
// Recursively locate all subnodes of the entry parameter and display it in treeview1. The entry and entrynode must correspond to each other.
Private void enumchildren (directoryentry entry, treenode entrynode)
{
If (entry. Children! = NULL) file: // ends if no subnode exists.
{
Foreach (directoryentry I in entry. Children)
{
File: // Add each subnode to the Treeview and perform recursion
Enumchildren (I, addnode (entrynode, I. Name ));
}
}
}
// Construct the root node with the given string and list all its subnodes
Private void enumerate (string path)
{
Try
{
Using (directoryentry root = new directoryentry (PATH ))
{
Treenode node = new treenode (root. Name );
Treeview1.nodes. Add (node );
Enumchildren (root, node );
}
}
Catch {}
}
In this way, by passing "winnt:" To the enumerate (string) function, you can see all the computers on the network in the Treeview, and users, groups, services, and other resources on each computer.

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.