Thứ Năm, 25 tháng 12, 2014

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

SQL Server: Chuyển database từ một phiên bản cao hơn sang phiên bản thấp hơn

Tham khảo:

Do keep in mind, of course, that this is probably not a practical option with a large database.  When I've had to do this with 5-10GB DBs, especially when I know I'll be doing it more than once (data coming in from an external site that running a newer version of SQL than we are), I use a variation of this plus SSIS, as follows:
1.  Generate the DB scripts as above, schema only.
2.  Create the empty database.
3.  Use the "Import/Export" commands to import data from the newer version DB into the older one.  Save the SSIS package thus generated.
4.  You may need to modify the default column mappings; for instance, if there are columns of the timestamp datatype, those can't actually be moved over this way.


Thứ Hai, 27 tháng 10, 2014

Base64 Encode/Decode C#

        public static string ToBase64(this string src, Encoding encoding)
        {
            byte[] b = encoding.GetBytes(src);
            return Convert.ToBase64String(b);
        }

        public static string Base64ToString(this string src, Encoding encoding)
        {
            byte[] b = Convert.FromBase64String(src);
            return encoding.GetString(b);
        }

Remove Html Tag, Html Encode/Decode, Url Encode/Decode

Thỉnh thoảng cần dùng, lưu lại cho nhớ.

        public static string RemoveHtml(this string text)
        {
            return Regex.Replace(text, "<[^>]*>", string.Empty);
        }

        public static string HtmlEncode(this string src)
        {
            return System.Net.WebUtility.HtmlEncode(src);
        }

        public static string HtmlDecode(this string src)
        {
            return System.Net.WebUtility.HtmlDecode(src);
        }

        public static string UrlEncode(this string src)
        {
            return System.Web.HttpUtility.UrlEncode(src);
        }

        public static string UrlDecode(this string src)
        {
            return System.Web.HttpUtility.UrlDecode(src);
        }

Thứ Ba, 14 tháng 10, 2014

Set a Database to Single-user Mode

Using SQL Server Management Studio


To set a database to single-user mode

  1. In Object Explorer, connect to an instance of the SQL Server Database Engine, and then expand that instance.
  2. Right-click the database to change, and then click Properties.
  3. In the Database Properties dialog box, click the Options page.
  4. From the Restrict Access option, select Single.
  5. If other users are connected to the database, an Open Connections message will appear. To change the property and close all other connections, click Yes.
You can also set the database to Multiple or Restricted access by using this procedure. For more information about the Restrict Access options, see Database Properties (Options Page).

Using Transact-SQL


To set a database to single-user mode

  1. Connect to the Database Engine.
  2. From the Standard bar, click New Query.
  3. Copy and paste the following example into the query window and click Execute. This example sets the database to SINGLE_USER mode to obtain exclusive access. The example then sets the state of the AdventureWorks2012 database to READ_ONLY and returns access to the database to all users.The termination option WITH ROLLBACK IMMEDIATE is specified in the first ALTER DATABASE statement. This will cause all incomplete transactions to be rolled back and any other connections to the AdventureWorks2012 database to be immediately disconnected.
USE master;
GO
ALTER DATABASE AdventureWorks2012
SET SINGLE_USER
WITH ROLLBACK IMMEDIATE;
GO
ALTER DATABASE AdventureWorks2012
SET READ_ONLY;
GO
ALTER DATABASE AdventureWorks2012
SET MULTI_USER;
GO

http://msdn.microsoft.com/en-us/library/ms345598.aspx

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);
}