วันพุธที่ 11 มีนาคม พ.ศ. 2558

visual c++ socket

Program Server
เมื่อกดปุ่ม "Generate number & Send data" โปรแกรม Server จะ Random เลขมา 10 ตัว (ไม่เกิน 4 หลัก) หลักจากนั้นนำมาเรียงจาก น้อยไปมาก ให้เห็นบนโปรแกรม 
สามารถกดปุ่ม "Generate number & Send data" ได้ไม่จำกัดจำนวนครั้ง

Program Client
เมื่อได้ข้อมูลจาก Socket ให้นำตัวเลขทั้ง 10 ตัวที่เรียงจากน้อยไปมาก มาแบ่งครึ่งเพื่อแสดงผล ตามรูปภาพ




server
 #pragma once  
 #include <stdlib.h>   /* srand, rand */  
 #include <time.h>    /* time */  
 #include <algorithm>     /* sort */  
 #include <winsock2.h>     /* socket */  
 #include <Ws2tcpip.h>     /* socket */  
 #pragma comment(lib, "Ws2_32.lib")  
 #define WIN32_LEAN_AND_MEAN  
 #define DEFAULT_BUFLEN 512  
 #define DEFAULT_PORT 27015  
 namespace SocketSortNumber {  
      using namespace System;  
      using namespace System::ComponentModel;  
      using namespace System::Collections;  
      using namespace System::Windows::Forms;  
      using namespace System::Data;  
      using namespace System::Drawing;  
      using namespace std;  
      using namespace Runtime::InteropServices;  
      /// <summary>  
      /// Summary for Form1  
      /// </summary>  
      public ref class Form1 : public System::Windows::Forms::Form  
      {  
      public:  
           Form1(void)  
           {  
                InitializeComponent();  
                //  
                //TODO: Add the constructor code here  
                //  
           }  
      protected:  
           /// <summary>  
           /// Clean up any resources being used.  
           /// </summary>  
           ~Form1()  
           {  
                if (components)  
                {  
                     delete components;  
                }  
           }  
      private: System::Windows::Forms::Button^ button1;  
      protected:   
      private: System::Windows::Forms::TextBox^ textBox1;  
      private: System::Windows::Forms::Label^ label1;  
      private: System::Windows::Forms::Label^ label2;  
      private: System::Windows::Forms::TextBox^ textBox2;  
      private: System::Windows::Forms::Label^ label3;  
      private:  
           /// <summary>  
           /// Required designer variable.  
           /// </summary>  
           System::ComponentModel::Container ^components;  
 #pragma region Windows Form Designer generated code  
           /// <summary>  
           /// Required method for Designer support - do not modify  
           /// the contents of this method with the code editor.  
           /// </summary>  
           void InitializeComponent(void)  
           {  
                this->button1 = (gcnew System::Windows::Forms::Button());  
                this->textBox1 = (gcnew System::Windows::Forms::TextBox());  
                this->label1 = (gcnew System::Windows::Forms::Label());  
                this->label2 = (gcnew System::Windows::Forms::Label());  
                this->textBox2 = (gcnew System::Windows::Forms::TextBox());  
                this->label3 = (gcnew System::Windows::Forms::Label());  
                this->SuspendLayout();  
                //   
                // button1  
                //   
                this->button1->Location = System::Drawing::Point(60, 57);  
                this->button1->Name = L"button1";  
                this->button1->Size = System::Drawing::Size(210, 23);  
                this->button1->TabIndex = 0;  
                this->button1->Text = L"Generate number and Send data";  
                this->button1->UseVisualStyleBackColor = true;  
                this->button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click);  
                //   
                // textBox1  
                //   
                this->textBox1->Location = System::Drawing::Point(27, 130);  
                this->textBox1->Name = L"textBox1";  
                this->textBox1->Size = System::Drawing::Size(278, 20);  
                this->textBox1->TabIndex = 1;  
                //   
                // label1  
                //   
                this->label1->AutoSize = true;  
                this->label1->Location = System::Drawing::Point(35, 111);  
                this->label1->Name = L"label1";  
                this->label1->Size = System::Drawing::Size(87, 13);  
                this->label1->TabIndex = 2;  
                this->label1->Text = L"Random Number";  
                //   
                // label2  
                //   
                this->label2->AutoSize = true;  
                this->label2->Location = System::Drawing::Point(35, 175);  
                this->label2->Name = L"label2";  
                this->label2->Size = System::Drawing::Size(59, 13);  
                this->label2->TabIndex = 3;  
                this->label2->Text = L"Min -> Max";  
                //   
                // textBox2  
                //   
                this->textBox2->Location = System::Drawing::Point(27, 192);  
                this->textBox2->Name = L"textBox2";  
                this->textBox2->Size = System::Drawing::Size(278, 20);  
                this->textBox2->TabIndex = 4;  
                //   
                // label3  
                //   
                this->label3->AutoSize = true;  
                this->label3->Location = System::Drawing::Point(27, 236);  
                this->label3->Name = L"label3";  
                this->label3->Size = System::Drawing::Size(0, 13);  
                this->label3->TabIndex = 5;  
                //   
                // Form1  
                //   
                this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);  
                this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;  
                this->ClientSize = System::Drawing::Size(334, 261);  
                this->Controls->Add(this->label3);  
                this->Controls->Add(this->textBox2);  
                this->Controls->Add(this->label2);  
                this->Controls->Add(this->label1);  
                this->Controls->Add(this->textBox1);  
                this->Controls->Add(this->button1);  
                this->Name = L"Form1";  
                this->Text = L"Server";  
                this->ResumeLayout(false);  
                this->PerformLayout();  
           }  
 #pragma endregion  
      private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {  
                     int number [10] = {};  
                     int iResult = 0;        
                     int recvbuflen = DEFAULT_BUFLEN;  
                     WSADATA wsaData;  
                     SOCKET ListenSocket = INVALID_SOCKET;  
                     sockaddr_in service;  
                     randdomNumber(number,number+10);  
                     String^ str = ToString(number,number+10);  
                     textBox1->Text = str;  
                     std::sort(number,number+10);  
                     str = ToString(number,number+10);  
                     textBox2->Text = str;  
                     iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);  
                     if (iResult != NO_ERROR) {  
                          label3->Text = ("Error at WSAStartup()");   
                     }  
                     ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);  
                     if (ListenSocket == INVALID_SOCKET) {  
                          label3->Text = ("socket function failed with error: %u");  
                          WSACleanup();  
                     }  
                     service.sin_family = AF_INET;  
                     service.sin_addr.s_addr = inet_addr("127.0.0.1");  
                     service.sin_port = htons(27015);  
                     iResult = bind(ListenSocket, (SOCKADDR *) &service, sizeof (service));  
                     if (iResult == SOCKET_ERROR) {  
                          label3->Text = ("bind failed with error ");  
                          closesocket(ListenSocket);  
                          WSACleanup();  
                     }  
                     if (listen(ListenSocket, SOMAXCONN) == SOCKET_ERROR){  
                          label3->Text = ("listen function failed with error: ");  
                          iResult = closesocket(ListenSocket);  
                          WSACleanup();  
                     }  
                     ListenSocket = accept(ListenSocket, NULL, NULL);  
                     if (ListenSocket == INVALID_SOCKET) {  
                          label3->Text = ("accept failed with error:");  
                          closesocket(ListenSocket);  
                          WSACleanup();  
                     } else  
                          label3->Text = ("Client connected.");       
                     IntPtr p = Marshal::StringToHGlobalAnsi(str);  
                     char *sendbuf = static_cast<char*>(p.ToPointer());  
                     send(ListenSocket, sendbuf, (int)strlen(sendbuf), 0 );  
                     WSACleanup();  
                 }   
                 void randdomNumber(int* first, int* last){  
                      srand(time(NULL));  
                      int * current = first;  
                      while (current != last) {  
                          *current = rand() % 10000; //Generate an integer between 0 and 9999  
                          ++current;  
                     }  
                 }  
                 String^ ToString(const int* first, const int* last){  
                     String^ str = "";  
                     const int * current = first;  
                     while (current != last) {  
                          str += Convert::ToString(*current);  
                          ++current;   // increment pointer  
                          if (current != last) str += ",";   
                     }  
                     return str;  
                 }  
 };  
 }  


client
 #pragma once  
 #include <winsock2.h>     /* socket */  
 #include <Ws2tcpip.h>     /* socket */  
 #pragma comment(lib, "Ws2_32.lib")  
 #define WIN32_LEAN_AND_MEAN  
 #define DEFAULT_BUFLEN 512  
 #define DEFAULT_PORT 27015  
 namespace client {  
      using namespace System;  
      using namespace System::ComponentModel;  
      using namespace System::Collections;  
      using namespace System::Windows::Forms;  
      using namespace System::Data;  
      using namespace System::Drawing;  
      /// <summary>  
      /// Summary for Form1  
      /// </summary>  
      public ref class Form1 : public System::Windows::Forms::Form  
      {  
      public:  
           Form1(void)  
           {  
                InitializeComponent();  
                //  
                //TODO: Add the constructor code here  
                //  
           }  
      protected:  
           /// <summary>  
           /// Clean up any resources being used.  
           /// </summary>  
           ~Form1()  
           {  
                if (components)  
                {  
                     delete components;  
                }  
           }  
      private: System::Windows::Forms::Timer^ timer1;  
      private: System::Windows::Forms::Label^ label1;  
      private: System::Windows::Forms::Label^ label2;  
      private: System::Windows::Forms::Label^ label3;  
      private: System::Windows::Forms::DataGridView^ dataGridView1;  
      private: System::Windows::Forms::Label^ label4;  
      protected:   
      private: System::ComponentModel::IContainer^ components;  
      private:  
           /// <summary>  
           /// Required designer variable.  
           /// </summary>  
 #pragma region Windows Form Designer generated code  
           /// <summary>  
           /// Required method for Designer support - do not modify  
           /// the contents of this method with the code editor.  
           /// </summary>  
           void InitializeComponent(void)  
           {  
                this->components = (gcnew System::ComponentModel::Container());  
                this->timer1 = (gcnew System::Windows::Forms::Timer(this->components));  
                this->label1 = (gcnew System::Windows::Forms::Label());  
                this->label2 = (gcnew System::Windows::Forms::Label());  
                this->label3 = (gcnew System::Windows::Forms::Label());  
                this->dataGridView1 = (gcnew System::Windows::Forms::DataGridView());  
                this->label4 = (gcnew System::Windows::Forms::Label());  
                (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->dataGridView1))->BeginInit();  
                this->SuspendLayout();  
                //   
                // timer1  
                //   
                this->timer1->Enabled = true;  
                this->timer1->Interval = 250;  
                this->timer1->Tick += gcnew System::EventHandler(this, &Form1::timer1_Tick);  
                //   
                // label1  
                //   
                this->label1->AutoSize = true;  
                this->label1->Location = System::Drawing::Point(105, 66);  
                this->label1->Name = L"label1";  
                this->label1->Size = System::Drawing::Size(0, 13);  
                this->label1->TabIndex = 0;  
                //   
                // label2  
                //   
                this->label2->AutoSize = true;  
                this->label2->Location = System::Drawing::Point(37, 66);  
                this->label2->Name = L"label2";  
                this->label2->Size = System::Drawing::Size(27, 13);  
                this->label2->TabIndex = 1;  
                this->label2->Text = L"Max";  
                //   
                // label3  
                //   
                this->label3->AutoSize = true;  
                this->label3->Location = System::Drawing::Point(40, 174);  
                this->label3->Name = L"label3";  
                this->label3->Size = System::Drawing::Size(24, 13);  
                this->label3->TabIndex = 2;  
                this->label3->Text = L"Min";  
                //   
                // dataGridView1  
                //   
                this->dataGridView1->ColumnHeadersHeightSizeMode = System::Windows::Forms::DataGridViewColumnHeadersHeightSizeMode::AutoSize;  
                this->dataGridView1->Location = System::Drawing::Point(156, 50);  
                this->dataGridView1->Name = L"dataGridView1";  
                this->dataGridView1->Size = System::Drawing::Size(10, 168);  
                this->dataGridView1->TabIndex = 3;  
                //   
                // label4  
                //   
                this->label4->AutoSize = true;  
                this->label4->Location = System::Drawing::Point(193, 65);  
                this->label4->Name = L"label4";  
                this->label4->Size = System::Drawing::Size(0, 13);  
                this->label4->TabIndex = 4;  
                //   
                // Form1  
                //   
                this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);  
                this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;  
                this->ClientSize = System::Drawing::Size(284, 261);  
                this->Controls->Add(this->label4);  
                this->Controls->Add(this->dataGridView1);  
                this->Controls->Add(this->label3);  
                this->Controls->Add(this->label2);  
                this->Controls->Add(this->label1);  
                this->Name = L"Form1";  
                this->Text = L"Client";  
                (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->dataGridView1))->EndInit();  
                this->ResumeLayout(false);  
                this->PerformLayout();  
           }  
 #pragma endregion  
      private: System::Void timer1_Tick(System::Object^ sender, System::EventArgs^ e) {  
                int Result;  
                WSADATA wsaData;  
                SOCKET SocketNumber = INVALID_SOCKET;  
                struct sockaddr_in clientService;   
                int recvbuflen = DEFAULT_BUFLEN;  
                char recvbuf[DEFAULT_BUFLEN] = "";  
                Result = WSAStartup(MAKEWORD(2,2), &wsaData);  
                if (Result != NO_ERROR) {  
                     label1->Text = ("WSAStartup failed with error:" + Result);  
                }  
                SocketNumber = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);  
                if (SocketNumber == INVALID_SOCKET) {  
                     label1->Text = ("socket failed with error: " + WSAGetLastError());  
                     WSACleanup();  
                }  
                clientService.sin_family = AF_INET;  
                clientService.sin_addr.s_addr = inet_addr( "127.0.0.1" );  
                clientService.sin_port = htons( DEFAULT_PORT );  
                Result = connect( SocketNumber, (SOCKADDR*) &clientService, sizeof(clientService) );  
                if (Result == SOCKET_ERROR) {  
                     //label1->Text = ("connect failed with error: " + WSAGetLastError());  
                     closesocket(SocketNumber);  
                     WSACleanup();  
                 }  
                do {  
                     Result = recv(SocketNumber, recvbuf, recvbuflen, 0);  
                     if ( Result > 0 ){  
                     String^ msg = gcnew String(recvbuf);  
                     array<Char> ^sep = gcnew array<Char>{','};  
                     array<String^>^result;  
                     result = msg->Split( sep, StringSplitOptions::RemoveEmptyEntries );  
                     String^ tmp = "";  
                     for(int i = (result->Length)/2-1;i >= 0;i-- )  
                          tmp += result[i] + "\n\n";  
                     label1->Text = tmp;  
                     tmp = "";  
                     for(int i = (result->Length)/2;i < result->Length;i++ )  
                          tmp += result[i] + "\n\n";  
                     label4->Text = tmp;  
                     memset(recvbuf, 0, DEFAULT_BUFLEN);  
                     }else if ( Result == 0 )  
                          label1->Text = ("Connection closed");    
                     else  
                          //label1->Text = ("recv failed with error: " + WSAGetLastError());  
                          ;  
                } while( Result > 0 );  
            }  
      };  
 }  

วันอาทิตย์ที่ 4 พฤษภาคม พ.ศ. 2557

C# class example

โปรแกรมจะรับค่า properties ของ air จำนวน 10 ชุด
โดยจะมี class AirCondition เพื่อเป็นต้นแบบของวัตถุ
เมื่อรับค่าเสร็จก็จะแสดงค่า BTU ของ air แต่ละตัวผ่าน method getBTU()
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Text;  
 namespace ConsoleApplication2  
 {  
   class Program  
   {  
     static void Main(string[] args)  
     {  
       List<AirCondition> air = new List<AirCondition>();  
       int n = 1, width, high, length, var;  
       while (n <= 10)  
       {  
         Console.WriteLine("Enter properties of air{0}/10 :", n);  
         Console.WriteLine("Enter width : ");  
         string s_width = Console.ReadLine();  
         Console.WriteLine("Enter high : ");  
         string s_high = Console.ReadLine();  
         Console.WriteLine("Enter length : ");  
         string s_length = Console.ReadLine();  
         Console.WriteLine("Enter var : ");  
         string s_var = Console.ReadLine();  
         if (int.TryParse(s_width, out width) && int.TryParse(s_high, out high) && int.TryParse(s_length, out length) && int.TryParse(s_var, out var))  
         {  
           AirCondition temp = new AirCondition(width, high, length, var);  
           air.Add(temp);  
           n++;  
         }  
         else  
         {  
           Console.WriteLine("Please enter again!!");  
         }  
       }  
       n = 1;  
       foreach (AirCondition ob in air)  
       {   
         Console.WriteLine("BTU of air{0}/10 : {1}", n, ob.getBTU());  
         n++;  
       }  
       Console.WriteLine("Press any key to stop...");  
       Console.ReadKey();  
       /*AirCondition air = new AirCondition(5,3,5,400);  
       double value = air.getBTU();  
       Console.WriteLine("BTU : {0}", value);  
       Console.WriteLine("Press any key to stop...");  
       Console.ReadKey();  
       */  
     }  
   }  
   class AirCondition  
   {  
     public int width;  
     public int high;  
     public int length;  
     public int var;  
     public AirCondition()  
     {  
       width = 0;  
       high = 0;  
       length = 0;  
       var = 0;  
     }  
     public AirCondition(int width,int high, int length, int var)  
     {  
       this.width = width;  
       this.high = high;  
       this.length = length;  
       this.var = var;  
     }  
     public double getBTU()  
     {  
       return (width * high * length * var) / 3;  
     }  
   }  
 }  

--------------------------------------------------

C# get input number from keyboard and find max min


โปรแกรมจะรับ input จาก keyboard จำนวน 10 ตัวเลข
จะมีการเช็ค input ว่าเป็นตัวเลขหรือไม่ ถ้าไม่ใช่ก็จะให้กลับไปใส่อีกรอบ
เมื่อใส่ตัวเลขเรียบร้อยแล้วก็จะแสดงผลค่ามากที่สุดและน้อยที่สุด
ผ่านหน้าจอโปรแกรม
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Text;  
 namespace ConsoleApplication1  
 {  
   class Program  
   {  
     static void Main(string[] args)  
     {  
       int[] numbers;  
       numbers = new int[10];  
       int n = 1, value, max, min;  
       while (n <= 10)  
       {  
         Console.WriteLine("Enter number {0}/10 :", n);  
         string line = Console.ReadLine();  
         if (int.TryParse(line, out value))  
         {  
           numbers[n - 1] = value;  
           n++;  
         }  
         else  
         {  
           Console.WriteLine("Please enter again!!");  
         }  
       }  
       max = min = numbers[0];  
       foreach (int i in numbers)   
       {  
         if (i > max)   
         {  
           max = i;  
         }  
         if (i < min)   
         {  
           min = i;  
         }  
       }  
       Console.WriteLine("\n\nmax number : {0} \nmin number : {1}",max,min);  
       Console.WriteLine("Press any key to stop...");  
       Console.ReadKey();  
     }  
   }  
 }  


วันอาทิตย์ที่ 6 เมษายน พ.ศ. 2557

การใช้งานฟังก์ชั่น COUNTIF ใน Excel

พอดีได้มีโอกาสใช้ Excel ในการสร้างตารางการใช้ชีวิตในแต่ละวันเพราะรู้สึกว่าจะใช้ชีวิตไร้จุดหมายไปหน่อย เลยทำการสร้างตารางมาโดยจะทำการนับการอ่านหนังสือในแต่ละวันนั้นให้มีจำนวน 1.5 ชม./วัน

แบบก็ประมาณนี้


แต่ก็อยากจะใช้ เครื่องหมาย "/" มันดูเหมือนเป็นการเช็คดี :P
ที่จริงจะใช้ เป็นตัวเลข 1 แล้วใช้ฟังก์ชั่น SUM ก็ได้แต่มันดูไม่เท่อ่ะ
ปัญหาเกิดทีนี้!@~& ลองใช้ SUM ก็ไม่ได้(หรือใช้ได้แต่ใช้ไม่เป็น !!)
ก็เลยมาเจอกับ COUNTIF การใช้ก็ง่ายๆ
รูปแบบ COUNTIF(range, criteria) 
จากนั้นก็นำมาใช้ให้ตรงกับงานของเราก็จะเป็น =COUNTIF(C3:AF3,"/")

ผลลัพธ์

ส่วนการใช้งานแบบอื่นถ้าอยากรู้ดูได้จาก
http://office.microsoft.com/th-th/excel-help/HP010069840.aspx
ตามนี้เลย
*************