Hướng dẫn xây dựng Windows Service

Hướng dẫn xây dựng windows services (How to create a windows services)

  • Tạo dự án chọn loại Windows Services

1

  • Đặt tên cho Windows Service

2

  • Click chuột phải trên MyServiceDemo (Design) > Add Installer, VS sẽ add 2 thành phần vào MyServiceDemo như sau

3

  • Thiết lập tài khoản chạy Service bằng cách click vào serviceProcessInstaller1
    • Thiết lập loại tài khoản Account: LocalSystem
    • Click chọn ServiceInstaller1 thiết lập kiểu khởi động và tên services
      • StartType: Automatic
      • Description: My Service Demo
      • DisplayName: My Service Demo
  • Viết code cho 2 sự kiện của service khi khởi động và tắt dịch vụ

protected override void OnStart(string[] args)
{
File.WriteAllText(“c:\\temp\\log.txt”,”Started time:” + DateTime.Today.ToLongTimeString());
}

protected override void OnStop()
{

File.WriteAllText(“c:\\temp\\log.txt”,”Started time:” + DateTime.Today.ToLongTimeString());

}

  • Biên dịch Project
  • Mở Visual Studio Command với quyền là Administrator
  • Chuyển đến thư mục chứa file exe của windows services vừa biên dịch
  • Gõ lệnh
  • Installutil /i tencuaproject.exe

WCF and ASP.NET Web API

Bảng dưới đây mô tả sự khác nhau giữa WCF and ASP.NET Web API, từ bảng này chúng ta có thể lựa chọn công nghệ phù hợp cho từng bài toán.

WCF ASP.NET Web API
Enables building services that support multiple transport protocols (HTTP, TCP, UDP, and custom transports) and allows switching between them. HTTP only. First-class programming model for HTTP. More suitable for access from various browsers, mobile devices etc enabling wide reach.
Enables building services that support multiple encodings (Text, MTOM, and Binary) of the same message type and allows switching between them. Enables building Web APIs that support wide variety of media types including XML, JSON etc.
Supports building services with WS-* standards like Reliable Messaging, Transactions, Message Security. Uses basic protocol and formats such as HTTP, WebSockets, SSL, JQuery, JSON, and XML. There is no support for higher level protocols such as Reliable Messaging or Transactions.
Supports Request-Reply, One Way, and Duplex message exchange patterns. HTTP is request/response but additional patterns can be supported through SignalRand WebSockets integration.
WCF SOAP services can be described in WSDL allowing automated tools to generate client proxies even for services with complex schemas. There is a variety of ways to describe a Web API ranging from auto-generated HTML help page describing snippets to structured metadata for OData integrated APIs.
Ships with the .NET framework. Ships with .NET framework but is open-source and is also available out-of-band as independent download.

Regular Expression

Regular Expression

Character class Description Pattern Matches
[character_group] Matches any single character in character_group. By default, the match is case-sensitive. [ae] “a” in “gray”

“a”, “e” in “lane”

[^character_group] Negation: Matches any single character that is not in character_group. By default, characters in character_group are case-sensitive. [^aei] “r”, “g”, “n” in “reign”
[firstlast] Character range: Matches any single character in the range from first to last. [A-Z] “A”, “B” in “AB123”
. Wildcard: Matches any single character except \n.

To match a literal period character (. or \u002E), you must precede it with the escape character (\.).

a.e “ave” in “nave”

“ate” in “water”

\p{name} Matches any single character in the Unicode general category or named block specified by name. \p{Lu}

\p{IsCyrillic}

“C”, “L” in “City Lights”

“Д”, “Ж” in “ДЖem”

\P{name} Matches any single character that is not in the Unicode general category or named block specified by name. \P{Lu}

\P{IsCyrillic}

“i”, “t”, “y” in “City”

“e”, “m” in “ДЖem”

\w Matches any word character. \w “I”, “D”, “A”, “1”, “3” in “ID A1.3”
\W Matches any non-word character. \W ” “, “.” in “ID A1.3”
\s Matches any white-space character. \w\s “D ” in “ID A1.3”
\S Matches any non-white-space character. \s\S ” _” in “int __ctr”
\d Matches any decimal digit. \d “4” in “4 = IV”
\D Matches any character other than a decimal digit. \D ” “, “=”, ” “, “I”, “V” in “4 = IV”
Assertion Description Pattern Matches
^ The match must start at the beginning of the string or line. ^\d{3} “901” in

“901-333-“

$ The match must occur at the end of the string or before \n at the end of the line or string. -\d{3}$ “-333” in

“-901-333”

\A The match must occur at the start of the string. \A\d{3} “901” in

“901-333-“

\Z The match must occur at the end of the string or before \n at the end of the string. -\d{3}\Z “-333” in

“-901-333”

\z The match must occur at the end of the string. -\d{3}\z “-333” in

“-901-333”

\G The match must occur at the point where the previous match ended. \G\(\d\) “(1)”, “(3)”, “(5)” in “(1)(3)(5)[7](9)”
\b The match must occur on a boundary between a \w (alphanumeric) and a \W (nonalphanumeric) character. \b\w+\s\w+\b “them theme”, “them them” in “them theme them them”
\B The match must not occur on a \b boundary. \Bend\w*\b “ends”, “ender” in “end sends endure lender”

What is Unobtrusive Validation?

In a normal validation scenario, when we use a validator to validate any control and use Client side validation, some JavaScript is generated and rendered as HTML. Also some supportive JavaScript files also get loaded by the browser for the validation.

Now with feature Unobtrusive Validation, inline JavaScript is not generated and rendered to handle the Client Side validation. Instead of this, it uses HTML5 data-* attributes for all these validation.

S0 now let’s see a normal scenario. I have taken textbox and applied two ASP.NET validators on it. One is RequiredFieldValidator and RangeValidator that allows to enter the value between 100 and 1000. Let’s see the aspx code:

unobtrusive

Đọc dữ liệu từ Excel

Mã nguồn dưới đây hướng dẫn cách đọc dữ liệu từ Excel vào cơ sở dữ liệu

var fullFileName =”PathOfExcelFile”;
var connectionString = string.Format(“Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties=Excel 8.0;data source={0};”, fullFileName);
var adapter = new OleDbDataAdapter(“select * from [Ten_Sheet$]”, connectionString);
var ds = new DataSet();
string tableName = “tableName”;
adapter.Fill(ds, tableName);
DataTable data = ds.Tables[tableName];
dataGridView1.Columns.Clear();
dataGridView1.DataSource = data;

Export to excel C#- Xuất dữ liệu ra excel bằng c#

Mã nguồn dưới đây hướng dẫn cách xuất dữ liệu ra excel trong C#

public void ExportToExcel(DataTable dataTable, string ExcelFilePath)
{
try
{
int ColumnsCount;

if (DataTable == null || (ColumnsCount = dataTable.Columns.Count) == 0)
throw new Exception(“ExportToExcel: Null or empty input table!\n”);

// create a new workbook
Microsoft.Office.Interop.Excel.Application Excel = new Microsoft.Office.Interop.Excel.Application();
Excel.Workbooks.Add(System.Reflection.Missing.Value);

object misValue = System.Reflection.Missing.Value;

// single worksheet
Microsoft.Office.Interop.Excel._Worksheet Worksheet = (Microsoft.Office.Interop.Excel._Worksheet)Excel.ActiveSheet;

object[] Header = new object[ColumnsCount];

// column headings
for (int i = 0; i < ColumnsCount; i++)
Header[i] = dataTable.Columns[i].ColumnName;

Microsoft.Office.Interop.Excel.Range HeaderRange = Worksheet.get_Range((Microsoft.Office.Interop.Excel.Range)(Worksheet.Cells[1, 1]), (Microsoft.Office.Interop.Excel.Range)(Worksheet.Cells[1, ColumnsCount]));
HeaderRange.Value2 = Header;
HeaderRange.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightGray);
HeaderRange.Font.Bold = true;

// DataCells
int RowsCount = dataTable.Rows.Count;
object[,] Cells = new object[RowsCount, ColumnsCount];

for (int j = 0; j < RowsCount; j++)
for (int i = 0; i < ColumnsCount; i++)
Cells[j, i] = dataTable.Rows[j][i];

Worksheet.get_Range((Microsoft.Office.Interop.Excel.Range)(Worksheet.Cells[2, 1]), (Microsoft.Office.Interop.Excel.Range)(Worksheet.Cells[RowsCount + 1, ColumnsCount])).Value2 = Cells;

// check fielpath
if (ExcelFilePath != null && ExcelFilePath != “”)
{
try
{
Worksheet.SaveAs(ExcelFilePath, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue);

Excel.Visible = true;
}
catch (Exception ex)
{
throw new Exception(“ExportToExcel: Excel file could not be saved! Check filepath.\n”
+ ex.Message);
}
}
else // no filepath is given
{
Excel.Visible = true;
}
}
catch (Exception ex)
{
throw new Exception(“ExportToExcel: \n” + ex.Message);
}
}

Gọi hàm ExportToExcel()

ExportToExcel(table, fileOnDisk);