UNINSTALL OR COMPLETELY REMOVE MYSQL FROM UBUNTU 16-04

While upgrading from ubuntu 16.04.1 to ubuntu 16.04.03, we had face once issue that we unexpected.

This incident are cause by mysql server update, while setting up the mysql by apt, its hang on the server and will not work for leaving it around one hours.

So we decide to remove the mysql server and reinstall again, below are the step that we were done.

  1. sudo apt-get remove --purge mysql*
  2. sudo apt-get purge mysql*
    
  3. sudo apt-get autoremove
  4. sudo apt-get autoclean
  5. sudo apt-get remove dbconfig-mysql
  6. sudo apt-get dist-upgrade
  7. sudo apt-get install mysql-server
    
    
    Source:https://linuxscriptshub.com

Chapter 3 Resetting the Root Password: Windows Systems

On Windows, use the following procedure to reset the password for the MySQL 'root'@'localhost' account. To change the password for a root account with a different host name part, modify the instructions to use that host name.

  1. Log on to your system as Administrator.
  2. Stop the MySQL server if it is running. For a server that is running as a Windows service, go to the Services manager: From the Start menu, select Control Panel, then Administrative Tools, then Services. Find the MySQL service in the list and stop it.

    If your server is not running as a service, you may need to use the Task Manager to force it to stop.

  3. Create a text file containing the password-assignment statement on a single line. Replace the password with the password that you want to use.

    MySQL 5.7.6 and later:

    ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass';

    MySQL 5.7.5 and earlier:

    SET PASSWORD FOR 'root'@'localhost' = PASSWORD('MyNewPass');
  4. Save the file. This example assumes that you name the file C:\mysql-init.txt.
  5. Open a console window to get to the command prompt: From the Start menu, select Run, then enter cmd as the command to be run.
  6. Start the MySQL server with the special --init-file option (notice that the backslash in the option value is doubled):
    C:\> cd "C:\Program Files\MySQL\MySQL Server 5.7\bin"
    C:\> mysqld --init-file=C:\\mysql-init.txt

    If you installed MySQL to a different location, adjust the cd command accordingly.

    The server executes the contents of the file named by the --init-file option at startup, changing the'root'@'localhost' account password.

    To have server output to appear in the console window rather than in a log file, add the --console option to themysqld command.

    If you installed MySQL using the MySQL Installation Wizard, you may need to specify a --defaults-file option. For example:

    C:\> mysqld
             --defaults-file="C:\\ProgramData\\MySQL\\MySQL Server 5.7\\my.ini"
             --init-file=C:\\mysql-init.txt

    The appropriate --defaults-file setting can be found using the Services Manager: From the Start menu, selectControl Panel, then Administrative Tools, then Services. Find the MySQL service in the list, right-click it, and choose the Properties option. The Path to executable field contains the --defaults-file setting.

  7. After the server has started successfully, delete C:\mysql-init.txt.

You should now be able to connect to the MySQL server as root using the new password. Stop the MySQL server and restart it normally. If you run the server as a service, start it from the Windows Services window. If you start the server manually, use whatever command you normally use.

If the ALTER USER statement fails to reset the password, try repeating the procedure using the following statements to modify the user table directly:

UPDATE mysql.user
    SET authentication_string = PASSWORD('MyNewPass'), password_expired = 'N'
    WHERE User = 'root' AND Host = 'localhost';
FLUSH PRIVILEGES;

time regex

preg_match("/(1[012]|0[0-9]):([0-5][0-9])/", $foo)

for 12-hour or

preg_match("/(2[0-3]|[01][0-9]):([0-5][0-9])/", $foo)

for 24-hour.

If you use a 24-hour clock going from 01:00 to 24:59, use

preg_match("/(2[0-4]|[01][1-9]|10):([0-5][0-9])/", $foo)

Modify app.config in C#

Hiện giờ thường chỉ những file cấu hình đặc biệt người ta mới sử dụng file xml để cấu hình cho ứng dụng. Với những cấu hình không quá phức tạp thì việc sử dụng appSettings trong file app.config cực kỳ nhanh gọn.

Khai báo biến ‘abc’ có giá trị ‘01/01/1900 00:00:00 AM‘ trong appSettings  trong file app.config:

  1. <?xml version=“1.0”?>
  2. <configuration>
  3. <startup>
  4.   <supportedRuntime version=“v4.0” sku=“.NETFramework,Version=v4.0”/></startup>
  5.   <appSettings>
  6.     <add key=“abc” value=“01/01/1900 00:00:00 AM”/>
  7.   </appSettings>
  8. </configuration>

Để đọc giá trị của abc sử dụng:

  1. string abc = ConfigurationManager.AppSettings[“abc”];

Khi cần thay đổi các giá trị cấu hình này, cách đơn giản nhất là mở file config lên và sửa ^^!. Tuy nhiên đối với những ứng dụng cho người dùng cuối, không thể bắt người dùng tự vào chỉnh sửa được mà ta phải làm chức năng cho họ cấu hình. Dưới đây là một số hàm cần thiết để chỉnh sửa file config.

– Sửa giá trị của biến trong appSettings trong file app.config:

  1. public static void EditAppSetting(string key, string value)
  2. {
  3.     System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
  4.     config.AppSettings.Settings[key].Value = value;
  5.     config.Save(ConfigurationSaveMode.Modified);
  6.     ConfigurationManager.RefreshSection(“appSettings”);
  7. }

– Thêm 1 giá trị mới vào appSettings trong file app.config:

  1. public static void AddAppSetting(string key, string value)
  2. {
  3.     System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
  4.     config.AppSettings.Settings.Add(key,value);
  5.     config.Save(ConfigurationSaveMode.Modified);
  6.     ConfigurationManager.RefreshSection(“appSettings”);
  7. }

– Xóa 1 giá trị ra khỏi appSettings trong file app.config:

  1. public static void RemoveAppSetting(string key)
  2. {
  3.     System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
  4.     config.AppSettings.Settings.Remove(key);
  5.     config.Save(ConfigurationSaveMode.Modified);
  6.     ConfigurationManager.RefreshSection(“appSettings”);
  7. }

Demo thử hàm edit nào:

  1. Console.WriteLine(ConfigurationManager.AppSettings[“abc”]);
  2. EditAppSetting(“abc”,DateTime.Now.ToString());
  3. Console.WriteLine(ConfigurationManager.AppSettings[“abc”]);
  4. Console.ReadLine();

Dòng đầu tiên sẽ in ra giá trị của abc trước khi sửa file config.
Dòng thứ 2 tiến hành sửa giá trị abc thành giá trị thời gian hiện tại trong file config.
Dòng thứ 3 tiến hành đọc lại và in ra giá trị của abc sau khi đã sửa file config.

Chạy lại thêm một lần nữa :

Vậy là xong. Sử dụng app.config nhanh hơn so với thao tác đọc và ghi file xml nhiều đúng không nào.

Note:
– Cần add Reference System.configuration.
– Sau khi chạy chương trình thì file config bị chỉnh sửa là file config trong cùng thư mục chứa file exe (có dạng TenUngDung.exe.config) chứ không phải file app.config trong project đâu nhé.
– Quá trình sửa file config chỉ chính xác khi build ứng dụng ra thành file exe và chạy. Nếu chạy trong chế độ debug thì bị tình trạng là đọc từ file TenUngDung.exe.config nhưng lại ghi ra file TenUngDung.vshost.exe.config.

 

Các hàm tham khảo:

—– Edit value of key
public static void EditAppSetting(string key, string value)
{
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings[key].Value = value;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(“appSettings”);
}

—— remove key
public static void RemoveAppSetting(string key)
{
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings.Remove(key);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(“appSettings”);
}

—–Load all key
stackoverflow.com

Export data to excel in C#

  namespace ExportExcel  
    {      
        public partial class ExportDatatabletoExcel : Form  
        {  
            public ExportDatatabletoExcel()  
            {  
                InitializeComponent();  
            }  

            private void Form1_Load(object sender, EventArgs e)
            {

                DataTable dt = new DataTable();

                //Add Datacolumn
                DataColumn workCol = dt.Columns.Add("FirstName", typeof(String));

                dt.Columns.Add("LastName", typeof(String));
                dt.Columns.Add("Blog", typeof(String));
                dt.Columns.Add("City", typeof(String));
                dt.Columns.Add("Country", typeof(String));

                //Add in the datarow
                DataRow newRow = dt.NewRow();

                newRow["firstname"] = "Arun";
                newRow["lastname"] = "Prakash";
                newRow["Blog"] = "http://royalarun.blogspot.com/";
                newRow["city"] = "Coimbatore";
                newRow["country"] = "India";

                dt.Rows.Add(newRow);

                //open file
                StreamWriter wr = new StreamWriter(@"D:\\Book1.xls");

                try
                {

                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        wr.Write(dt.Columns[i].ToString().ToUpper() + "\t");
                    }

                    wr.WriteLine();

                    //write rows to excel file
                    for (int i = 0; i < (dt.Rows.Count); i++)
                    {
                        for (int j = 0; j < dt.Columns.Count; j++)
                        {
                            if (dt.Rows[i][j] != null)
                            {
                                wr.Write(Convert.ToString(dt.Rows[i][j]) + "\t");
                            }
                            else
                            {
                                wr.Write("\t");
                            }
                        }
                        //go to next line
                        wr.WriteLine();
                    }
                    //close file
                    wr.Close();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
    }

Import data from excel file in c#

Mô tả:Người dùng nhất vào nút “Browse …” để chọn tập tin excel cần import. Kế tiếp nhấn nút “Import excel” để thực thiện việc import dữ liệu vào database. Sau khi kết thúc import xong, lấy tất cả dữ liệu từ dabase hiển thị lên DataGridView, kết quả như hình bên dưới:https://i0.wp.com/gockinhnghiem.com/wp-content/uploads/FormImport.gif

Hình 1: Giao diện form import excel

Giờ chúng ta cùng Góc Kinh Nghiệm lần lượt làm theo các bước sau:

  • Bước 1: Tạo tập tin import tên EmployeeInfo.xls có thông tin và định dạnh như hình bên dưới:https://i0.wp.com/gockinhnghiem.com/wp-content/uploads/Dinh-dang-tap-tin-import.gif

Hình 2: thông tin và định dạng tập tin excel cần import

  • Bước 2: Vào SQL Server 2005 tạo cơ sở dữ liệu có tên HumanResourceDB và table có tên EmployeeInfo như hình bên dưới:

Hình 3: Database để lưu thông tin import

Lưu ý: ở đây bạn cũng có thể dụng SQL Server 2000 để thao tác (không nhất thiết là SQL Server 2005)

  • Bước 3: Mở Visual Studial 2010 (bạn cũng có thể dùng VS2005, VS2008 để thao tác), Vào File -> New -> Project … -> Windows (phía bên trái) -> Windows Forms Application, và gõ vào ô Name bên tên project là ImportExcel
  • Bước 4: Sau khi project được tạo, bạn đổi tên Form1 thành FormMain, vào design của FormMain tạo các đối tượng sau:
    • TextBox: tên txtFilePath, dùng để chứa đường dẫn tập tin excel cần import
    • Button: tên btnBrowse, cho phép người dùng chọn tập tin excel cần import
    • Button: tên btnImportExcel, thực hiện import khi người dùng nhấn vào nút này, sau khi import thành công sẽ hiển thị dữ liệu lên DataGridView
    • DataGridView: tên dgvData, để chứa dữ liệu được lấy từ database sau khi import xong
    • Lable “File Path” tùy ý

Tham khảo hình 1 ở trên

  • Bước 5: Nhất chuột phải lên project ImportExcel -> Add -> New Item .. -> Data (bên trái) -> DataSet (bên phải), gõ tên HumanResource.xsd vào ô Name như hình bên dưới

Hình 4: Tạo DataSet tên HummanResource.xsd

  • Bước 6: Nhấn chuột phải vào vào DataSet vừa tạo ở bước 5, chọn Add -> TableAdapter …, hiện ra một hộp thoại TableAdapter Cofiguration Wizard -> nhấn nút New Connection …, -> xuất hiện hộp thoại tên Add Connection, gõ dấu chấm (.) vào ô Server Name (dấu chấm ở đây đại diện cho localhost, tức SQL Server đang được cài trên máy hiện hành của bạn), và chọn database tên “HumanResourceDB” (database này đã tạo sẵn ở bước 2) -> nhấn nút OK -> nhất Next, và làm theo chỉ dẫn của wizard, xem hình bên dưới:

Hình 5: tạo kết nối với database

Sau khi hoàn tất Wizard, chúng ta được DataSet với kết quả hình như sau:https://i0.wp.com/gockinhnghiem.com/wp-content/uploads/Query.gif

Hình 6: kết quả của DataSet được tạo

Trong đó:

Nội dung các  hàm lần lược như sau:

GetData()

1
2
SELECT[Index], Code, FullName, WorkingYears
FROMEmployeeInfo

GetEmployeeInfoByCode()

1
2
3
SELECT[Index], Code, FullName, WorkingYears
FROMEmployeeInfo
WhereCode = @Code

InsertEmployee()

1
2
INSERTINTO[EmployeeInfo] ([Code], [FullName], [WorkingYears]) VALUES(@Code, @FullName, @WorkingYears);
SELECTSCOPE_IDENTITY()

UpdateEmployeeInfoByCode()

1
2
3
UPDATEEmployeeInfo
SETFullName = @FullName, WorkingYears = @WorkingYears
WHERE(Code = @Original_Code);
  • Bước 7: quay lại form FormMain, code như bên dưới:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
usingSystem;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Windows.Forms;
usingSystem.Data.OleDb;
namespaceImportExcel
{
    publicpartialclassFormMain : Form
    {
        publicFormMain()
        {
            InitializeComponent();
            btnBrowse.Click += newEventHandler(btnBrowse_Click);
            btnImportExcel.Click += newEventHandler(btnImportExcel_Click);
        }
        voidbtnBrowse_Click(objectsender, EventArgs e)
        {
            // Browse đến file cần import
            OpenFileDialog ofd = newOpenFileDialog();
            // Lấy đường dẫn file import vừa chọn
            txtFilePath.Text = ofd.ShowDialog() == DialogResult.OK ? ofd.FileName : "";
        }
        voidbtnImportExcel_Click(objectsender, EventArgs e)
        {
            if(!ValidInput())
                return;
            // Đọc dữ liệu từ tập tin excel trả về DataTable
            DataTable data = ReadDataFromExcelFile();
            // Import dữ liệu đọc được vào database
            ImportIntoDatabase(data);
            // Lấy hết dữ liệu import từ database hiển thị lên gridView
            ShowData();
        }
        privateboolValidInput()
        {
            if(txtFilePath.Text.Trim() == "")
            {
                MessageBox.Show("Xin vui lòng chọn tập tin excel cần import");
                returnfalse;
            }
            returntrue;
        }
        privateDataTable ReadDataFromExcelFile()
        {
            stringconnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+ txtFilePath.Text.Trim() + ";Extended Properties=Excel 8.0";
            // Tạo đối tượng kết nối
            OleDbConnection oledbConn = newOleDbConnection(connectionString);
            DataTable data = null;
            try
            {
                // Mở kết nối
                oledbConn.Open();
                // Tạo đối tượng OleDBCommand và query data từ sheet có tên "Sheet1"
                OleDbCommand cmd = newOleDbCommand("SELECT * FROM [Sheet1$]", oledbConn);
                // Tạo đối tượng OleDbDataAdapter để thực thi việc query lấy dữ liệu từ tập tin excel
                OleDbDataAdapter oleda = newOleDbDataAdapter();
                oleda.SelectCommand = cmd;
                // Tạo đối tượng DataSet để hứng dữ liệu từ tập tin excel
                DataSet ds = newDataSet();
                // Đổ đữ liệu từ tập excel vào DataSet
                oleda.Fill(ds);
                data = ds.Tables[0];
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                // Đóng chuỗi kết nối
                oledbConn.Close();
            }
            returndata;
        }
        privatevoidImportIntoDatabase(DataTable data)
        {
            if(data == null|| data.Rows.Count == 0)
            {
                MessageBox.Show("Không có dữ liệu để import");
                return;
            }
            HumanResourceTableAdapters.EmployeeInfoTableAdapter adapter = newHumanResourceTableAdapters.EmployeeInfoTableAdapter();
            stringcode = "", fullName = "";
            intworkingYears = 0;
            try
            {
                for(inti = 0; i < data.Rows.Count; i++)
                {
                    code = data.Rows[i]["Code"].ToString().Trim();
                    fullName = data.Rows[i]["FullName"].ToString().Trim();
                    workingYears = int.Parse(data.Rows[i]["WorkingYears"].ToString().Trim());
                    HumanResource.EmployeeInfoDataTable existingEmployee = adapter.GetEmployeeInfoByCode(code);
                    // Nếu nhân viên chưa tồn tại trong DB thì thêm mới
                    if(existingEmployee == null|| existingEmployee.Rows.Count == 0)
                    {
                        adapter.InsertEmployee(code, fullName, workingYears);
                    }
                    // Ngược lại, nhân viên đã tồn tại trong DB thì update
                    else
                    {
                        adapter.UpdateEmployeeInfoByCode(fullName, workingYears, code);
                    }
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            MessageBox.Show("Kết thúc import");
        }
        privatevoidShowData()
        {
            HumanResourceTableAdapters.EmployeeInfoTableAdapter adapter = newHumanResourceTableAdapters.EmployeeInfoTableAdapter();
            dgvData.DataSource = adapter.GetData();
        }
    }
}

Bước 8: Build và chạy chương trình, thu được kết quả như hình 1 bên trên

//

int i = 2; // Với i là Sheet cần load của file Excel đó.
string query = String.Format(“select * from [Sheet{0}$]”, i);// Ở đây lấy dữ liệu của Sheet2

C # – Truyền dữ liệu giữa các Form

Truyền dữ liệu giữa các Window Form rất quan trọng khi làm ví dụ với các hộp thoại . Hoặc đơn giản chỉ là hệ thống đầu vào của nhiều cửa sổ. Trong bài viết này sẽ là 3 cách cơ bản để truyền dữ liệu giữa các Form.

Để đơn giản, chúng ta sẽ truyền một thông điệp dạng text từ một form A sang form B. Form A sẽ có một textbox để nhập thông điệp và một button để gọi form B. Form B sẽ có 1 label để nhận thông điệp.

1. Dùng Contructor

Mọi thứ trong C# đều là class, kể cả Form. Mà class thì luôn có hàm khởi tạo (Contructor). Ta sẽ lợi dụng điều này để truyền tham số vào Form qua Contructor.

Form2 :
Code

Tiếp theo cài đặt trên Form1 :
Code

Khi nhấn nút Send trên Form1, thông điệp trong textbox sẽ được truyền vào tham số của hàm khởi tạo Form2. Nhờ vậy, thông điệp được truyền vào biến _message của Form2.
2. Dùng Properties

Một cách khác để truyền dữ liệu giữa 2 Form là dùng Properties. Trong Form2, ta sẽ khai báo một thuộc tính để lưu giữ thông điệp nhận từ Form1. Khi gọi Form2, Form1 sẽ gán thông điệp trực tiếp vào thuộc tính này.
Form2 :
Code

Form1 :
Code

3. Dùng Delegate

Delegate là một khái niệm khá thú vị và mạnh mẽ trong C#. Nó có rất nhiều ứng dụng và truyền dữ liệu giữa các Form là một trong những ứng dụng đó. Nếu bạn đã từng học qua C++ thì bạn sẽ thấy Delegate cũng tương tự như con trỏ hàm trong C++.

Để thực hiện, trong Form2 ta sẽ khai báo một Delegate có nhiệm vụ nhận vào một tham số và không trả về giá trị. Đồng thời tạo một hàm để lấy tham số của Delegate. Và trong Form1, ta sẽ gọi Delegate này với tham số truyền vào là một chuỗi thông điệp cần gửi.
Form2 :
Code

Form1 :
Code

Trên đây là 3 phương pháp đơn giản nhất để truyền dữ liệu giữa các Form. Hy vọng các bạn sẽ vận dụng tốt các phương pháp này trong chương trình của mình.

How to use resolve the zkemkeeper embedd issue?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using iTimeService.dsitimeTableAdapters;
using System.IO;

namespace iTimeService
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }
        public zkemkeeper.CZKEMClass axCZKEM1 = new zkemkeeper.CZKEMClass();
        private bool bIsConnected = false;//the boolean value identifies 
whether the device is connected
        private int iMachineNumber = 1;//the serial number of the device.
After connecting the device ,this value will be changed.
        TENTERTableAdapter tenteradapter = new TENTERTableAdapter();
        T012_GATETableAdapter gateadapter = new T012_GATETableAdapter();
    }
}


Answer: click on the reference you have, I think for that specific project
that would be ‘zkemkeeper’ then on its properties just set the ‘Embed Interop Type’
to ‘False’ I hope this would help.