油條兒ㄉ筆記

2009年7月22日 星期三

部落格使用table出現一堆

問: 我在文章裡放入表格時,出現了多餘的空白行。 我要如何刪除這些空白行?
答: 空白行是因為 Blogger 會在您文章的每行結尾插入<br />標記,這可在 設定 -> 格式 -> 轉換分行符號 中設定
Reference:
http://www.google.com/support/blogger/bin/answer.py?hl=b5&answer=41592

2009年7月21日 星期二

visual studio常用熱鍵(hotkey)

我個人常用的visual studio 2008熱鍵一覽表

Table 1: Visual Studio Hotkeys/Default Keybindings/Shortcut keys
基本設定
清單顯示熱鍵 Tools -> Customize... -> Toolbars -> Show shortcut keys in Screen Tips
源碼顯示行號 Tools -> Options... -> Text Editor -> C/C++ -> Display -> Line numbers
Build/Compile
Build CTRL+SHIFT+B or F7
Build CTRL+SHIFT+B or F7
Build CTRL+SHIFT+B or F7
Build CTRL+SHIFT+B or F7
Debugging/Running
Start with Debug F5
Debug.StartWithoutDebugging Global::Ctrl+F5
Toggle/Untoggle Breakpoint F9
Navigation
Edit.GoToDefinition F12 Go to definition
Edit.GoToReference Shift-F12 Finds a reference to the selected item or the item under the cursor.
Edit.GoToDeclaration Ctrl-F12 Displays the declaration of the selected symbol in the code.
Edit.GoTo Global::Ctrl+G Displays the Go to Line dialog. If the debugger is running, the dialog also lets you specify addresses or function names to go to.
Edit.GotoBrace Ctrl-] Moves the cursor to the matching brace in the document. If the cursor is on an opening brace, this will move to the corresponding closing brace and vice versa.
Edit.DocumentEnd Ctrl-End Moves the cursor to the end of the document.
Edit.DocumentStart Ctrl-Home Moves the cursor to the start of the document.
Edit.ToggleBookmark Ctrl+K, Ctrl+K or Ctrl+F2 Sets or removes a bookmark at the current line.
Edit.ClearBookmarks Text Editor::Ctrl+K, Ctrl+L Removes all unnamed bookmarks in the current document.
Edit.NextBookmark Text Editor::Ctrl+K, Ctrl+N or F2 Moves to the next bookmark in the document.
Edit.PreviousBookmark Text Editor::Ctrl+K, Ctrl+P Moves to the previous bookmark.
View.TaskList Ctrl+\, Ctrl+T Displays the TaskList window, which displays tasks, comments, shortcuts, warnings, and error messages.
Edit.ToggleTaskListShortcut Ctrl-K, Ctrl-H Sets or removes a shortcut in the tasklist to the current line.
Edit.ScrollLineDown Ctrl+Down Arrow Scrolls text down one line but does not move the cursor. This is useful for scrolling more text into view without losing your place. Available only in text editors.
Edit.ScrollLineUp Ctrl+Up Arrow Scrolls text up one line but does not move the cursor. Available only in text editors.
Edit.WordNext Ctrl+Right Arrow Moves the cursor one word to the right.
Edit.WordPrevious Ctrl+Left Arrow Moves the cursor one word to the left.
Edit.SelectCurrentWord Ctrl-W Selects the word containing the cursor or the word to the right of the cursor.
Code View
Edit.CollapsetoDefinitions Ctrl+M, Ctrl+O Automatically determines logical boundaries for creating regions in code, such as procedures, and then hides them. This collapses all such regions in the current document.
Edit.StopHidingCurrent Ctrl-M, Ctrl-U Removes the outlining information for the currently selected region.
Edit.StopOutlining Ctrl-M, Ctrl-P Removes all outlining information from the entire document.
Search and Replace
Edit.Find Ctrl-F Displays the Find dialog.
Edit.FindinFiles Ctrl-Shift-F Displays the Find in Files dialog.
Edit.FindNext F3 Finds the next occurrence of the previous search text.
Edit.FindPrevious Shift-F3 Finds the previous occurrence of the search text.
Edit.FindNextSelected Ctrl-F3 Finds the next occurrence of the currently selected text or the word under the cursor if there is no selection.
Edit.FindPreviousSelected Ctrl-Shift-F3 Finds the previous occurrence of the currently selected text or the word under the cursor.
Edit.Replace Global::Ctrl+H Displays the Replace dialog.
Edit.ReplaceinFiles Ctrl+Shift+H Displays the Replace in Files dialog.
Edit.IncrementalSearch Ctrl+I Starts an incremental search—after pressing Ctrl-I, you can type in text, and for each letter you type, VS.NET will find the first occurrence of the sequence of letters you have typed so far. This is a very convenient facility, as it lets you find text by typing in exactly as many characters as are required to locate the text and no more. If you press Ctrl-I a second time without typing any characters, it recalls the previous pattern. If you press it a third time or you press it when an incremental search has already found a match, VS.NET searches for the next occurrence.
Edit.ReverseIncrementalSearch Ctrl+Shift+I Performs an incremental search in reverse direction.
Edit.FindSymbol ALT+F12 Displays the Find Symbol dialog.
Edit.QuickFindSymbol Global::Shift+Alt+F12 Displays the Find Symbol Results window.
Window
Next IDE Window CTRL+F6 or Ctrl+Tab
IntelliSense
Edit.CompleteWord CTRL+SPACE or ALT+RIGHT ARROW Completes the current word or shows the IntelliSense completion list.
Edit.ListMembers Ctrl-J Lists members for statement completion when editing code.
Edit.QuickInfo CTRL+K, CTRL+I Displays the complete declaration of the identifier under cursor.
Editing
Edit.Comment-Selection CTRL+K, CTRL+C Comments selected text.
Edit.Uncomment-Selection CTRL+K, CTRL+U Uncomments selected text.
Edit.Cut Global::Shift+Del Cut the entire row from the document and past it to the clipboard.
Edit.LineCut Ctrl-L Cuts all selected lines or the current line if nothing has been selected to the clipboard.
Edit.WordDeleteToEnd Ctrl-Delete Deletes the word to the right of the cursor.
Edit.WordDeleteToStart Ctrl-Backspace Deletes the word to the left of the cursor.
Edit.LineOpenAbove Ctrl-Enter Inserts a blank line above the cursor.
Edit.LineOpenBelow Ctrl-Shift-Enter Inserts a blank line below the cursor.
Edit.WordTranspose Ctrl+Shift+T Moves the word containing the cursor after the next word.
Edit.LineTranspose Shift+Alt+T Moves the line containing the cursor below the next line.
Edit.MakeLowercase Ctrl-U Changes the selected text to lowercase characters.
Edit.MakeUppercase Ctrl-Shift-U Changes the selected text to uppercase characters.
Edit.FormatSelection Text Editor::Ctrl+K, Ctrl+F or Alt+F8 Format the code in the window to be nicely indented.
Edit.Insert Insert Toggles between insert and overtype insertion modes.
Reference:
http://dotnetbutchering.blogspot.com/2008/02/net-top-5-visual-studio-hotkeys.html http://www.mssoftwareconsulting.com/msswc/blog/post/Reformat-Code-in-Visual-Studio.aspx http://www.dofactory.com/ShortCutKeys/ShortCutKeys.aspx

Windows Socket Server/Client with Visual C++

/* Blocking Sockets in TCP/IP (The Server) */
#include <iostream>
#include <string>
#include <string.h>
#include <winsock2.h>
#pragma comment(lib,"ws2_32.lib")
#define WSA_VERSION MAKEWORD(2, 2) // using winsock 2.2

using namespace std;

class TcpServer{
public:
 class InitSocketError{};
 class CreateSocketError{};
 class BindSocketError{};

 TcpServer()
 {
  initWinsock();
  _socket = tcpSocket();
  listenSocket(8888);
 }

 TcpServer(u_short port)
 {
  initWinsock();
  _socket = tcpSocket();
  listenSocket(port);
 }

 ~TcpServer()
 {
  endSocket();
 }

 SOCKET getSocket(){ return _socket; }
 void sendMessage();
private:
 SOCKET _socket;

 bool initWinsock();
 SOCKET tcpSocket();
 void listenSocket(u_short);
 void endSocket();

};

bool TcpServer::initWinsock()
{
 // Initialise Winsock
 WSADATA WsaData = { 0 };
 if(WSAStartup(WSA_VERSION, &WsaData) != 0)
 {
  // Tell the user that we could not find a usable WinSock DLL.
  if(LOBYTE(WsaData.wVersion) != LOBYTE(WSA_VERSION) ||
   HIBYTE(WsaData.wVersion) != HIBYTE(WSA_VERSION)){
    throw InitSocketError();
  }
  WSACleanup();
  system("PAUSE");
  return false;
 }
 return true;
}

SOCKET TcpServer::tcpSocket()
{
 _socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
 if(_socket==INVALID_SOCKET)
 {
  throw CreateSocketError();
  WSACleanup();
  system("PAUSE");
  return 0;
 }
 return _socket;
}

void TcpServer::listenSocket(u_short port)
{
 SOCKADDR_IN serverInf;
 serverInf.sin_family=AF_INET;
 serverInf.sin_addr.s_addr=INADDR_ANY;
 serverInf.sin_port=htons(port);

 if(bind(_socket,(SOCKADDR*)(&serverInf),sizeof(serverInf))==SOCKET_ERROR)
 {
  throw BindSocketError();
  WSACleanup();
  system("PAUSE");
  return;
 }
 listen(_socket,1);
}

void TcpServer::sendMessage()
{
 SOCKET TempSock=SOCKET_ERROR;
 while(TempSock==SOCKET_ERROR)
 {
  cout<<"Waiting for incoming connections...\r\n";
  TempSock=accept(_socket,NULL,NULL);
 }
 _socket=TempSock;

 cout<<"Client connected!\r\n\r\n";

 char *szMessage="Welcome to the server!\r\n";
 send(_socket, szMessage, strlen(szMessage), 0);
}


void TcpServer::endSocket()
{
 // Shutdown our socket
 shutdown(_socket, SD_SEND);
 // Close our socket entirely
 closesocket(_socket);
 // Cleanup Winsock
 WSACleanup();
}

int main()
{
 try{
  TcpServer *ts1 = new TcpServer(8888);
  ts1->sendMessage();  
  system("PAUSE");
 }catch(TcpServer::InitSocketError){
  cout<<"Winsock error - Winsock initialization failed\r\n";
  system("PAUSE");
 }catch(TcpServer::CreateSocketError){
  cout<<"Winsock error - Socket creation Failed, ec: "<<WSAGetLastError()<<endl;
  system("PAUSE");
 }catch(TcpServer::BindSocketError){
  std::cout<<"Unable to bind socket!\r\n";
  system("PAUSE");
 }

 return 0;
}
/* Blocking Sockets in TCP/IP (The Client) */
#include <iostream>
#include <string>
#include <winsock2.h>
#pragma comment(lib,"ws2_32.lib")
#define WSA_VERSION MAKEWORD(2, 2) // using winsock 2.2

using namespace std;


class TcpClient
{
public:
 class InitSocketError{};
 class CreateSocketError{};
 class GetHostNameError{};
 class ConnectSocketError{};

 TcpClient()
 {
  string hostname = "localhost";
  initWinsock();
  _socket = tcpSocket();
  connectSocket(hostname, 8888);
 }

 TcpClient(string hostname, u_short hostport)
 {
  initWinsock();
  _socket = tcpSocket();
  connectSocket(hostname, hostport);
 }

 ~TcpClient()
 {
  endSocket();
 }

 SOCKET getSocket() { return _socket; }
 void recevMessage();

private:
 SOCKET _socket;

 bool initWinsock();
 SOCKET tcpSocket();
 bool connectSocket(string&, u_short);
 void endSocket();
};

bool TcpClient::initWinsock()
{
 // Initialise Winsock
 WSADATA WsaData = { 0 };
 if(WSAStartup(WSA_VERSION, &WsaData) != 0)
 {
  // Tell the user that we could not find a usable WinSock DLL.
  if(LOBYTE(WsaData.wVersion) != LOBYTE(WSA_VERSION) ||
   HIBYTE(WsaData.wVersion) != HIBYTE(WSA_VERSION)){
    throw InitSocketError();
  }

  WSACleanup();
  system("PAUSE");
  return false;
 }
 return true;
}

SOCKET TcpClient::tcpSocket()
{
 SOCKET tsocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
 if(tsocket == INVALID_SOCKET)
 {
  throw CreateSocketError();
  WSACleanup();
  system("PAUSE");
  return 0;
 }
 return tsocket;
}

bool TcpClient::connectSocket(string& hostname, u_short hostport)
{
 // Resolve IP address for hostname
 struct hostent *host;
 if((host=gethostbyname(hostname.c_str()))==NULL)
 {
  throw GetHostNameError();
  WSACleanup();
  system("PAUSE");
  return false;
 }

 // Setup our socket address structure
 SOCKADDR_IN SockAddr;
 SockAddr.sin_port=htons(hostport);
 SockAddr.sin_family=AF_INET;
 SockAddr.sin_addr.s_addr=*((unsigned long*)host->h_addr);

 // Attempt to connect to server
 if(connect(_socket, (SOCKADDR*)(&SockAddr), sizeof(SockAddr))!=0)
 {
  throw ConnectSocketError();
  WSACleanup();
  cout<<"exe\n";
  system("PAUSE");
  return false;
 }
 return true;
}

void TcpClient::recevMessage()
{
 // Display message from server
 char buffer[1000];
 memset(buffer,0,999);
 int inDataLength=recv(_socket, buffer, 1000, 0);
 cout<<buffer;
}

void TcpClient::endSocket()
{
 // Shutdown our socket
 shutdown(_socket, SD_SEND);
 // Close our socket entirely
 closesocket(_socket);
 // Cleanup Winsock
 WSACleanup();
}


int main()
{
 try{

  TcpClient *tc2 = new TcpClient("smtp.gmail.com", 587);
  tc2->recevMessage();

  TcpClient *tc1 = new TcpClient();
  tc1->recevMessage();

  system("PAUSE");
 }catch(TcpClient::InitSocketError){
  cout<<"Winsock error - Winsock initialization failed\r\n";
  system("PAUSE");
 }catch(TcpClient::CreateSocketError){
  cout<<"Winsock error - Socket creation Failed, ec: "<<WSAGetLastError()<<endl;
  system("PAUSE");
 }catch(TcpClient::GetHostNameError){
  cout<<"Failed to resolve hostname.\r\n";
  system("PAUSE");
 }catch(TcpClient::ConnectSocketError){
  std::cout<<"Failed to establish connection with server\r\n";
  system("PAUSE");
 }
 return 0;
}
/**********************************************
Non-Blocking Sockets in TCP/IP (The Server)
1) Initialise Winsock
2) Create a Socket
3) Fill out a SOCKADDR_IN struct
4) Listen on our socket
5) Accept a connection from the client 
***********************************************/

#include <iostream>
#include <winsock2.h>
#pragma comment(lib,"ws2_32.lib")
#define WSA_VERSION MAKEWORD(2, 2) // using winsock 2.2

int main()
{
 WSADATA WsaDat;
 if(WSAStartup(WSA_VERSION, &WsaDat)!=0)
 {
  std::cout<<"WSA Initialization failed!\r\n";
  WSACleanup();
  system("PAUSE");
  return 0;
 }

 SOCKET Socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
 if(Socket==INVALID_SOCKET)
 {
  std::cout<<"Socket creation failed.\r\n";
  WSACleanup();
  system("PAUSE");
  return 0;
 }

 SOCKADDR_IN serverInf;
 serverInf.sin_family=AF_INET;
 serverInf.sin_addr.s_addr=INADDR_ANY;
 serverInf.sin_port=htons(8888);

 if(bind(Socket,(SOCKADDR*)(&serverInf),sizeof(serverInf))==SOCKET_ERROR)
 {
  std::cout<<"Unable to bind socket!\r\n";
  WSACleanup();
  system("PAUSE");
  return 0;
 }

 listen(Socket,1);

 SOCKET TempSock=SOCKET_ERROR;
 while(TempSock==SOCKET_ERROR)
 {
  std::cout<<"Waiting for incoming connections...\r\n";
  TempSock=accept(Socket,NULL,NULL);
 }

 // If iMode!=0, non-blocking mode is enabled.
 u_long iMode=1;
 ioctlsocket(Socket,FIONBIO,&iMode);

 Socket=TempSock;
 std::cout<<"Client connected!\r\n\r\n";

 // Main loop
 for(;;)
 {
  char *szMessage="Welcome to the server!\r\n";
  send(Socket,szMessage,strlen(szMessage),0);

  int nError=WSAGetLastError();
  if(nError!=WSAEWOULDBLOCK&&nError!=0)
  {
   std::cout<<"Winsock error code: "<<nError<<"\r\n";
   std::cout<<"Client disconnected!\r\n";

   // Shutdown our socket
   shutdown(Socket,SD_SEND);

   // Close our socket entirely
   closesocket(Socket);

   break;
  }

  Sleep(1000);
 }

 WSACleanup();
 system("PAUSE");
 return 0;
}
/* Non-Blocking Sockets in TCP/IP (The Client) */
#include <iostream>
#include <winsock2.h>
#pragma comment(lib,"ws2_32.lib")

#define WSA_VERSION MAKEWORD(2, 2) // using winsock 2.2
using namespace std;

class NonBlockTcpClient
{
public:
 class CreateSocketError{};
 class GetHostNameError{};
 class ConnectSocketError{};
 NonBlockTcpClient()
 {
  string hostname = "localhost";
  _socket = tcpSocket();
  connectSocket(hostname, 8888);
 }
 NonBlockTcpClient(string hostname, u_short hostport)
 {
  _socket = tcpSocket();
  connectSocket(hostname, hostport);
 }
 void sendMessage();
private:
 SOCKET _socket;

 SOCKET tcpSocket();
 bool connectSocket(string&, u_short);
};


SOCKET NonBlockTcpClient::tcpSocket()
{
 // Create our socket

 SOCKET Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
 if(Socket==INVALID_SOCKET)
 {
  throw CreateSocketError(); 
  return 0;
 }
 return Socket;
}

bool NonBlockTcpClient::connectSocket(string& hostname, u_short hostport)
{
 // Resolve IP address for hostname
 struct hostent *host;
 if((host=gethostbyname(hostname.c_str()))==NULL)
 {
  throw GetHostNameError();
  return false;
 }

 // Setup our socket address structure
 SOCKADDR_IN SockAddr;
 SockAddr.sin_port=htons(hostport);
 SockAddr.sin_family=AF_INET;
 SockAddr.sin_addr.s_addr=*((unsigned long*)host->h_addr);

 // Attempt to connect to server
 if(connect(_socket,(SOCKADDR*)(&SockAddr),sizeof(SockAddr))!=0)
 {
  throw ConnectSocketError();
  return false;
 }

 // If iMode!=0, non-blocking mode is enabled.
 u_long iMode=1;
 ioctlsocket(_socket,FIONBIO,&iMode);
 return true;
}

void NonBlockTcpClient::sendMessage()
{
 // Main loop
 for(;;)
 {
  // Display message from server
  char buffer[1000];
  memset(buffer,0,999);
  int inDataLength=recv(_socket,buffer,1000,0);
  std::cout<<buffer;

  int nError=WSAGetLastError();
  if(nError!=WSAEWOULDBLOCK&&nError!=0)
  {
   std::cout<<"Winsock error code: "<<nError<<"\r\n";
   std::cout<<"Server disconnected!\r\n";
   // Shutdown our socket
   shutdown(_socket,SD_SEND);

   // Close our socket entirely
   closesocket(_socket);

   break;
  }
  Sleep(1000);
 }
}

int main(void)
{
 /* initialize winsock */
 WSADATA WsaDat;
 if(WSAStartup(WSA_VERSION, &WsaDat)!=0)
 {
  std::cout<<"Winsock error - Winsock initialization failed\r\n";
  WSACleanup();
  system("PAUSE");
  return 0;
 }

 try{

  //NonBlockTcpClient *nbtc = new NonBlockTcpClient("smtp.gmail.com", 587); 
  //nbtc->sendMessage();
  NonBlockTcpClient *nbtcl = new NonBlockTcpClient(); 
  nbtcl->sendMessage();
 }catch(NonBlockTcpClient::CreateSocketError){
  cout<<"Winsock error - Socket creation Failed!\r\n";
  WSACleanup();
  system("PAUSE");
 }catch(NonBlockTcpClient::GetHostNameError){
  cout<<"Failed to resolve hostname.\r\n";
  WSACleanup();
  system("PAUSE");
 }catch(NonBlockTcpClient::ConnectSocketError){
  cout<<"Failed to establish connection with server\r\n";
  WSACleanup();
  system("PAUSE");
 }

 /* clean winsock */
 WSACleanup();
 system("PAUSE");
 return 0;
}

2009年7月16日 星期四

A simple program using smtp for sending gmail

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#using <System.dll>

using namespace System;
using namespace System::Net::Sockets;
using namespace System::Collections;
using namespace System::Collections::Generic;
using namespace System::Text;
using namespace System::IO;
using namespace System::Net;
using namespace System::Net::Mail;
using namespace System::Net::Mime;
using namespace System::Threading;
using namespace System::ComponentModel;

namespace GMailSend
{
 //array: http://msdn.microsoft.com/zh-tw/library/ms235236.aspx
 void Send(String^ from, String^ to, String^ subject, String^ body, 
  array<System::String ^>^ cc, int cc_num, array<System::String ^>^ bcc, int bcc_num, String^ host, int port, 
  String^ smtpUsername, String^ smtpPassword)
 {
  // Create mail message
  MailMessage^ message = gcnew MailMessage(from, to, subject, body);
  message->BodyEncoding = System::Text::Encoding::UTF8;

  if (cc != nullptr && cc_num > 0)
  {
   for(int i=0; i<cc_num; i++)
   {
    message->CC->Add(gcnew MailAddress(cc[i]));
   }
  }
  if (bcc != nullptr && bcc_num > 0)
  {
   for(int i=0; i<bcc_num; i++)
   {
    message->Bcc->Add(gcnew MailAddress(bcc[i]));
   }
  }

  // Send email
  SmtpClient^ client = gcnew SmtpClient(host, port);
  if (!String::IsNullOrEmpty(smtpUsername) && !String::IsNullOrEmpty(smtpPassword))
  {
   client->Credentials = gcnew NetworkCredential(smtpUsername, smtpPassword);
  }
  client->EnableSsl = true;
  client->Send(message);
 }

}

int _tmain(int argc, _TCHAR* argv[])
{


 GMailSend::Send("from@gmail.com","to@hotmail.com",  "testsubject", "testbodymessage", nullptr, 0, nullptr, 0, 
  "smtp.gmail.com", 587, "gmail_account", "gmail_password");


 system("pause");
 return 0;
}
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#using <System.dll>

using namespace System;
using namespace System::Net::Sockets;
using namespace System::Collections;
using namespace System::Collections::Generic;
using namespace System::Text;
using namespace System::IO;
using namespace System::Net;
using namespace System::Net::Mail;
using namespace System::Net::Mime;
using namespace System::Threading;
using namespace System::ComponentModel;


#define GMail_DEBUG

String^ showUsage() {
 StringBuilder^ sb = gcnew StringBuilder();

 sb->AppendLine( "Usage: MailSharp [options] ToAddress" );
 sb->AppendLine( "\t-a File to attach." );
 sb->AppendLine( "\t-f From address" );
 sb->AppendLine( "\t-b Body message" );
 sb->AppendLine( "\t-s Subject");
 sb->AppendLine( "\t-S SMTP server host" );
 sb->AppendLine( "\t-U Username for SMTP server authentication" );
 sb->AppendLine( "\t-p Password for SMTP server authentication" );
 sb->AppendLine( "\t-P SMTP server port" );
 sb->AppendLine( "\t-l Use SSL" );
 sb->AppendLine( "\t-h Help/Usage");
 sb->AppendLine();
 sb->AppendLine( "Example:" );
 sb->AppendLine( "\tFor GMail" );
 sb->AppendLine( "\tMailSharp -f your_name@gmail.com -b MessageBody -s TestSubject -S smtp.gmail.com -P 587 -l -U your_gmail -p your_gmail_password -t someone@somewhere.com" );
#ifdef GMail_DEBUG 
 // Display the number of characters in the StringBuilder and its string.
 Console::WriteLine("{0} chars: {1}", sb->Length, sb->ToString());
#endif

 return sb->ToString();
}




int _tmain(int argc, _TCHAR* argv[])
{

 //showUsage();
 MailAddress^ from = nullptr;
 MailAddress^ to = nullptr;
 MailMessage^ message = gcnew MailMessage();
 SmtpClient^ client = gcnew SmtpClient();
 NetworkCredential^ myCred = gcnew NetworkCredential();
 bool bShowUsage=false;

 try{
  if ( argc > 0 ) {
   for ( int i=0; i<argc; i++ ) {
    if( argv[i][0] == '-' ){
     switch ( argv[i][1] ) {
     case 'S': // server host
      i++;
      if ( i<argc ) {
       client->Host = gcnew String(argv[i]);
      } else
       throw gcnew Exception( "-S was specified, but no value." );
      break;
     case 'P': // server port
      i++;
      if ( i<argc ) {
       client->Port= Convert::ToInt32( gcnew String(argv[i]) );
      } else
       throw gcnew Exception( "-P was specified, but no value." );
      break;
     case 'T': // timeout
      i++;
      if ( i<argc ) {
       client->Timeout = Convert::ToInt32( gcnew String(argv[i]) );
      } else
       throw gcnew Exception( "-T was specified, but no value." );
      break;
     case 'U': // username for smtp server authentication
      i++;
      if ( i<argc )
       myCred->UserName = gcnew String(argv[i]);
      else
       throw gcnew Exception( "-U was specified, but no value." );
      break;
     case 'p': // password for smtp server authentication
      i++;
      if ( i<argc )
       myCred->Password = gcnew String(argv[i]);
      else
       throw gcnew Exception( "-p was specified, but no value." );
      break;
     case 'l': // use SSL
      client->EnableSsl = true;
      break;
     case 's': // subject
      i++; // next one is subject.
      if ( i<argc ) {
       message->Subject = gcnew String(argv[i]);
       message->SubjectEncoding = System::Text::Encoding::UTF8;
      } else
       throw gcnew Exception( "-s was specified, but no value." );
      break;
     case 'a': // attachment
      i++; // next one is attachment filename.
      if ( i<argc ) {
       // Add attachment.
       Attachment^ data = gcnew Attachment( gcnew String(argv[i]), MediaTypeNames::Application::Octet);
       message->Attachments->Add(data);
      } else
       throw gcnew Exception( "-a was specified, but no value." );
      break;
     case 'b': // body message.
      i++; // next one is body message
      if ( i<argc ) {
       message->Body = gcnew String(argv[i]);
       message->BodyEncoding =  System::Text::Encoding::UTF8;
      } else
       throw gcnew Exception( "-b was specified, but no value." );
      break;
     case 'f': // from address
      i++;
      if ( i<argc ) {
       // Specify the e-mail sender.
       // Create a mailing address that includes a UTF8 character
       // in the display name.
       // from = new MailAddress( "someone@gmail.com", "someone", System.Text.Encoding.UTF8);
       from = gcnew MailAddress( gcnew String(argv[i]) );
      } else
       throw gcnew Exception( "-f was specified, but no value." );
      break;
     case 'h': // show help/usage
      bShowUsage=true;
      break;
     case 't':
      i++;
      to = gcnew MailAddress( gcnew String(argv[i]) );
      break;
     }//end of switch
    }//end of check '-'
   }//end of for
  } else
   throw gcnew Exception("No arguments.");
 }catch(Exception^ ex){
  Console::WriteLine( ex->Message );
  bShowUsage = true;
 }

 try {
  if ( bShowUsage == true )
   throw gcnew Exception( showUsage() );

  if ( from==nullptr )
   throw gcnew Exception( "Must specify from address (-f)." );

  // Set destinations for the e-mail message.
  if ( to == nullptr )
   throw gcnew Exception("At least, must specify to address");

  if ( client->Host == String::Empty )
   throw gcnew Exception("Must specify SMTP Server (-S)." );

  // Specify the message content.
  message->From = from;
  message->To->Add( to );

  // Credentials are necessary if the server requires the client
  // to authenticate before it will send e-mail on the client's behalf.
  //client.UseDefaultCredentials = false;
  client->Credentials = myCred;

  // Send.
  // If you need asynchronous sample, please visit the reference above.
  client->Send(message);

  Console::WriteLine("Done.");
 } catch ( Exception^ ex ) {
  Console::WriteLine( "Exception was raised when sending...");
  Console::WriteLine( ex->Message );
 } finally {
  // Clean up.
  message->~MailMessage();
 }


 system("pause");
 return 0;
}

parse command line in Win32 API

#include "stdafx.h"
#include <stdio.h>
#include <string>
#include <stdlib.h>

// 出處:http://www.codeguru.com/cpp/w-p/win32/comments.php/c1427/?thread=3545
// A Simple Win32 Command-Line Parser

#include <windows.h>

char **argv = NULL;

/*******************************************************
WIN32 command line parser function
********************************************************/
int ParseCommandline()
{
 int    argc, BuffSize, i;
 WCHAR  *wcCommandLine;
 LPWSTR *argw;

 // Get a WCHAR version of the parsed commande line
 wcCommandLine = GetCommandLineW(); 
 argw = CommandLineToArgvW( wcCommandLine, &argc);

 // Create the first dimension of the double array
 argv = (char **)GlobalAlloc( LPTR, argc + 1 );

 // convert eich line of wcCommandeLine to MultiByte and place them
 // to the argv[] array
 for( i=0; i<argc; i++)
 {
  BuffSize = WideCharToMultiByte( CP_ACP, WC_COMPOSITECHECK, argw[i], -1, NULL, 0, NULL, NULL );
  argv[i] = (char *)GlobalAlloc( LPTR, BuffSize );  
  WideCharToMultiByte( CP_ACP, WC_COMPOSITECHECK, argw[i], BuffSize * sizeof( WCHAR ) ,argv[i], BuffSize, NULL, NULL );
 }

 // return the number of argument
 return argc;
}

//Command Line argument parsing 
//linux: getopt
//windows ?
int main( int argc, char **argv ) {
 argc = ParseCommandline();
 for(int i=0; i<argc; i++){
  printf("%s\n", argv[i]);
 }
 system("pause");
 return 0;
} 

port scanner/firewall

Port Scan wiki: http://en.wikipedia.org/wiki/Port_scanner background: http://en.wikipedia.org/wiki/Internet_Protocol_Suite common application ports: http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers tools: http://en.wikipedia.org/wiki/Nmap keyword: ICMP(關掉可以防一些port scan?) 查看Ports的方法: windows: 指令:netstat[-a] [-e] [-n] [-s] [-p protocol] [-r] [interval] C:>netstat -a (可查看所有與電腦的連線狀態,不過太繁雜了) C:>netstat -p tcp (可查看與電腦的tcp的連線狀態) C:>netstat -p udp (可查看與電腦的udp的連線狀態) Linux: 指令:netstat(本機端) yslinnote@~> netstat -t (可查看與電腦的tcp的連線狀態) yslinnote@~> netstat -u (可查看與電腦的udp的連線狀態) 指令:nmap(遠端) nmap localhost(查詢自己所有開放的port,結果與netstat類似)   nmap IP(查詢某特定IP開放的port)   nmap 192.168.1.0(查詢192.168.1.0~192.168.1.254開放的port)   nmap 192.168.0-10(查詢192.168.1.0~192.168.1.10開放的port)   nmap -sT/-sU IP(查詢某特定IP開放有關TCP/UDP的port) simple code: 參考來源: http://indeepnight.blogspot.com/2007/05/port-scanner.html

perl

# 純量陣列以 @ 開頭。
my @array;
my @array=qw(a b c d);

# qw 函數會將其後的每個元素用逗點隔開,效果就像下面這行。
my @array=("a","b","c","d");

# 當然你也可以一個個元素宣告,下面就是存取每一個元素的方法。
# 因為陣列中的每一個元素都是純量變數,所以要以 $ 開頭,
# 剛開始容易搞混,請注意。
$array[0]="a"; $array[1]="b"; $array[2]="c"; $array[3]="d";

# 使用for loop印出陣列內每個元素的值。
for($i=0; $i<=$#array; $i++) {
print "$array[$i]\n";
}