Thứ Sáu, 23 tháng 12, 2016

Compile SASS to CSS with Gulp

Install gulp-sass
npm install gulp-sass --save-dev

Create tasks:
var gulp = require('gulp');
var $ = require('gulp-load-plugins')({lazy: true});

gulp.task('clean-styles', function () {
    return gulp.src('build/styles', {read: false})
 .pipe($.clean());
});

gulp.task('styles',['clean-styles'], function () {
    return gulp.src('source/scss/**/*.scss')
 .pipe($.sass())
 .pipe(gulp.dest('build/styles'));
});

Making gulp file cleaner with gulp-load-plugins

gulpfile.js without gulp-load-plugins:
var gulp = require('gulp');
var clean = require('gulp-clean');
var concat = require('gulp-concat');
var babel = require('gulp-babel');
var uglify = require('gulp-uglify');
var jshint = require('gulp-jshint');
var jscs =  require('gulp-jscs');

gulp.task('clean', function () {
    return gulp.src('build', {read: false})
        .pipe(clean());
});

gulp.task('build', ['clean'], function() {
     return gulp.src('source/**/*.js')
  .pipe(jshint())
  .pipe(jshint.reporter('jshint-stylish'))
  .pipe(jshint.reporter('fail'))
    .pipe(babel({
        presets: 'es2015'
    }))
 .pipe(concat('all.js'))
 .pipe(uglify())
    .pipe(gulp.dest('build'));
})

gulp.task('jshint', function () {
    return gulp.src('source/**/*.js')
        .pipe(jscs())
  .pipe(jshint())
  .pipe(jshint.reporter('jshint-stylish'))
  .pipe(jshint.reporter('fail'));
});

gulp.task('default', ['build'])

Install gulp-load-plugins:
npm install --save-dev gulp-load-plugins

gulpfile.js with gulp-load-plugins:
var gulp = require('gulp');
var $ = require('gulp-load-plugins')({lazy: true});

gulp.task('clean', function () {
    return gulp.src('build', {read: false})
        .pipe($.clean());
});

gulp.task('build', ['clean'], function() {
     return gulp.src('source/**/*.js')
  .pipe($.jshint())
  .pipe($.jshint.reporter('jshint-stylish'))
  .pipe($.jshint.reporter('fail'))
    .pipe($.babel({
        presets: 'es2015'
    }))
 .pipe($.concat('all.js'))
 .pipe($.uglify())
    .pipe(gulp.dest('build'));
})

gulp.task('jshint', function () {
    return gulp.src('source/**/*.js')
        .pipe($.jscs())
  .pipe($.jshint())
  .pipe($.jshint.reporter('jshint-stylish'))
  .pipe($.jshint.reporter('fail'));
});

gulp.task('default', ['build'])

Thứ Năm, 22 tháng 12, 2016

Using JSHint with Gulp

Install jshint, gulp-jshint, jshint-stylish
npm install jshint gulp-jshint jshint-stylish --save-dev

Config javascript version in .jshintrc file:
{
  "esversion": 6
}

Define task in gulpfile.js:
var gulp = require('gulp');
var jshint = require('gulp-jshint');

gulp.task('jshint', function () {
    return gulp.src('source/**/*.js')
  .pipe(jshint())
  .pipe(jshint.reporter('jshint-stylish'))
  .pipe(jshint.reporter('fail'));
});

Chủ Nhật, 18 tháng 12, 2016

Gulp Basic

Install Gulp:
npm install gulp -g
npm install gulp --save-dev


Babel + Concat + Uglify with Gulp:
npm install gulp-babel --save-dev
npm install gulp-uglify --save-dev
npm install gulp-concat --save-dev
npm install gulp-clean --save-dev

Gulpfile.js:
var gulp = require('gulp');
var clean = require('gulp-clean');
var concat = require('gulp-concat');
var babel = require('gulp-babel');
var uglify = require('gulp-uglify'); 

gulp.task('clean', function () {
    return gulp.src('build', {read: false})
        .pipe(clean());
});

gulp.task('build', ['clean'], function() {
     return gulp.src('source/**/*.js')
    .pipe(babel({
        presets: 'es2015'
    }))
   .pipe(concat('all.js'))
   .pipe(uglify())
   .pipe(gulp.dest('build'));
})

gulp.task('default', ['build'])

Babel Basic

Install globally:
npm install babel-cli -g

Install locally
npm install babel-cli --save-dev

Install Babel Preset ES2015
npm install babel-preset-es2015 --save-dev

Transpile all files inside a specific folder:
babel [source-folder] --presets es2015 --out-dir [build-folder]

Transpile and bundle all files inside a specific folder:
babel [source] --presets es2015 --out-file [build/bundle.js]

Transpiling with watch option:
babel [source] --presets es2015 --out-file [build/bundle.js] -w

Configuration with .babelrc
{
    "presets": ["es2015"],
    "plugins": [],
    "sourceMaps": true
}

Bower Basic

Install Bower:
npm install bower -g

Create bower.json file:
bower init

Install package:
bower install [package_name]
bower install [package_name] --save
bower install [package_name] --save-dev

Install specific package:
bower install [package_name]#[version]

Configuration with .bowerrc
{
  "directory": "bower_components"
}

NPM Basic

Create package.json file:
npm init

Install package:
npm install [package_name] --save
npm install [package_name] --save-dev
npm install [package_name] -g

Install specific version:
npm install [package_name]@[version] --save
npm install [package_name]@[version] --save-dev
npm install [package_name]@[version] -g

Thứ Hai, 28 tháng 11, 2016

Route Constraints

https://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2#constraints
ConstraintDescriptionExample
alphaMatches uppercase or lowercase Latin alphabet characters (a-z, A-Z){x:alpha}
boolMatches a Boolean value.{x:bool}
datetimeMatches a DateTime value.{x:datetime}
decimalMatches a decimal value.{x:decimal}
doubleMatches a 64-bit floating-point value.{x:double}
floatMatches a 32-bit floating-point value.{x:float}
guidMatches a GUID value.{x:guid}
intMatches a 32-bit integer value.{x:int}
lengthMatches a string with the specified length or within a specified range of lengths.{x:length(6)}
{x:length(1,20)}
longMatches a 64-bit integer value.{x:long}
maxMatches an integer with a maximum value.{x:max(10)}
maxlengthMatches a string with a maximum length.{x:maxlength(10)}
minMatches an integer with a minimum value.{x:min(10)}
minlengthMatches a string with a minimum length.{x:minlength(10)}
rangeMatches an integer within a range of values.{x:range(10,50)}
regexMatches a regular expression.{x:regex(^\d{3}-\d{3}-\d{4}$)}

Chủ Nhật, 27 tháng 11, 2016

Thứ Bảy, 19 tháng 11, 2016

Enabling Windows Authentication in Katana

https://www.asp.net/aspnet/overview/owin-and-katana/enabling-windows-authentication-in-katana

using System.Net;

namespace Owin
{
    public static class WindowsAuthenticationExtensions
    {
        public static IAppBuilder UseWindowsAuthentication(this IAppBuilder app)
        {
            object value;
            if (app.Properties.TryGetValue("System.Net.HttpListener", out value))
            {
                var listener = value as HttpListener;
                if (listener != null)
                {
                    listener.AuthenticationSchemes =
                        AuthenticationSchemes.IntegratedWindowsAuthentication;
                }
            }

            return app;
        }
    }
}

Thứ Tư, 16 tháng 11, 2016

Regex pattern for comma separated list

<textarea ng-pattern="/^([^,]+)(,[^,]+)*$/i"></textarea>

Allow one comma at the end:

<textarea ng-pattern="/^([^,]+)(,[^,]+)*(,?)$/i"></textarea>

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

Configure TortoiseSVN to use Visual Studio 2015 for Diff Viewer

Settings -> Diff Viewer -> External -> paste the command as below:

C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe -diff %base %mine

or

C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\vsDiffMerge.exe /t %base %mine %bname %yname



Thứ Sáu, 30 tháng 9, 2016

T-SQL Cast datetime2 text to datetime

select cast(cast('2016-09-30 16:10:53.49876' as datetime2) as datetime)
-- result: 2016-09-30 16:10:53.500

Thứ Tư, 21 tháng 9, 2016

Compare 2 branches in TortoiseSVN

http://stackoverflow.com/questions/4675517/compare-files-between-two-branches-in-tortoisesvn

  1. Go to the repository browser (<right click>/TortoiseSVN/Repo-browser/<enter URL>).
  2. Open right click menu on branch B, select 'Mark for comparison'.
  3. Then open right click menu on branch A, select 'Compare URLs' or 'Show differences as unified diff'.

Thứ Sáu, 12 tháng 8, 2016

Calculating a selector's specificity

A selector's specificity is calculated as follows:
  • count the number of ID selectors in the selector (= a)
  • count the number of class selectors, attributes selectors, and pseudo-classes in the selector (= b)
  • count the number of type selectors and pseudo-elements in the selector (= c)
  • ignore the universal selector
Selectors inside the negation pseudo-class are counted like any other, but the negation itself does not count as a pseudo-class.
Concatenating the three numbers a-b-c (in a number system with a large base) gives the specificity.
Examples:
*               /* a=0 b=0 c=0 -> specificity =   0 */
LI              /* a=0 b=0 c=1 -> specificity =   1 */
UL LI           /* a=0 b=0 c=2 -> specificity =   2 */
UL OL+LI        /* a=0 b=0 c=3 -> specificity =   3 */
H1 + *[REL=up]  /* a=0 b=1 c=1 -> specificity =  11 */
UL OL LI.red    /* a=0 b=1 c=3 -> specificity =  13 */
LI.red.level    /* a=0 b=2 c=1 -> specificity =  21 */
#x34y           /* a=1 b=0 c=0 -> specificity = 100 */
#s12:not(FOO)   /* a=1 b=0 c=1 -> specificity = 101 */
Note: Repeated occurrances of the same simple selector are allowed and do increase specificity.
Note: the specificity of the styles specified in an HTML style attribute is described in CSS 2.1. [CSS21].

Thứ Sáu, 1 tháng 4, 2016

Sử dụng Cursor trong SQL Server

DECLARE @tblStudent table(Name varchar(50), Age int);
insert into @tblStudent(Name,Age) values('Name 1',1)
insert into @tblStudent(Name,Age) values('Name 2',2)

DECLARE @name VARCHAR(50) 
DECLARE @age int

DECLARE myCursor CURSOR FOR  
SELECT Name, Age
FROM @tblStudent

OPEN myCursor   
FETCH NEXT FROM myCursor INTO @name,@age  

WHILE @@FETCH_STATUS = 0   
BEGIN   
       print(@name + ' - ' + cast(@age as varchar))
       FETCH NEXT FROM myCursor INTO @name ,@age 
END   

CLOSE myCursor   
DEALLOCATE myCursor

Phân trang trong MS SQL Server 2012

declare @currPage int = 2,-- trang hiện tại
@recodperpage int = 20;-- số dòng trên 1 trang

select *,COUNT(*) OVER () as TotalRecords from [TenBang]
order by [TenCot]
OFFSET (@currPage - 1)*@recodperpage ROWS
FETCH NEXT @recodperpage ROWS ONLY

Phân trang theo cách truyền thống sử dụng ROW_NUMBER()

Thứ Sáu, 26 tháng 2, 2016

char and varchar (Transact-SQL)

https://msdn.microsoft.com/en-us/library/ms176089.aspx

Note:

char là kiểu fixed length nên nếu dùng không đúng trong 1 số trường hợp sẽ gây ra code chạy không như mong đợi.

Ví dụ khai báo biến kiểu char(20) sau đó gắn giá trị 10 ký tự thì 10 ký tự còn lại sẽ là khoảng trắng.

Thứ Hai, 22 tháng 2, 2016

Đoạn code Format Number ( ngắt theo ngàn, triệu ... ) bằng Javascript

Viết lại từ phiên bản C# và xử lý thêm trường hợp số âm
http://www.hanhtranglaptrinh.com/2011/12/oan-code-format-number-ngat-theo-ngan.html


var insertAt = function (originalStr, index, string) {
     return originalStr.substr(0, index) + string + originalStr.substr(index);
}
var formatNumber = function (number) {
    var rs;
    var part = number.replace("-", "").split('.');
    var len = part[0].length;
    var i = parseInt(len / 3);
    if (i > 0) {
        var pos = len % 3;
        if (pos > 0) {
            part[0] = insertAt(part[0],pos, ",");
            pos += 4;
        }
        else {
            pos = 3;
        }

        for (var k = 1; k < i; k++) {
            part[0] = insertAt(part[0],pos, ",");
            pos += 4;
        }

    }
    if (number.indexOf(".") >= 0) {
        rs = part[0] + "." + part[1];
    }
    else
        rs = part[0];

    if (number.indexOf("-") == 0)
        rs = "-" + rs;

    return rs;
}

Thứ Năm, 14 tháng 1, 2016

Drop and Re-Create All Foreign Key Constraints in SQL Server

Reference: https://www.mssqltips.com/sqlservertip/3347/drop-and-recreate-all-foreign-key-constraints-in-sql-server/

CREATE TABLE #x -- feel free to use a permanent table
(
  drop_script NVARCHAR(MAX),
  create_script NVARCHAR(MAX)
);
  
DECLARE @drop   NVARCHAR(MAX) = N'',
        @create NVARCHAR(MAX) = N'';

-- drop is easy, just build a simple concatenated list from sys.foreign_keys:
SELECT @drop += N'
ALTER TABLE ' + QUOTENAME(cs.name) + '.' + QUOTENAME(ct.name) 
    + ' DROP CONSTRAINT ' + QUOTENAME(fk.name) + ';'
FROM sys.foreign_keys AS fk
INNER JOIN sys.tables AS ct
  ON fk.parent_object_id = ct.[object_id]
INNER JOIN sys.schemas AS cs 
  ON ct.[schema_id] = cs.[schema_id];

INSERT #x(drop_script) SELECT @drop;

-- create is a little more complex. We need to generate the list of 
-- columns on both sides of the constraint, even though in most cases
-- there is only one column.
SELECT @create += N'
ALTER TABLE ' 
   + QUOTENAME(cs.name) + '.' + QUOTENAME(ct.name) 
   + ' ADD CONSTRAINT ' + QUOTENAME(fk.name) 
   + ' FOREIGN KEY (' + STUFF((SELECT ',' + QUOTENAME(c.name)
   -- get all the columns in the constraint table
    FROM sys.columns AS c 
    INNER JOIN sys.foreign_key_columns AS fkc 
    ON fkc.parent_column_id = c.column_id
    AND fkc.parent_object_id = c.[object_id]
    WHERE fkc.constraint_object_id = fk.[object_id]
    ORDER BY fkc.constraint_column_id 
    FOR XML PATH(N''), TYPE).value(N'.[1]', N'nvarchar(max)'), 1, 1, N'')
  + ') REFERENCES ' + QUOTENAME(rs.name) + '.' + QUOTENAME(rt.name)
  + '(' + STUFF((SELECT ',' + QUOTENAME(c.name)
   -- get all the referenced columns
    FROM sys.columns AS c 
    INNER JOIN sys.foreign_key_columns AS fkc 
    ON fkc.referenced_column_id = c.column_id
    AND fkc.referenced_object_id = c.[object_id]
    WHERE fkc.constraint_object_id = fk.[object_id]
    ORDER BY fkc.constraint_column_id 
    FOR XML PATH(N''), TYPE).value(N'.[1]', N'nvarchar(max)'), 1, 1, N'') + ');'
FROM sys.foreign_keys AS fk
INNER JOIN sys.tables AS rt -- referenced table
  ON fk.referenced_object_id = rt.[object_id]
INNER JOIN sys.schemas AS rs 
  ON rt.[schema_id] = rs.[schema_id]
INNER JOIN sys.tables AS ct -- constraint table
  ON fk.parent_object_id = ct.[object_id]
INNER JOIN sys.schemas AS cs 
  ON ct.[schema_id] = cs.[schema_id]
WHERE rt.is_ms_shipped = 0 AND ct.is_ms_shipped = 0;

UPDATE #x SET create_script = @create;

PRINT @drop;
PRINT @create;

/*
EXEC sp_executesql @drop
-- clear out data etc. here
EXEC sp_executesql @create;
*/