Thứ Sáu, 17 tháng 10, 2014

Qui đổi thời gian từ một tuần cụ thể trong một năm ra ngày bắt đầu của tuần và ngày kết thúc của tuần trong năm đó

DECLARE @Tuan INT
      , @Nam char(4);

SELECT @Tuan = 38
     , @Nam = 2014
-- once you have the @WeekNum and @YearNum set, the following calculates the date range.
SELECT DATEADD(wk, DATEDIFF(wk, 6, '1/1/' + @Nam ) + (@Tuan -1), 6) AS StartOfWeek;
SELECT DATEADD(wk, DATEDIFF(wk, 5, '1/1/' + @Nam ) + (@Tuan -1), 5) AS EndOfWeek;

Thứ Năm, 9 tháng 10, 2014

Thực thi một thủ tục trên SQL server 2008 - execute procedure SQL server

1. Tạo DB có tên là DBTest
2. Tạo một bảng User trong DBTest
create table User(UserID int primary key identity(1,1), UserName varchar(50));
insert into User Values('test')
insert into User Values('test2')
3. Nếu chưa có thủ tục ->Tạo thủ tục. Câu lệnh tạo thủ tục
CREATE PROC test(@UserID int)--@UserID là tham số truyền vào kiểu số nguyên
AS
BEGIN
 select Username from User where UserID=@UserID;
END
4. Câu lệnh thực thi
execute test @UserID=1;
5.Kết quả
-- UserName
    test

Thứ Tư, 8 tháng 10, 2014

Tính số ngày giữa 2 ngày tháng cho trước C#

DateTime now = DateTime.Now;
DateTime then = new DateTime (1, 1, 2005);
TimeSpan diff = now - then;
int days = diff.Days;
 Hoặc.

private int DateDiffInDays(DateTime fromDate, DateTime toDate)
{
return toDate.Subtract(fromDate).Days;
}

Thứ Bảy, 4 tháng 10, 2014

Thứ Năm, 2 tháng 10, 2014

Configuring Apache for SSL and LDAP authentication

Configuring Apache for SSL and LDAP authentication


tags: , , 

Imagine you have a directory on your web server you want to protect so that people have to login to see the item in it. You don’t want to give them a different password to remember but use an existing username/password in an LDAP directory. You want to make sure that when they login that their username and password are sent encrypted across the network. Below are directions to do exactly what I describe. That is if you have an LDAP server.
The Head of Computer and Networking Systems originally wrote these directions (which are amazing and better than most of what I found on the web) when I wanted to password protect our internal blogs. I’ve updated them to be more generic and posted them because they are relevant if you want to set up LDAP authentication for MediaWiki. Note that steps f to i in the section “Configure LDAPs authentication for Directory access”

Set up SSL on Web Server

  1. On the server where you want to perform SSL, Generate Server Private key (one time)
    1. Remove default keys
      cd /etc/apache2/
      rm ssl.key/server.key
      rm ssl.crt/server.crt
    2. Generate new private key
      /usr/bin/openssl genrsa 1024 > /etc/apache2/ssl.key/server.key
    3. Set secure permissions on key file
      chmod go-rwx /etc/apache2/ssl.key/server.key
  2. Create self-signed certificate
    1. Create certificate

      /usr/bin/openssl req -new -key /etc/apache2/ssl.key/server.key -x509 -days 365 -out
      /etc/apache2/ssl.crt/server.crt
      You are about to be asked to enter information that will be incorporated
      into your certificate request.

      What you are about to enter is what is called a Distinguished Name or a DN.

      There are quite a few fields but you can leave some blank

      For some fields there will be a default value,
      If you enter ‘.’, the field will be left blank.
      —–

      Country Name (2 letter code) [AU]:US
      State or Province Name (full name) [Some-State]: State
      Locality Name (eg, city) []: City
      Organization Name (eg, company) [Internet Widgits Pty Ltd]: Some Organization
      Organizational Unit Name (eg, section) []: Some Unit
      Common Name (eg, YOUR name) []: server.webaddress.com
      Email Address []: email@address.com
  3. Configure apache for SSL
    1. Tell apache SSL port
      1. Edit /etc/apache2/listen.conf and remove # before:
        Listen 443
      2. Copy virtual host template file (must end in .conf)

        cp /etc/apache2/vhosts.d/vhost-ssl.template /etc/apache2/vhosts.d/vhost-ssl.conf
      3. Change the following lines in /etc/apache2/vhosts.d/vhost-ssl.conf
        #<IfDefine SSL>

        #<IfDefine !NOSSL>
        <VirtualHost server.webaddress.com:443>
        DocumentRoot “/srv/www/htdocs”

        ServerName server.webaddress.com:443

        ServerAdmin email@address.com

        ErrorLog /var/log/apache2/error_443_log

        TransferLog /var/log/apache2/access_443_log
        #</IfDefine>

        #</IfDefine>
    2. Restart Apache with new configuration

      Apache2ctl stop
      Apache2ctl start
    3. Use Netstat to check to see if httpd is listening on port 443
      netstat -anp |more
    4. Open port on Firewall for 443
    1. Test in web browser https://server.webaddress.com

    Configure LDAPs authentication for Directory access

    1. Import certificate for ldap server into the web server where you want to authenticate via LDAP
      1. Export server certificate from your LDAP server
      2. Open exported certificate file and copy text
      3. Create file /etc/apache2/server-name.crt
      4. Paste certificate text into file
      5. Edit /etc/apache2/default-server.conf and add following lines:
        LDAPTrustedCAType    BASE64_FILE
        LDAP
        TrustedCA                       /etc/apache2/server-name.crt
      6. Edit /etc/apache2/vhosts.d/vhost-ssl.conf
        1. Add lines following between <VirtualHost> and </VirtualHost>
          <Directory /srv/www/htdocs/directory_you_want_to_protect_with_ldap>

          AuthType Basic
          AuthName “LDAPs Login”

          AuthLDAPEnabled on
          AuthLDAPURL “ldaps://ldapserver.domain.edu:ldapport#/OU=usergroup,DC=subdomain,DC=mydomain,DC=edu?sAMAccountName?sub?(objectClass=*)”

          AuthLDAPBindDN “CN=bindaccount,CN=usergroup,DC=subdomain,DC=mydomain,DC=edu”

          AuthLDAPBindPassword (bindaccountpassword)
          AuthLDAPAuthoritative off
          require valid-user
          AllowOverride None
          Order deny,allow
          Deny from all
          Allow from IP range you want to allow access from
          </Directory>
      7. Edit /etc/apache2/sysconfig.d/loadmodule.conf and add following
        lines:
        LoadModule ldap_module /usr/lib/apache2/mod_ldap.so

        LoadModule auth_ldap_module /usr/lib/apache2/mod_auth_ldap.so
      8. Restart Apache with new configuration
        Apache2ctl stop
        Apache2ctl start
      9. Test in web browser – https://server.webaddress.com/directory_you_want_to_protect_with_ldap

    Cấu hình xác thực ldap

    Xác thực ldap: Cần có một server đã được thiết lập xác thực ldap - vd.
    https://code.google.com/p/openssl-for-windows/downloads/list
    serverxacthuldap.compnay.com

    1. Chạy trên Xampp
    1.1. cấu hình
    mở file ở thư mục cài đặt xampp
    tìm tới vd: C:\xampp\php\php.ini
    ;extension=php_ldap.dll
    bỏ comment màu đỏ đi ->extension=php_ldap.dll
    1.2. Code thực thi
    <html>
    <head></head>
    <body>
    <?php

    // using ldap bind
    $ldaprdn  = 'username@company.com';     // ldap rdn or dn
    $ldappass = '123456';  // associated password

    // connect to ldap server
    $ldapconn = ldap_connect("ldap://serverxacthuldap.compnay.com") // Địa chỉ domain hoặc server dùng để xác thực
        or die("Could not connect to LDAP server.");

    if ($ldapconn) {

        // binding to ldap server
        $ldapbind = ldap_bind($ldapconn, $ldaprdn, $ldappass);

        // verify binding
        if ($ldapbind) {
            echo "LDAP bind successful...";
        } else {
            echo "LDAP bind failed...";
        }

    }

    ?>
    </body>
    </html>

    Thứ Sáu, 26 tháng 9, 2014

    Ghi log trong C#

     public void Log(string Message, TextWriter w)
        {
            w.Write("\r\nLog Entry: ");
            w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString());
            w.WriteLine(" :");
            w.WriteLine(" :{0}", Message);
            w.WriteLine("-------------------------------");
        }
        public void DumpLog(StreamReader r)
        {
            string line;
            while ((line = r.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
        }



                using (StreamWriter w = File.AppendText(SererLogFileMapPath + "log.txt"))
                {
                    Log(ex.Message, w);
                }
                using (StreamReader tr = File.OpenText(SererLogFileMapPath + "log.txt"))
                {
                    DumpLog(tr);
                }

    Thứ Năm, 18 tháng 9, 2014

    Cách thêm một bản ghi mới vào trong một bảng dữ liệu có sẵn

    Ví dụ: Bảng User( ID,Name,Age)
    1. Câu lệnh thực thi thêm dữ liệu
    INSERT INTO User VALUES( '1234','tên của bạn',20)
    Hoặc 
    INSERT INTO User( ID,Name,Age) VALUES( '1234','tên của bạn',20)
     
    2. Câu lệnh lấy kết quả vừa thêm mới
     SELECT  ID,Name,Age FROM User ;

    WITH common_table_expression (Transact-SQL)

    Specifies a temporary named result set, known as a common table expression (CTE). This is derived from a simple query and defined within the execution scope of a single SELECT, INSERT, UPDATE, or DELETE statement. This clause can also be used in a CREATE VIEW statement as part of its defining SELECT statement. A common table expression can include references to itself. This is referred to as a recursive common table expression.

    [ WITH <common_table_expression> [ ,...n ] ]
    
    <common_table_expression>::=
        expression_name [ ( column_name [ ,...n ] ) ]
        AS
        ( CTE_query_definition )
     
    -- Define the CTE expression name and column list.
    WITH Sales_CTE (SalesPersonID, SalesOrderID, SalesYear)
    AS
    -- Define the CTE query.
    (
        SELECT SalesPersonID, SalesOrderID, YEAR(OrderDate) AS SalesYear
        FROM Sales.SalesOrderHeader
        WHERE SalesPersonID IS NOT NULL
    )
    -- Define the outer query referencing the CTE name.
    SELECT SalesPersonID, COUNT(SalesOrderID) AS TotalSales, SalesYear
    FROM Sales_CTE
    GROUP BY SalesYear, SalesPersonID
    ORDER BY SalesPersonID, SalesYear;
    GO 

     

    Lấy giá trị của một radio xem đang ở trạng thái check hay chưa check

    <input type="radio" id="chktest" name="test"/> 
    <script>
    if ($('[name="test"]').is(':checked'))
    </script> 

    Thứ Tư, 17 tháng 9, 2014

    chuyển đổi từ kiểu chuỗi sang kiểu số - và check xem chuỗi truyển vào chỉ là số hay không

    int num;
    bool isNumeric = int.TryParse(txtNum.text, out num);
    if(isNumeric)
    {
    // Do your code, the value is number
    }
    else
    {
    // value is not a number
    }

    Thứ Tư, 30 tháng 7, 2014

    chuyển từ chuỗi sang datetime

    string dateTime = DateTime.Now.ToString("yyyy-MM-dd h:mm tt");   
    
    DateTime dt = DateTime.Parse(dateTime);

    Thứ Ba, 29 tháng 7, 2014

    Lấy các ngày trong tuần sử dụng biến DateTime C#

    using System;
    
    class Program
    {
        static void Main()
        {
     // Get currrent day of week.
     DayOfWeek today = DateTime.Today.DayOfWeek;
     Console.WriteLine("Today is {0}",
         today);
    
     // Test current day of week.
     if (today == DayOfWeek.Monday)
     {
         Console.WriteLine("DO WORK");
     }
    
     // Demonstrate all DayOfWeek values.
     Console.WriteLine("{0}, {1}, {2}, {3}, {4}, {5}, {6}",
         DayOfWeek.Monday,
         DayOfWeek.Tuesday,
         DayOfWeek.Wednesday,
         DayOfWeek.Thursday,
         DayOfWeek.Friday,
         DayOfWeek.Saturday,
         DayOfWeek.Sunday);
        }
    }
    
    Output
    
    Today is Monday
    DO WORK
    Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday

    Thứ Bảy, 26 tháng 7, 2014

    Thêm dữ liệu quan hệ giữa hai bảng trong C# - Add Relations

    In a DataSet with multiple DataTable objects, you can use DataRelation objects to relate one table to another, to navigate through the tables, and to return child or parent rows from a related table.
    The arguments required to create a DataRelation are a name for the DataRelation being created, and an array of one or more DataColumn references to the columns that serve as the parent and child columns in the relationship. After you have created a DataRelation, you can use it to navigate between tables and to retrieve values.
    Adding a DataRelation to a DataSet adds, by default, a UniqueConstraint to the parent table and a ForeignKeyConstraint to the child table. For more information about these default constraints, see DataTable Constraints.
    The following code example creates a DataRelation using two DataTable objects in a DataSet. Each DataTable contains a column named CustID, which serves as a link between the two DataTable objects. The example adds a single DataRelation to the Relations collection of the DataSet. The first argument in the example specifies the name of the DataRelation being created. The second argument sets the parent DataColumn and the third argument sets the child DataColumn.

    customerOrders.Relations.Add("CustOrders",
      customerOrders.Tables["Customers"].Columns["CustID"],
      customerOrders.Tables["Orders"].Columns["CustID"]);

    Tính toán chênh lệch giờ - phút - giây

    DateTime startTime = DateTime.Now;
    
     DateTime endTime = DateTime.Now.AddSeconds( 75 );
    
     TimeSpan span = endTime.Subtract ( startTime );
     Console.WriteLine( "Time Difference (seconds): " + span.Seconds );
     Console.WriteLine( "Time Difference (minutes): " + span.Minutes );
     Console.WriteLine( "Time Difference (hours): " + span.Hours );
     Console.WriteLine( "Time Difference (days): " + span.Days );

    Thứ Bảy, 19 tháng 7, 2014

    Cách mở cổng trong Win7

    1) Go to Start -> Control Panel -> System and Security -> Windows Firewall.
    2) On the left, click "Advanced settings".
    3) On the left again, click "Inbound Rules" (if the the port is supposed to be outbound, click "Outbound Rules").
    4) Go though the wizard.

    Thứ Tư, 16 tháng 7, 2014

    Cách hhai báo và sử dụng biến Dictionary với drop down list trong C#

    1. Tạo một trang aspx - 
    kéo control dropdownlist vào trang
    đặt ID của control là ddl 
     
    2. Nhấn phím F7 vào code behind,
    trong thủ tục page_load thêm đoạn code này vào:
    
    
     //int là kiểu giá trị cho key, string là kiểu giá trị áp dụng cho valúe
    
        Dictionary<int, string> objItems = new Dictionary<int, string>(); 
         
        objItems .Add(1, "Item 1");
        objItems .Add(2, "Item 2");
        objItems .Add(3, "Item 3");
        objItems .Add(4, "Item 4"); 
    
        ddl.DataSource = objItems ;
        ddl.DataTextField = "Value";
        ddl.DataValueField = "Key";
        ddl.DataBind();

    Thứ Hai, 14 tháng 7, 2014

    Lỗi xảy ra khi đếm sql

    Arithmetic overflow error converting expression to data type int.

    The Explanation:  The upper bounds of an int is a little over two billion: 2,147,483,647.  The count() function always returns an int.
    The Solution: Use count_big() instead, as it always returns a bigint data type, which has an upper bound of 9,223,372,036,854,775,807.  “select count_big(1) from MY_HUGE_TBL”

    Chủ Nhật, 6 tháng 7, 2014

    Tạo một mảng dùng nhiều phần tử để tách mảng sử dụng hàm Split trong C#

     var arraySplit={" ",",",";"};
    var Source="text,tex2;text3 text4";
    var NewArray = Source.Split(mang, StringSplitOptions.None);

    Thứ Tư, 2 tháng 7, 2014

    Câu lệnh lấy các phần tử trong một mảng linq C#

    // khai một mảng gồm 7 phần tử có giá trị tương ứng từ 0 tới 6
    int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };
     
    var myVariable = (from l in numbers // lấy các phần tử trong numbers
        order by l decending// và xắp xếp theo thứ tự giảm dần
       select l).take(3);// lấy 3 phần tử đầu tiên của mảng.