Wednesday, May 16, 2018
Simple Image Manipulation - Brightness
Last time I played with played with Pixels - Color Effect with HTML5 and JS

For this short post, let's go back to basics. Let us try to adjust an image's brightness by trying to add a value between -255 (darkest ) to 255 (lightest) to an image pixel data.


NOTE - an image can be loaded to an ImageData, The data attribute of this object contains a Uint8ClampedArray representing a one-dimensional array containing the data in the RGBA order, with integer values between 0 and 255 (included).

below is a short sample on how to read the RGB data parts.
  RED = imageData[c ] 
GREEN = imageData[c+1] 
BLUE = imageData[c+2] 

Posted On Wednesday, May 16, 2018 6:34 PM | Comments (2)
Friday, May 11, 2018
Playing with Pixels - Color Effect with HTML5 and JS

I've been playing with HTML5 and JS when I feel bored, and I love taking pictures. 
So Tried putting them together in this mini project <3


Next Step look for more interesting color effects. 

The RGB Matrix was generated from Excel, I just multiplied 0-255 to some random numbers and converted them into an Array. 

Posted On Friday, May 11, 2018 2:54 PM | Comments (2)
Friday, November 4, 2016
SQL Server Statistics Parser


Working as a Data Engineer, one of my key role is to do Query and Server Optimizations, and one of the weird things that we will be seeing is this Nerdy Data


Of course this does not automatically show up unless you turn this 2 ON



Whole Query Sample



The data is pretty readable and understandable but still can be improved, Hopefully soon by Microsoft via SSMS(SQL Server Management Studio).


Luckily  Richie Rump (  created a site - that let’s us paste our data and parse them into this,


Now if we want to compare(before/after) stats from queries that we are optimizing improvements should be more READABLE.


And if you are wondering if the site collects that Data including the table names?

NO, the site does not collect anything, and the author is kind enough to share his source code on GITHUB incase you want to setup your own under your webserver

Posted On Friday, November 4, 2016 10:38 PM | Comments (0)
Tuesday, September 13, 2016
Semaphores for better distribution of work items across threads


As developers we will often find ourselves doing loops/iterations to process hundreds, thousands or even millions of  items, e.g. parsing files, screen scraping sites, doing complex computations on multiple rows etc.

To process these types of jobs, we can take a look on some supermarket lines, where we have 1 long line with several counters catering to 1 customer at a time, when a cashier is done with the current customer, one customer will be called from the line. 

On the programming world we have what we call threading and semaphores and luckily .Net Offers built-in classes for these concepts Smile .

Threads allows us to do calculations on a separate thread while leaving the original/main thread busy on the GUI.

Sempaphores allows us to process limited number of items within our list(collection of jobs that needs to be processed) by flagging them when a thread is already available


Below is the resulting output from the code below



Text files will be generated on the bin directory



Below is a short code that connects to multiple sites and saves the HTML code that is returned.

using System;
using System.Net;
using System.Threading;

namespace Semaphores
    class Program
        private static Semaphore sem;
        private static int workCount;
        private static int totalJobs;
        private static int maxJobs = 3;
        public static void Main()
            string[] webSites= new string[100];
            sem = new Semaphore(0, maxJobs);

            webSites[0] = "";
            webSites[1] = "";
            webSites[1] = "";
            webSites[2] = "";
            webSites[3] = "";
            webSites[4] = "";
            webSites[5] = "";
            webSites[6] = "";
            webSites[7] = "";
            webSites[8] = "";
            webSites[9] = "";
            webSites[10] = "";

            totalJobs = 0;  

            //send all works to the queue
            for (int i = 0; i <= 10; i++)
                Thread thread = new Thread(new ParameterizedThreadStart(Worker));

            //Release initial semaphores based on maxJobs

        private delegate void ProcessDelegate(string site);

        private static void Worker(object site)
            Console.WriteLine("{0} added to queue and waits for a signal from the semaphore.",  site.ToString());

            //waits for a go signal from the semaphore
            //Start to work

        private static void webWorker(string site)
            WebClient wc = new WebClient();
            string responseData = "";
            string outFile = "";
                Console.WriteLine("Started to connect to " + site.ToString());

                //Start to connect to website and get HTML Contents
                responseData = wc.DownloadString(site);
                //Clean up strings to generate a filename for the output file
                outFile = site.Replace("http://", "");
                outFile = outFile.Replace("https://", "");
                outFile = outFile.Replace("/", "");

                //Save Html Content
                System.IO.StreamWriter sw = new System.IO.StreamWriter(outFile + ".txt",true);
                workCount += 1;

                //Delegate to count jobs being processed
                ProcessDelegate PD = countItems;
            catch (Exception)

        private static void countItems(string  site)
            totalJobs += 1;

            Console.WriteLine("Last Job Processed ==>  " + site);
            Console.WriteLine("Total Jobs Processed ==>  " + totalJobs.ToString());
            if (workCount >= 11)
                Console.WriteLine("Done with all the jobs . . . . ");



Please feel free to commend and suggest . . .

Posted On Tuesday, September 13, 2016 7:20 PM | Comments (2)
Monday, July 18, 2016
AngularJS2 on ASP.Net Core using TypeScript Part 3 - Attribute Directives


Previously we started creating our seed project then we created our first AngularJS2 app, on this post we will try to play with AngularJs2’s Attribute Directives.

Basically, Attribute Directives allows us to change the appearance or behavior of a DOM Element, such us changing colors of DIVS when our mouse enters or exits, or alter the behavior of a DOM element when clicking them.


For this Post, We will use the current state of the project we used on our last post, you can go back to my previous posts if you still haven't done so.

AngularJS2 on ASP.Net Core using TypeScript Part 1
AngularJS2 on ASP.Net Core using TypeScript Part 2

Target Output



Table of Procedures

1. Update main.scss
2. Create app.component.html
3. Create highlight.directive.ts
4. Update app.component.ts
5. Test our Application



1. Update main.scss

First, We need to add a base class for our boxes.

$font-stack: Arial, Helvetica, sans-serif;
$primary-color: #336699;

h1 {
  font: $font-size $font-stack;
  color: $primary-color;   

body {
      margin: $margin;

.boxes {
    display: inline-block;
    position: relative;
    float: left;
    margin: 10px;   
    width: 100px;
    height: 100px;
    text-align: center;
    vertical-align: middle;
    line-height: 100px; 
    border: 1px #000000 solid;


2. Create app.component.html

On our last project we hardcoded our HTML code on our component’s template property,


For this project we will use an external html file as a template, first create a HTML File under wwwrooot\app\, let’s name this file app.component.html.

Copy and paste the codes below, for now take note of [myHighlight]="color" and [defaultColor]="'violet'". We will get these values from our components once we created our custom Directive.

<h1>Welcome to the world of Directives</h1><br />
    <input type="radio" name="colors" (click)="color='lightgreen'">Green
    <input type="radio" name="colors" (click)="color='yellow'">Yellow
    <input type="radio" name="colors" (click)="color='cyan'">Cyan

<div class="boxes" [myHighlight]="color">Apple</div>
<div class="boxes" [myHighlight]="color">Bat</div>
<div class="boxes" [myHighlight]="color" [defaultColor]="'violet'">Cat</div>
<div class="boxes" [myHighlight]="color" [defaultColor]="'violet'">Dog</div>
<div class="boxes" [myHighlight]="color" [defaultColor]="'violet'">Elephant</div>
<div class="boxes" [myHighlight]="color" [defaultColor]="'violet'">Frog</div>
<div class="boxes" [myHighlight]="color" [defaultColor]="'violet'">Girrafe</div>
<div class="boxes" [myHighlight]="color" [defaultColor]="'violet'">Hippopotamus</div>


3. Create highlight.directive.ts

Create a new TypeScript file under our projects APP Folder(not the wwwroot/app folder) and copy and paste the complete codes at the end of this step/procedure.

What’s note worthy here is the @Directive decorator, this will locate all elements on our template HTML that has the [myHighlight] attribute and will inject our Directives capabilities.

We will also have @Hostlistener’s which will allow us to catch the MouseEnter and MouseLeave and insert what we want our Directives to do, on this case we will change the style.backgroundColor of our DIVS.

import { Directive, ElementRef, HostListener, Input } from '@angular/core';

    selector: '[myHighlight]'

export class HighlightDirective {
    private _defaultColor = 'red';
    private el: HTMLElement;

    constructor(el: ElementRef) { this.el = el.nativeElement; }

    @Input() set defaultColor(colorName: string) {
        this._defaultColor = colorName || this._defaultColor;

    @Input('myHighlight') highlightColor: string;

    @HostListener('mouseenter') onMouseEnter() {
        this.highlight(this.highlightColor || this._defaultColor);
    @HostListener('mouseleave') onMouseLeave() {

    private highlight(color: string) { = color;

4. Update app.component.ts

Now we need to update our app.component.ts so we could use the HighlightDirective we created on step no 3. what’s note worthy here is we change the template:  to templateUrl and we told our app.component to use our newly created [HighlightDirective]

import { Component } from '@angular/core';
import { HighlightDirective } from './highlight.directive';

    selector: 'my-app',   
    templateUrl: 'app/app.component.html',
    directives: [HighlightDirective]
export class AppComponent {
    constructor() {
        var test = null;


5. Now you can press F5 to run our application.

If no option is selected it will apply our default color indicated on our Directive

private _defaultColor = 'red';




For the boxes that has the [defaultColor] Attribute, the color indicated on the attribute will be used.




If the user selected a Color, our directive should be able to pick that up and apply it to our DIVs




Please feel fee to comment . . .

Posted On Monday, July 18, 2016 11:25 PM | Comments (4)
Friday, June 24, 2016
AngularJS2 on ASP.Net Core using TypeScript Part 1 - Preparing the Seed Project


Starting to play with technologies that are not yet released is a pain in the a#$%. First, because big changes can occur thus breaking our proof of concept projects, Second, looking for a good resource online is not as rich when looking for resources for products that are already released, Third, the list of pains goes on …

To start the series we will begin by preparing what we need. On Part 2 of  the series, We will start creating our first AngularJS2 on ASP.Net Core using TypeScript

Updates :

July 2, 2016

ASP.NET Core 1.0 is now released, so I updated the VS and Tools update links
Added an item to update TypeScript Manually

Table of Contents

1. Upgrade your Visual Studio 2015 to Update 3 (released June 27, 2016)
2. Download and Install VS Tools Update
3. Download, Install and Configure latest NodeJS Binaries
4. Download, Install and Configure latest GIT Binaries
5. Download and Install latest Web Compiler Extension for VS 2015
6. Download and Install TypeScript for Visual Studio 2015
7. Update TypeScript



1. Upgrade your Visual Studio 2015 to Update 2

- download Link

2. Download and Install VS Tools Update

- download link

3. Download, Install and Configure latest NodeJS Binaries

- Configure Visual Studio to use the newly installed NodeJS instead of the depracated NPM installed with VS. (Uncheck .\node_modules\bin and add a new item “C:\program files\nodejs\”)


- If you are using a proxy server configure NodeJS to use your companies proxy

Setup Proxy
npm config set proxy
npm config set https-proxy

Remove Proxy
npm config rm proxy
npm config rm https-proxy



4. Download, Install and Configure latest GIT Binaries

- Configure Visual Studio to use the newly installed GIT instead of the depracated NPM installed with VS. (Uncheck $(VSINSTALLDIR)\Web\External\git and add a new item “C:\Program Files\Git\bin”)


- If you are using a proxy server configure GIT to use your companies proxy

Setup Proxy
git config --global http.proxy


Remove Proxy
git config --global --unset http.proxy


5. Download and Install latest Web Compiler Extension for VS 2015


6. Download and Install TypeScript for Visual Studio 2015

7. Download latest typescriptService.js file from link below and replace the file on “C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\TypeScript”



NOTE: It is a good idea to have the latest GIT and NODEJS binaries, because Visual Studio 2015 is shipped with an older GIT and NodeJS binaries, you might encounter some errors if you are not going to have the latest versions

Posted On Friday, June 24, 2016 5:46 PM | Comments (5)
Friday, June 17, 2016
AngularJS2 on ASP.Net Core using TypeScript Part 2 - Our First App


On Part 1 we started preparing the stage. If you still haven't done so, please visit

On this Part of the series we will start building our first AngularJS2 on ASP.Net Core using Typescript. On Part 3 we will start coding our own Directives (component that can help us change the appearance or behavior of an HTML elements)


Original Article is from AngularIO Site - 
I wrote this blog entry for those who want to begin doing Angular using ASP.NET Core 1.0 as a backend.


July 2, 2016 - ASP.NET CORE is now RTM and AngularJS2 RC4 is released, Updated some scripts below

Procedures Summary

  • Create a new ASP.NET Core Web Application
  • Add package.json (package.json)
  • Add a Gulp file
  • Add a typings.json file
  • Install typings
  • Add a tsconfig.json file – This will contain our TypeScript configurations
  • Create an app folder that will house all of our AngularJS2 codes
  • Create the following files within app folder
  • Create systemjs.config.js
  • Create a css folder and add a new scss file with the following code
  • Configure compilerconfig.json (automatically generated after compiling the scss file) to send css files to wwwroot/css folder
  • Create index.html
  • Edit startup.cs
  • Configure the project to use index.html as a startup page



1. Create a new ASP.NET Core Web Application

- File new project


- Select Web API


2. Add package.json (package.json)

- Open Solutions Explorer (CTRL + W then S)

- Select the your project name within src folder


- Add a new item (CTRL + SHIFT + A)

- On the upper right side of the screen type package, this will filter the main window


Update the contents of the file with the following code and save

    "version": "1.0.0",
    "name": "",
  "private": true,
  "dependencies": {
    "@angular/common": "2.0.0-rc.4",
    "@angular/compiler": "2.0.0-rc.4",
    "@angular/core": "2.0.0-rc.4",
    "@angular/forms": "0.2.0",
    "@angular/http": "2.0.0-rc.4",
    "@angular/platform-browser": "2.0.0-rc.4",
    "@angular/platform-browser-dynamic": "2.0.0-rc.4",
    "@angular/router": "3.0.0-beta.1",
    "@angular/router-deprecated": "2.0.0-rc.2",
    "@angular/upgrade": "2.0.0-rc.4",
    "systemjs": "^0.19.31",
    "core-js": "^2.4.0",
    "reflect-metadata": "^0.1.3",
    "rxjs": "^5.0.0-beta.9",
    "symbol-observable": "1.0.1",
    "zone.js": "0.6.12",
    "angular2-in-memory-web-api": "^0.0.14",
    "bootstrap": "^3.3.6"
  "devDependencies": {
    "concurrently": "^2.1.0",   
    "gulp": "^3.9.1",
    "rimraf": "^2.5.2"


After saving package.json, Visual Studio will use NPM to download the files required by the dependencies and devDependencies you specified.


On your local drive, you will have a copy of the different items you included in your package.json file



3.  Add a Gulp file


- Update the contents of the file with the following code and save

var gulp = require('gulp');
var rimraf = require('rimraf');

gulp.task('default', function () {
    // place code for your default task here

gulp.task('clean:lib', function (cb) {
    return rimraf('wwwroot/lib/', cb);

gulp.task('copy:lib', function () {
    return gulp.src('node_modules/**/*')

- right click on gulp.js and select Task Runner


- click refresh(upper left corner of the task runner explorer )



- right click on “copy:lib” then select RUN

- After the task runner finishes you will be able to see that the npm files previously downloaded/copied from step 2 will also be copied to wwwroot folder


4. Add a typings.json file


- Update the contents of the file with the following code and save

  "globalDependencies": {
    "core-js": "registry:dt/core-js#0.0.0+20160602141332",
    "jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
    "node": "registry:dt/node#6.0.0+20160621231320"

5. Install typings

- Open command prompt

- go to the path where your typings.json file is located

- use the following command to install the items we added in typings.json

typings install

- use the following command if you are behind a proxy

typings install –-proxy

- you will now have a typings folder containing the objects we included on our typings.json file


6. Add a tsconfig.json file – This will contain our TypeScript configurations


- Update the contents of the file with the following code and save

  "compileOnSave": true,
  "compilerOptions": {
    "target": "es5",
    "module": "system",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false,
    "outDir": "wwwroot/app/"
  "exclude": [

6. Create an app folder that will house all of our AngularJS2 codes


7. Create the following files within app folder


import { Component } from '@angular/core';
    selector: 'my-app',
    template: '<h1>My First Angular 2 App</h1>'
export class AppComponent { }



import { bootstrap }    from '@angular/platform-browser-dynamic';
import { AppComponent } from './app.component';


- js files will be generated under wwwroot\app folder as a result of our tsconfig.json after saving the ts files we created above


8. Create systemjs.config.js inside wwwroot folder

- Update the contents of the file with the following code and save

* System configuration for Angular 2 samples
* Adjust as necessary for your application needs.
(function (global) {
    // map tells the System loader where to look for things
    var map = {
        'app': 'app', // 'dist',
        '@angular': 'lib/@angular',
        'angular2-in-memory-web-api': 'lib/angular2-in-memory-web-api',
        'rxjs': 'lib/rxjs',
    // packages tells the System loader how to load when no filename and/or no extension
    var packages = {
        'app': { main: 'main.js', defaultExtension: 'js' },
        'rxjs': { defaultExtension: 'js' },
        'angular2-in-memory-web-api': { main: 'index.js', defaultExtension: 'js' },
        'symbol-observable': { main: 'index.js', defaultExtension: 'js' }
    var ngPackageNames = [
    // Individual files (~300 requests):
    function packIndex(pkgName) {
        packages['@angular/' + pkgName] = { main: 'index.js', defaultExtension: 'js' };
    // Bundled (~40 requests):
    function packUmd(pkgName) {
        packages['@angular/' + pkgName] = { main: '/bundles/' + pkgName + '.umd.js', defaultExtension: 'js' };
    // Most environments should use UMD; some (Karma) need the individual index files
    var setPackageConfig = System.packageWithIndex ? packIndex : packUmd;
    // Add package entries for angular packages
    var config = {
        map: map,
        packages: packages

9. Create a css folder udner the project folder and add a new scss file with the following code


$font-stack: Arial, Helvetica, sans-serif;
$primary-color: #336699;

h1 {
  font: $font-size $font-stack;
  color: $primary-color;   

body {
      margin: $margin;

- right click on main.scss and select Web Compiler then Re-compile file, This will generate main.css


main.css and main.min.css will be generated automatically


10. Configure compilerconfig.json (automatically generated after compiling the scss file) to send css files to wwwroot/css folder

    "outputFile": "wwwroot/css/main.css",
    "inputFile": "css/main.scss"

-css files should now be automatically generated under wwwroot/css/


11. Create index.html Inside wwwroot folder

    <title>Angular 2 QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="css\main.css">
    <!-- 1. Load libraries -->
    <!-- Polyfill(s) for older browsers -->
    <script src="lib/core-js/client/shim.min.js"></script>
    <script src="lib/zone.js/dist/zone.js"></script>
    <script src="lib/reflect-metadata/Reflect.js"></script>
    <script src="lib/systemjs/dist/system.src.js"></script>
    <!-- 2. Configure SystemJS -->
    <script src="systemjs.config.js"></script>
      System.import('app').catch(function(err){ console.error(err); });
<!-- 3. Display the application -->

12. Edit startup.cs – add the code below (BOLD)

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)

- click the word UseStaticFiles() and press CTRL + .  and select “Add package Microsoft.AspNetCore.StaticFiles 1.0.0


13. Configure the project to use index.html as a startup page

- Open Project>Properties and open Debug Tab and set Launch URL: index.html


14. Run the Project by pressing F5



Additional References/Notes

package.json -
gulp.js/grunt/gulp/webpack -,grunt,gulp,webpack
rimraf – This will traverse a folder and delete objects, similar to linux’ rm –rf command
taskrunner – task runners help developers to automate tasks by using different tools like GULP, BOWER
package.json - A package.json file contains meta data about your app or module. Most importantly, it includes the list of dependencies to install from npm when running npm install


Please feel fee to comment . . .

Posted On Friday, June 17, 2016 7:01 PM | Comments (4)
Thursday, May 19, 2016
Semaphores–queuing with multiple workers–C#

One of the challenges of working with queues is how to properly and neatly process each item using multiple workers, luckily on .Net we have Semaphores. “In computer science, a semaphore is a variable or abstract data type that is used for controlling access, by multiple processes, to a common resource in a concurrent system such as a multiprogramming operating system.”

Below is a simple program that demonstrate the use of semaphore with a parametized number of threads and HttpRequest as Payload.


private const int maxThreads = 10;
private Semaphore semaphore = new Semaphore(maxThreads, maxThreads);
private Queue queue = new Queue();
private void button1_Click(object sender, EventArgs e)
     while (queue.Count >=1)
        var item = queue.Dequeue();
        ThreadPool.QueueUserWorkItem(ProcessCurrentItem, item);
    int count = 0;
    while (count < maxThreads)

async void ProcessCurrentItem(object item)
           string responseData = "";
           HttpClient hc = new HttpClient();

           hc.DefaultRequestHeaders.Add("host", "");
          hc.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36");
           hc.DefaultRequestHeaders.Add("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
           hc.DefaultRequestHeaders.Add("scheme", "https");
           hc.DefaultRequestHeaders.Add("method", "GET");

           //Get the headers associated with the request.

               HttpResponseMessage response = await hc.GetAsync("" + item.ToString());
               responseData = response.ToString(); 



           catch (Exception ex)


private void addTestData()

Posted On Thursday, May 19, 2016 9:20 PM | Comments (0)
Monday, February 29, 2016
Lock Pages In Memory

SQL Server together with other RDBMS, are the most memory consuming applications on our servers, and this is because, RDBMs usually cache objects into the memory to take advantage of the speed that physical memory offers.

Sadly when windows feels that its physical memory is currently not enough for a driver and/or processes that is requesting some resources, it is forced to trim some of currently running application’s memory working set. Now that is bad news for SQL Server because windows will be forced to push the objects from the memory to the servers’ paging file. You can verify if windows is doing this to your SQL Server by investigating SQL Server Logs for this entries

A significant part of sql server process memory has been paged out.This may result in a performance degradation. Duration: 0 seconds. Working set (KB): 1086400, committed (KB), memory Utilization: 50%.

Currently there are 2 settings that we can play with to avoid or at least alleviate this situation

1. Properly set SQL Servers’ Max Memory settings, by setting aside enough memory for the OS and other running Processes like Antivirus and Server Monitoring Software.

2. Enable SQL Server Locked Page in Memory (LPIM)

NOTE: Enabling LPIM without fully Understanding how SQL Memory Works and without knowing how your DB Server Behaves specially if it’s in a Virtual Environment might give you negative effects.

For this Post we will be focusing on LPIM. When using LPIM Windows cannot simply touch the memory space used by SQL Servers’ Buffer Pool, it is locked and cannot be paged. SQL Server does this by using Address Windowing Extensions (AWE).

When LPIM is enabled you cannot simply view how much really SQL Server is using by viewing Task Manager. As you can see on the screen shot below, SQLSERVR.EXE is only using 49, 536Kb


You can however use RamMap (A free RAM tool from Sysinternals: To view how much memory AWE is using.



Or you can also use sys.dm_os_process_memory SQL Server Dynamic Management Views (DMV).


How to Enable LPIM

Use Windows Group Policy tool (gpedit.msc) to enable this policy for the account used by SQL Server. You must be a system administrator to change this policy.

1. On the Start menu, click Run. In the Open box, type gpedit.msc.

2. On the Local Group Policy Editor console, expand Computer Configuration, and then expand Windows Settings.

3. Expand Security Settings, and then expand Local Policies.

4. Select the User Rights Assignment folder.

The policies will be displayed in the details pane.

5. In the pane, double-click Lock pages in memory.

6. In the Local Security Setting – Lock pages in memory dialog box, click Add User or Group.

7. In the Select Users, Service Accounts, or Groups dialog box, add an account with privileges to run sqlservr.exe.

8. Log out and then log back in for this change to take effect.

Note about SQL Server 2008 R2 Standard Edition (64-bit): Microsoft SQL Server 2008 R2 Standard Edition (64-bit, all versions RTM and later) also requires trace flag 845 to be added as a startup parameter so that SQL Server can use locked pages for the Buffer Pool when the SQL Server service account is granted the Lock Pages in Memory security privilege

Note about SQL Server 2012 Standard Edition (64-bit): Microsoft SQL Server 2012 Standard Edition (64-bit) does not require you to enable any trace flag to allow SQL Server use locked pages for the Buffer pool when the SQL Server service account is granted the Lock Pages in Memory security privilege.


How to determine if LPIM is enabled

Option 1 (Tested SQL 2005 )

DECLARE @LockPagesInMemory VARCHAR(255);

SET @LockPagesInMemory = 'UNKNOWN';



[output] NVARCHAR(255) NULL


IF (SELECT value_in_use

FROM sys.configurations c

WHERE = 'xp_cmdshell'

) = 1



EXEC xp_cmdshell 'WHOAMI /PRIV';



WHERE [output] LIKE 'SeLockMemoryPrivilege%'


SET @LockPagesInMemory = 'ENABLED';


SET @LockPagesInMemory = 'DISABLED';


SELECT LockPagesInMemoryEnabled = @LockPagesInMemory;

Option 2 (Tested SQL 2008)

select osn.node_id,




from sys.dm_os_memory_nodes omn

inner join sys.dm_os_nodes osn on (omn.memory_node_id = osn.memory_node_id)

where osn.node_state_desc <> 'ONLINE DAC'

NOTE: A non zero value for locked pages allocation means Locked pages in memory is enabled

Option 3 (TestedSQL 2008)



(locked_page_allocations_kb/1024 )Locked_pages_used_Sqlserver_MB,

(total_virtual_address_space_kb/1024 )Total_VAS_in_MB,



from sys. dm_os_process_memory

NOTE: A non zero Locked_pages_allocation_KB means Locked pages in memory is enabled.

Option 4

Using Exec xp

exec xp_readerrorlog 0, 1, 'locked pages'

exec xp_readerrorlog 0, 1, 'lock pages in memory'

Technical References/Further Reading:

Great SQL Server Debates: Lock Pages in Memory

How to reduce paging of buffer pool memory in the 64-bit version of SQL Server

Support for Locked Pages on SQL Server Standard Edition (64-bit) systems

How to enable the "locked pages" feature in SQL Server 2012

Posted On Monday, February 29, 2016 5:22 PM | Comments (0)
Friday, January 29, 2016
SQL Server 2016 Dynamic Data Masking (DDM)
SQL Server 2016 Dynamic Data Masking
Posted On Friday, January 29, 2016 11:38 PM | Comments (0)
Tag Cloud