JSFiddles created for my own learning and reference:
On Closures
http://jsfiddle.net/yaraj/qfuf3L6n/3/
Prototypal inheritence
http://jsfiddle.net/yaraj/c68rp5fd/1/
Tuesday, May 19, 2015
Sunday, May 17, 2015
Simple steps for creating tasks in Gulp task runner for your SPA application using Visual Studio
First from within Visual Studio, go to Extensions and Updates and install the following 3 nuget packages:
Then in your solution add a package.json file if not already exists. One way to do it is simply create one using the command prompt by going to your solution root directory as
npm init --yes
and hit enter for defaults. Now include this file in your solution from within Visual Studio, so Node can use this.
Next, create a file in your Visual Studio solution called gulpfile.js
Create your gulp tasks in gulpfile.js like below
var gulp = require('gulp');
var concat = require('gulp-concat');
var angularFileSort = require('gulp-angular-filesort');
var strip = require('gulp-strip-line');
var templateCache = require('gulp-angular-templatecache');
gulp.task("buildMenuTemplateCache", function(){
return gulp
.src(["./ext-modules/menu/**/*.html"])
.pipe(templateCache({
root : "./ext-modules/menu/",
module: "menu"
}))
.pipe( gulp.dest("./ext-modules/menu/"));
});
gulp.task("buildJS", function(){
return gulp
.src(["./ext-modules/**/*.js"]), //specify source
.pipe(angularFileSort()), //sorts js files in same folder so module comes first
.pipe(strip(['use strict'])), //removes use strict
.pipe(concat('framework.js')), //concatenate all files into single file
.pipe(dest('./dist/')); //specify destination
});
gulp.task("buildCSS", function(){
return gulp.src(),
.pipe(),
.pipe();
});
The above file is going to run in Node and not on the browser. So we need to install each of the required packages locally in the project using --save-dev flag like so:
npm install --save-dev gulp
Now if we look in our package.json file, we should see all our devDependencies listed in the file.
To run each individual task in gulpfile.js from Visual Studio, just right click the file and run the task. Doing so will produce the output of the task. We can also run the tasks using Task Runner Explorer from View->Other Windows menu item.
Finally, include the output file produced by the task runner in the distribution folder using "Show all files' in the solution. Then we need to import just this one single js file in our index.html file for all the javascript files! Similarly include a single .CSS file in index.html.
References:
http://www.pluralsight.com/training/player?author=mark-zamoyta&name=building-spa-framework-angularjs-m7&mode=live&clip=8&course=building-spa-framework-angularjs
http://www.toptal.com/nodejs/an-introduction-to-automation-with-gulp
- GruntWatcher (works with Gulp too!)
- Package Intellisense ( helps with intellisense in npm)
- Task Runner Explorer (helps run Gulp)
Then in your solution add a package.json file if not already exists. One way to do it is simply create one using the command prompt by going to your solution root directory as
npm init --yes
and hit enter for defaults. Now include this file in your solution from within Visual Studio, so Node can use this.
Next, create a file in your Visual Studio solution called gulpfile.js
Create your gulp tasks in gulpfile.js like below
var gulp = require('gulp');
var concat = require('gulp-concat');
var angularFileSort = require('gulp-angular-filesort');
var strip = require('gulp-strip-line');
var templateCache = require('gulp-angular-templatecache');
gulp.task("buildMenuTemplateCache", function(){
return gulp
.src(["./ext-modules/menu/**/*.html"])
.pipe(templateCache({
root : "./ext-modules/menu/",
module: "menu"
}))
.pipe( gulp.dest("./ext-modules/menu/"));
});
gulp.task("buildJS", function(){
return gulp
.src(["./ext-modules/**/*.js"]), //specify source
.pipe(angularFileSort()), //sorts js files in same folder so module comes first
.pipe(strip(['use strict'])), //removes use strict
.pipe(concat('framework.js')), //concatenate all files into single file
.pipe(dest('./dist/')); //specify destination
});
gulp.task("buildCSS", function(){
return gulp.src(),
.pipe(),
.pipe();
});
The above file is going to run in Node and not on the browser. So we need to install each of the required packages locally in the project using --save-dev flag like so:
npm install --save-dev gulp
Now if we look in our package.json file, we should see all our devDependencies listed in the file.
To run each individual task in gulpfile.js from Visual Studio, just right click the file and run the task. Doing so will produce the output of the task. We can also run the tasks using Task Runner Explorer from View->Other Windows menu item.
Finally, include the output file produced by the task runner in the distribution folder using "Show all files' in the solution. Then we need to import just this one single js file in our index.html file for all the javascript files! Similarly include a single .CSS file in index.html.
References:
http://www.pluralsight.com/training/player?author=mark-zamoyta&name=building-spa-framework-angularjs-m7&mode=live&clip=8&course=building-spa-framework-angularjs
http://www.toptal.com/nodejs/an-introduction-to-automation-with-gulp
Saturday, May 16, 2015
Web API v2 security
The Web API security pipeline consists of
The whole idea about Katana and OWIN being to be able to self host anywhere and getting away from IIS and System.Web dependency
The new kid in block to work with client identity is
HttpRequestMessage.GetRequestContext().Principal
and using Thread.CurrentPrincipal is now legacy
Read http://chimera.labs.oreilly.com/books/1234000001708/ch10.html
http://www.hanselman.com/blog/SystemThreadingThreadCurrentPrincipalVsSystemWebHttpContextCurrentUserOrWhyFormsAuthenticationCanBeSubtle.aspx
http://leastprivilege.com/2012/06/25/important-setting-the-client-principal-in-asp-net-web-api/
- Katana Middleware
- message handlers is legacy (Http modules that is baked in asp.net hosting in IIS)
- Authentication filters
- Authorization Filters
The whole idea about Katana and OWIN being to be able to self host anywhere and getting away from IIS and System.Web dependency
The new kid in block to work with client identity is
HttpRequestMessage.GetRequestContext().Principal
and using Thread.CurrentPrincipal is now legacy
Read http://chimera.labs.oreilly.com/books/1234000001708/ch10.html
http://www.hanselman.com/blog/SystemThreadingThreadCurrentPrincipalVsSystemWebHttpContextCurrentUserOrWhyFormsAuthenticationCanBeSubtle.aspx
http://leastprivilege.com/2012/06/25/important-setting-the-client-principal-in-asp-net-web-api/
Performing MongoDB atomic updates
NoSQL databases normally don't deal with transactions. Transactions can generally be avoided with good schema design and the canonical account debit/credit transaction is not really an instant transaction, if you ever transferred your money to someone right? Anyway, you can handle transactions from your business layer if needed. Having said that, MongoDB does allow for atomic updates spanning multiple documents, but they should all be within the same collection. It is very efficient with minimal data transfer.
The MongoCollection.Update has two parts - Query and Update.
Each can be type safe and consider using Query<T> and Update<T> helper classes.
articles.Update(query, update);
//Single Update
articles.Update( Query<Article>.EQ ( a => a.Id, "123A"),
Update<Article>.Set ( a => a.Expires, DateTime.Today));
//Multiple Updates
articles.Update( Query<Article>.LT( a => a.Expires, DateTime.Today),
Update<Article>.Set ( a => a.Archived, true));
Note that this bulk update happens all server side and you don't have to fetch all the data on the client to update!
There is no concept of foreign keys and joins between different collections, but we can create "foreign keys" to other collections by embedding the ObjectId of the document in one document from a collection to another document in a different collection. To do any kind of "joins", you would have to run 2 queries to fetch the related documents between the two collections.
Thing is you need far fewer collections in NoSQL than in Relational model. Fewer Joins translates into more scalability. The trade off is redundant data being stored and more memory. But the memory is actually mitigated using sharding (and replication for data availability and failover) and actually often works out to be far more cheaper than provisioning sophisticated multi-license expensive data centers to handle terabytes of relational data.
Takeaways:
The MongoCollection.Update has two parts - Query and Update.
Each can be type safe and consider using Query<T> and Update<T> helper classes.
articles.Update(query, update);
//Single Update
articles.Update( Query<Article>.EQ ( a => a.Id, "123A"),
Update<Article>.Set ( a => a.Expires, DateTime.Today));
//Multiple Updates
articles.Update( Query<Article>.LT( a => a.Expires, DateTime.Today),
Update<Article>.Set ( a => a.Archived, true));
Note that this bulk update happens all server side and you don't have to fetch all the data on the client to update!
There is no concept of foreign keys and joins between different collections, but we can create "foreign keys" to other collections by embedding the ObjectId of the document in one document from a collection to another document in a different collection. To do any kind of "joins", you would have to run 2 queries to fetch the related documents between the two collections.
Thing is you need far fewer collections in NoSQL than in Relational model. Fewer Joins translates into more scalability. The trade off is redundant data being stored and more memory. But the memory is actually mitigated using sharding (and replication for data availability and failover) and actually often works out to be far more cheaper than provisioning sophisticated multi-license expensive data centers to handle terabytes of relational data.
Takeaways:
- Your Mongo context is your implicit schema
- Use Strongly typed collection to respect the schema
- Use Mongo + LINQ
- Use Update instead of Retrieve + Save
MongoDB Useful CRUD Extension pattern using LINQ
Say if we want to remove some documents from a collection, we can use collection.Remove() by passing in a query like so
articles.Remove(Query<Article>.EQ ( a => a.PublishedDate < DateTime.Today ));
We can create a LINQ extension class for the MongoDB collection
public static class MongoExtensions
{
public static WriteConcernResult Remove<T> ( this MongoCollection<T> collection,
Expression<Func<T, bool>> query)
{
return collection.Remove(Query<T>.Where(query));
}
}
Then you can have your zen coding moments!
articles.Remove( a => a.PublishedDate < DateTime.Today );
articles.Remove(Query<Article>.EQ ( a => a.PublishedDate < DateTime.Today ));
We can create a LINQ extension class for the MongoDB collection
public static class MongoExtensions
{
public static WriteConcernResult Remove<T> ( this MongoCollection<T> collection,
Expression<Func<T, bool>> query)
{
return collection.Remove(Query<T>.Where(query));
}
}
Then you can have your zen coding moments!
articles.Remove( a => a.PublishedDate < DateTime.Today );
Wednesday, May 13, 2015
Redis Use Cases
Redis -REmote DIctionary Service is a key value store which has the ability to store some data, called a value inside a key. This is the essence of a NoSQL database. It is touted as the world's fastest distributed NoSQL data store. Data is available in RAM but unlike Memcache it is also persisted and has failover, replication etc.
About 100K to 400K simple operations per second on a Intel Core 2 Duo 2.6GHz CPU.
Example string data structure
SET person:myname "Frybo"
GET person:myname
No Schemas and no schema migrations! ServiceStack is the most popular C# client API.
Redis is different from document database NoSQL like Couchbase, RavenDB and MongoDB in that primarily it is resident in memory and not persisted in disk as documents, and have no indexes. It's just a key value store where the value can be unstructured, semi and structured data types from strings, hash, lists (5 data types as of now). It is extremely fast though it has no indexes in most use cases and essentially the raw power of Redis comes from it being resident in memory.
Good use cases for Redis:
Side Note:
For the task queues or queuing system, Resque is popular with Redis. Resque’s real power comes with the Redis “NoSQL” Key-Value store. While most other Key-Value stores use strings as keys and values, Redis can use hashes, lists, set, and sorted sets as values, and operate on them atomically. Resque leans on the Redis list datatype, with each queue name as a key, and a list as the value. Read http://girders.org/blog/2011/10/30/how-queuing-with-resque-works/
Must see videos:
https://www.youtube.com/watch?v=8Unaug_vmFI
https://www.youtube.com/watch?v=CoQcNgfPYPc
About 100K to 400K simple operations per second on a Intel Core 2 Duo 2.6GHz CPU.
Example string data structure
SET person:myname "Frybo"
GET person:myname
No Schemas and no schema migrations! ServiceStack is the most popular C# client API.
Redis is different from document database NoSQL like Couchbase, RavenDB and MongoDB in that primarily it is resident in memory and not persisted in disk as documents, and have no indexes. It's just a key value store where the value can be unstructured, semi and structured data types from strings, hash, lists (5 data types as of now). It is extremely fast though it has no indexes in most use cases and essentially the raw power of Redis comes from it being resident in memory.
Good use cases for Redis:
- analytics
- task queues
- Caching
- Data that expires
- Cookie Storage
- Search engines
- Ad Targeting
- Forums
- Messaging (using Pub/Sub)
- High I/O Workload
- Geo searches
Bad Use Cases
- More data than can fit in RAM
- Data that fits relational model - have relations and need joins
- You need ACID transactions
Side Note:
For the task queues or queuing system, Resque is popular with Redis. Resque’s real power comes with the Redis “NoSQL” Key-Value store. While most other Key-Value stores use strings as keys and values, Redis can use hashes, lists, set, and sorted sets as values, and operate on them atomically. Resque leans on the Redis list datatype, with each queue name as a key, and a list as the value. Read http://girders.org/blog/2011/10/30/how-queuing-with-resque-works/
Must see videos:
https://www.youtube.com/watch?v=8Unaug_vmFI
https://www.youtube.com/watch?v=CoQcNgfPYPc
Sunday, May 10, 2015
Role Based Security in .NET
In .NET prior to 4.5 was based out of IIdentity and IPrincipal which is an abstraction over how you would do authentication and authorization whether it is
Like Forms Authentication and <authorization /> (ASP.NET web.config) is SQL implementation of custom with membership and roles. But now we have a better way with Claims implementing ClaimsIdentity and ClaimsPrincipal (next blog post).
interface IIdentity
{
string name;
bool isAutheticated;
string AuthencticatedType;
}
interface IPrincipal
{
IIdentity identity;
bool IsInRole();
}
Once the current user principal object is created, attach it to the Thread.CurrentPrincipal static property from where you can access it anywhere in your code. Though static, it is per thread so no thread collisions here and you can always get your correct security context in the thread.
TIP: Never check for Role using string role name as it can change, literal strings will not work with Globalization and will break your code. Instead use the SID (SecurityIdentifer id) values - those never change. also, unless the user is in the domain admin group, if UserAdmin is activated (windows 2003 and above?) then a user in the Builtin Admins group will not be automatically in the group unless explicitly/manually assigned! So that's why you need to execute some apps with Run As Administrator otherwise you might get thrown a security exception!(even though you are in the admin group)
- Custom - GenericIdentity and GenericPrincipal
- Windows - WindowsIdentity and WindowsPrincipal
Like Forms Authentication and <authorization /> (ASP.NET web.config) is SQL implementation of custom with membership and roles. But now we have a better way with Claims implementing ClaimsIdentity and ClaimsPrincipal (next blog post).
interface IIdentity
{
string name;
bool isAutheticated;
string AuthencticatedType;
}
interface IPrincipal
{
IIdentity identity;
bool IsInRole();
}
Once the current user principal object is created, attach it to the Thread.CurrentPrincipal static property from where you can access it anywhere in your code. Though static, it is per thread so no thread collisions here and you can always get your correct security context in the thread.
TIP: Never check for Role using string role name as it can change, literal strings will not work with Globalization and will break your code. Instead use the SID (SecurityIdentifer id) values - those never change. also, unless the user is in the domain admin group, if UserAdmin is activated (windows 2003 and above?) then a user in the Builtin Admins group will not be automatically in the group unless explicitly/manually assigned! So that's why you need to execute some apps with Run As Administrator otherwise you might get thrown a security exception!(even though you are in the admin group)
Subscribe to:
Posts (Atom)