ict.ken.be

Delivering solid user friendly software solutions since the dawn of time.

NodeJs 

Categories: Nodejs

Since november 2009 at http://jsconf.com/ europe by Ryan Dahl, because building progress bars into Ruby was just to slow. Written for a data center.

Who is using node

Best tool vs swiss army knife

  • Sharding complexity by separating your code
  • Composition in favor of inheritance
  • Avoid callback hell (http://callbackhell.com/)
  • No nested if-then-else, return early
  • Error-first callback
  • Leverage the ecosystem
  • Develop for the clueless stranger

Error-first callbacks

fs.readFile('/foo.txt', function(err, data) {
    if(err) {
        if(err.fileNotFound) {
            return this.sendErrorMessage('File Does not Exist');
        }
        if(!err.noPermission) {
            return next(err);
        }
    }
    console.log(data);
});

Use async

async.parallel({
    one: function(callback){
        setTimeout(function(){
            callback(null, 1);
        }, 200);
    },
    two: function(callback){
        setTimeout(function(){
            callback(null, 2);
        }, 100);
    }
},
    function(err, results) {
    // results is equal to: {one: 1, two: 2}
});

Testing

  • There are no points for clever tests
  • Test clarity above all else
  • Jasmine all in one testing framework
  • Mocha follows node standard, no mocks, no asserts

Mocha

describe('yourModuleName', function() {
    before(function(){
        // The before() callback gets run before all tests in the suite. Do one-time setup here.
    });
    beforeEach(function(){
        // The beforeEach() callback gets run before each test in the suite.
    });
    it('does x when y', function(){
        // Now... Test!
    });
    after(function() {
        // after() is run after all your tests have completed. Do teardown here.
    });
});

NodeJs Built-In Assertions

assert.equal(life, 42, 'some message');
assert(life === 3, 'some message');

Chai Assertion Library

foo.should.be.a('string');
expect(foo).to.be.a('string');
assert.typeOf(foo, 'string');

Sinon Spies, Stubs and Mocks

var callback = sinon.stub();
callback.withArgs(42).returns(1);

Mockery Require Mocking

before(function() {
    mockery.enable();
    mockery.registerAllowable('async');
    mockery.registerMock('../some-other-module', stubbedModule);
});
after(function() {
    mockery.deregisterAll();
    mockery.disable();
});

Rewire Require DI

var rewire = require("rewire");
var myModule = rewire("../lib/myModule.js");
myModule.__set__("path", "/dev/null");

Modules

Type example (preferred)

var privateStaticVariable = true;

module.exports = User;
function User(n) {
    this._privateVariable = true;
    this.name = n;
}
User.prototype.sayHi = function() {
    console.log('Hi, My name is ' + this.name);
};

var User = require('User');
var alice = new User('Alice');
alice.sayHi(); // "Hi, My name is Alice"

Slower, but real private variable (avoid)

module.exports = User;
function User(n) {
    var privateVariable = true; 
    this.publicVariable = n;     
    this.toggle = function toggle() {
        privateVariable = !privateVariable;
    }
}

Running multiple node versions

Using EcmaScript 2015 (ES6)

Clubbing the seal 

Categories: .Net

"There are those who think that a language should prevent programmers from doing stupid things, and those who think programmers should be allowed to do whatever they want." [Hackers & Painters by Paul Graham]

Cute seal toy on green carpet.

Imagine, you are implementing a DbExecutionStrategy for Entity Framework and you are thinking: Let me inherit this SqlException, so I can create a ThrowTimeOutExpiredSqlException and use this to test my execution strategy... a bit later you realise the class is sealed... bummer... ok let's just use the SqlException class itself and hopefully find the correct properties to make it behave the way I want... bummer again... it seems all the constructors are private... but wait it seems there are some factory methods called CreateException... I am sure that's what I need to use... euh or not since they are marked as internal.

I guess by now you realise I am belonging to the group of developers that thinks programmers should be allowed to do whatever they want.

So why make things so difficult? Why would I want to make things sealed, internal or even non-virtual?

  • Speed optimization
  • Security considerations
  • Ensuring immutables don't become mutables
  • Prevent inheritance fragility

OR...

Because I am to 'lazy' to design the class for inheritance and sealed effectivily says: "The writer of this class did not design this class to be inherited. Nothing less, nothing more."

Of course we need to read lazy as: I am working for a company and I have no time to implement all these other members and think of all the edge cases you might use this class for. Moreover if you inherit my stuff and then it breaks when I change stuff I have to work more and therefor spend more company money... and I think that's the main reason: Maintainability of legacy projects.

And this is also the reason many of the microsoft framework classes are sealed and have internals. Microsoft tries to prevent developers from using things they probably will change or not support in future versions. And if they would allow developers from using them, they would probably break the software when the user does the next windows update. And guess who get's the blame at that moment.

Maybe we should invent an attribute to mark classes with [I_Consider_This_Sealed But_I_Am_Leaving_You_The_Freedom To_Change_It] or some other way to express our intentions. Until then I believe that if you extend a class it's your problem if you break it. Start writing more unit tests.

Anyway, I solved the SqlException thing by using reflection to access the method and I for sure will blame microsoft if they change this method in future EF versions :)

More about seals:

ps: Most of the time I favor composition over inheritance.
ps2: Did you know static classes are actually sealed classes? Maybe that's why I don't like those either...

SAN certificate request checklist 

Categories: IIS

1. Validate your identity

  • Validations Wizard - Email Address Validation - Confirmation mail - Valid for 30days
  • Validations Wizard - Domain Name Validation - Confirmation mail
  • Validations Wizard - Personal Identity Validation
  • Upload scan of both sides of identity card.
  • Upload scan of first page of international passport.
  • Confirmation call
  • Upload additional documents requested
  • Wait for email confirmation
  • Validations Wizard - Organization Validation
  • Upload scan of trademark
  • Upload scan of company registration
  • Upload scan of authorization letter
  • Wait for email confirmation

2. Create certificate signing request

  • MMC - Certificates (Local Computer) - Personal - Right-click - All Tasks - Advanced Operations - Create custom request
  • Proceed without enrollment policy - CNG Key - PKCS#10
  • Certificate Information - Click Details - Properties
  • General - Friendly name : start with astrix eg. *SAN for my domains (description is not needed, but handy)
  • Subject - Name - Add Email, Common Name (eg. *.ken.be), Organisation, Location, State, Country
  • Subject - Alternative Name - Add DNS for each domain and wildcard for sub-domains (eg. ken.be and *.ken.be)
  • Extensions - Key Usage - Add Digital signature, Key encipherment, Key agreement (a8)
  • Extensions - Extended Key Usage - Add Server Authentication, Client Authentication
  • Private Key - Key Options - Key Size >= 4096
  • Private Key - Make private key exportable
  • Private Key - Select Hash Algorithm - sha256 or higher
  • Save as base64 .csr file
  • MMC - Certificates (Local Computer) - Certificate Enrollment Request - Export the request with private key

3. Web Server SSL/TLS certificate

  • Certificates Wizard - Skip - Paste your csr - Continue
  • Add each domain and then the subdomains
  • Wait for confirmation mail
  • Toolbox - Retrieve Certificate
  • Save as .cer file
  • MMC - Certificates (Local Computer) - Certificate Enrollment Request - Import the cer file.
  • It will merge with your request and you can then export it to a .pfx that contains both public and private key.

4. Install Intermediate Certification Authorities

  • MMC - Certificates (Local Computer) - Intermediate Certification Authorities
  • Make sure all the intermediate certificates are at least sha256 or you will get 'The site is using outdated security settings that may prevent future versions of Chrome from being able to safely access it.'
  • Also make sure not old sha1 stay behind in both the local and the current user store (right-click find certificate)
  • I had to reboot the server to get rid of the old intermediates.

5. Install your certificate on your server

  • IIS Root - Server Certificates - Import
  • You can now use it in your bindings (remember only on for each IP)

6. Remove cyphers that have been broken

  • Prevent Beast, Poodle, ...
  • You can do this all manually or use a simple tool like IISCrypto
  • Do not disable cyphers that you might need to remote desktop !
  • Test with SSLLabs

More
http://blog.chromium.org/2014/09/gradually-sunsetting-sha-1.html
https://support.servertastic.com/deprecation-of-sha1-and-moving-to-sha2/
https://www.nartac.com/Products/IISCrypto/
https://www.ssllabs.com/ssltest/analyze.html

Exe with all dll assemblies included 

Categories: .Net

When Owin was released, I created WebGenius. A small exe you can drop in any folder, run it and everything is accesible as web pages.

I embedded the assemblies like this:

static Program()
{
   AppDomain.CurrentDomain.AssemblyResolve += ResolveAssembly;
}

static Assembly ResolveAssembly(object sender, ResolveEventArgs args)
{
   var resourceName = "WebGenius." + new AssemblyName(args.Name).Name + ".dll";
   Console.WriteLine("Resolving: " + resourceName);
   using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
   {
      if (stream == null) return null;
      var assemblyData = new Byte[stream.Length];
      stream.Read(assemblyData, 0, assemblyData.Length);
      return Assembly.Load(assemblyData);
   }
}

However I just found out about an amazing plugin for the Fody dll weaver:

  • Include Costure.Fody nuget into your exe project and your done.

Some options for your FodyWeavers.xml

<Costura CreateTemporaryAssemblies='false' />
<Costura IncludeDebugSymbols='false' />
<Costura DisableCompression='false' />
<Costura ExcludeAssemblies='Foo|Bar' />-->
<Costura IncludeAssemblies='Foo|Bar' />-->
<Costura Unmanaged32Assemblies='Foo32|Bar32' Unmanaged64Assemblies='Foo64|Bar64' />
<Costura PreloadOrder='Foo|Bar' />

Some options for you project file:

<Target Name="CleanReferenceCopyLocalPaths" AfterTargets="AfterBuild;NonWinFodyTarget" >
   <Delete Files="@(ReferenceCopyLocalPaths->'$(OutDir)%(DestinationSubDirectory)%(Filename)%(Extension)')" />
</Target>
Page 6 of 40 << < 1 2 3 4 5 6 7 8 9 10 20 > >>