Thứ Năm, 31 tháng 7, 2014

Xác thực SPF cho domain gửi email

Trỏ 1 record txt cho domain để chỉ ra rằng các địa chỉ email của domain sẽ gửi email ra từ các smtp server có địa chỉ ip là bao nhiêu.

Ví dụ:
v=spf1 ip4:103.246.222.0/24 ?all

Đối với domain chưa xác thực:

Return-Path: <phong.nd@hanhtranglaptrinh.net>
Received: from smtp222.defaultip.fbems.net ([103.246.222.113])
        by mx.google.com with SMTP id yq7si4958059pac.112.2014.07.31.00.52.13
        for <nguyendoanphonxxxt@gmail.com>;
        Thu, 31 Jul 2014 00:52:14 -0700 (PDT)
Received-SPF: none (google.com: phong.nd@hanhtranglaptrinh.net does not designate permitted sender hosts) client-ip=103.246.222.113;

Đối với domain được xác thực:

Return-Path: <phong.nd@hanhtranglaptrinh.com>
Received: from smtp222.defaultip.fbems.net ([103.246.222.132])
        by mx.google.com with SMTP id g6si4844506pat.154.2014.07.31.00.07.47
        for <nguyendoanphonxxxt@gmail.com>;
        Thu, 31 Jul 2014 00:07:48 -0700 (PDT)
Received-SPF: pass (google.com: domain of phong.nd@hanhtranglaptrinh.com designates 103.246.222.132 as permitted sender) client-ip=103.246.222.132;

Tham khảo: https://support.google.com/a/answer/33786?hl=en
Tham khảo SPF Record Syntax: http://www.openspf.org/SPF_Record_Syntax

Thứ Ba, 29 tháng 7, 2014

Log4net Example

Thêm cấu hình trong App.config hoặc Web.config

<configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net debug="true">
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="LogFileName.txt" />
      <appendToFile value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="1MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%-5p %-8d %rms %-22.22c{1} %-18.18M - %m%n" />
      </layout>
    </appender>
    <root>
      <level value="ALL" />
      <appender-ref ref="RollingLogFileAppender" />
    </root>
</log4net>

Đối với ứng dụng Web thêm đoạn cấu hình vào sự kiện Application_Start:
protected void Application_Start(object sender, EventArgs e)
{
      log4net.Config.XmlConfigurator.Configure();
}

Để sử dụng trong mỗi Class thì khai báo thêm biến thành viên:
private static readonly ILog logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

Thứ Ba, 3 tháng 6, 2014

Send mail sử dụng socket C# (Giao thức SMTP)

Do công ty mình có nhu cầu cần can thiệp vào quá trình gửi mail của SMTP Server nên mình không dùng thư viện gửi mail có sẵn của .NET.

Dưới đây là quá trình giao tiếp cơ bản của giao thức SMTP.

Đoạn code do mình chuyển qua C# dựa vào bài viết gửi mail sử dụng dòng lệnh (CMD)  http://www.wikihow.com/Send-Email-Using-Telnet


TcpClient client = new TcpClient();

string log = "";

client.Connect("mail.emailserver.vn", 25);
            
StreamReader sr = new StreamReader(client.GetStream());
StreamWriter sw = new StreamWriter(client.GetStream());

log += "Server: " + sr.ReadLine() + "\n";

string data = "HELO";//một vài server yêu cầu phải HELO sender hostname

log += "Client: " + data + "\n";
sw.WriteLine(data);
sw.Flush();

log += "Server: " + sr.ReadLine() + "\n";

//Khai báo địa chỉ người gửi
data = "MAIL FROM: <" + "nguyxxdoxxphoxx.it@gmail.com" + ">";
log += "Client: " + data + "\n";
sw.WriteLine(data);
sw.Flush();
log += "Server: " + sr.ReadLine() + "\n";

//Khai báo địa chỉ người nhận
data = "RCPT TO: <" + "phong.nd@emailserver.vn" + ">";
log += "Client: " + data + "\n";
sw.WriteLine(data);
sw.Flush();
log += "Server: " + sr.ReadLine() + "\n";

//Gửi yêu cầu báo hiệu sẽ gửi nội dung bức thư
data = "DATA";
log += "Client: " + data + "\n";
sw.WriteLine(data);
sw.Flush();
log += "Server: " + sr.ReadLine() + "\n";

//Khai báo nội dung bức thư
data = emailContent + "\r\n" + ".";
log += "Client: " + data + "\n";
sw.WriteLine(data);
sw.Flush();
log += "Server: " + sr.ReadLine() + "\n";

//Ngắt kết nối với SMTP Server hoặc Email Server
data = "QUIT";
log += "Client: " + data + "\n";
sw.WriteLine(data);
sw.Flush();
log += "Server: " + sr.ReadLine() + "\n";

sr.Close();
sw.Close();
client.Close();

Thứ Sáu, 30 tháng 5, 2014

Simple Bulk Insert SQL Server

BULK INSERT tblTest
FROM 'c:\test.txt'
WITH
(
         FIELDTERMINATOR =',',
         ROWTERMINATOR ='\n'
);

Thứ Sáu, 11 tháng 4, 2014

Sự khác nhau giữa Struct và Class trong C#

Structs share most of the same syntax as classes, although structs are more limited than classes:

  • Within a struct declaration, fields cannot be initialized unless they are declared as const or static.
  • A struct cannot declare a default constructor (a constructor without parameters) or a destructor.
  • Structs are copied on assignment. When a struct is assigned to a new variable, all the data is copied, and any modification to the new copy does not change the data for the original copy. This is important to remember when working with collections of value types such as Dictionary<string, myStruct>.
  • Structs are value types and classes are reference types.
  • Unlike classes, structs can be instantiated without using a new operator.
  • Structs can declare constructors that have parameters.
  • A struct cannot inherit from another struct or class, and it cannot be the base of a class. All structs inherit directly from System.ValueType, which inherits from System.Object.
  • A struct can implement interfaces.
  • A struct can be used as a nullable type and can be assigned a null value.

Thứ Tư, 26 tháng 3, 2014

Mã hóa HMACSHA256

    private string HMACSHA256(string message, string secret)
    {
        secret = secret ?? "";
        var encoding = new System.Text.ASCIIEncoding();
        byte[] keyByte = encoding.GetBytes(secret);
        byte[] messageBytes = encoding.GetBytes(message);
        using (var hmacsha256 = new HMACSHA256(keyByte))
        {
            byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
            string sbinary = "";
            for (int i = 0; i < hashmessage.Length; i++)
            {
                sbinary += hashmessage[i].ToString("x2"); // hex format
            }
            return sbinary;
        }
    }

Thứ Sáu, 7 tháng 3, 2014

Gửi 1 file word qua máy in để in sử dụng c#

string[] files = Directory.GetFiles(Environment.CurrentDirectory, "*.docx");
foreach (var file in files)
{
 System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo(file);
 info.Arguments = "\"" + printDialog1.PrinterSettings.PrinterName + "\"";
 info.CreateNoWindow = true;
 info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
 info.UseShellExecute = true;
 info.Verb = "PrintTo";
 System.Diagnostics.Process.Start(info);
}