Wednesday, April 27, 2016

Friday, April 15, 2016

How to block the windows 10 upgrade

Difficult to believe, but the Microsoft Windows team seems it is ok to trick you to upgrade your Windows 7 machine to Windows 10 without you giving your consent.

 This article from PCWorld and utility from http://ultimateoutsider.com should let you configure your machine to avoid the upgrade.

How to block the windows 10 upgrade

Wednesday, April 13, 2016

Azure Function (JavaScript)


What Is An Azure Function? 


It is the equivalent of the Amazon Lambda. Azure can be written in JavaScript/NodeJs or in C# (Using dynamic C# or ScriptCS syntax). There are different ways to trigger a function
  • On demand via an http (HttpTrigger)
  • Periodically (TimerTrigger)
  • Trigger by blob storage, queue or event hub creation

Learn more : Create Your First Azure Function.
This is the default source code for a Http triggered function.

module.exports = function(context, req) {

    context.log('Node.js HTTP trigger function processed a request. RequestUri=%s', 
                req.originalUrl);

    if (req.query.name || (req.body && req.body.name)) {

        context.res = { 
            status: 200, 
            body: "Hello " + (req.query.name || req.body.name) };
    }
    else {

        context.res = { 
            status: 400, 
            body: "Please pass a name on the query string or in the request body" };
    }
    context.done();
};


Code Structure

Here is my attempt to write a Azure Function and build some re-usable code.
function AzureFunctionBaseClass(context, req) {

    this._context = context;
    this._req     = req;

    this.__terminate = function(m, status) { 

        this._context.res = { status: status, body: m };
        this._context.done();
    }
    this.succeed        = function(m) {  this.__terminate(m , 200); }
    this.fail           = function(m) {  this.__terminate(m , 400); }
    this.getQueryString = function()  { return this._req.query;           }
    this.getBody        = function()  { return this._req.body;            }
    this.log            = function(s) { this._context.log('[log]%s', s);  }
    this.getParameter   = function(n) { return this.getQueryString()[n];  }

    this.run = function() {

        var s = "Inherited run "+(new Date());
        this.log(s);
        this.succeed(s);
    }
    this.__init__ = function() {
        
        this.log("__init__ running");
    }
}

AzureFunctionBaseClass.create = function(functionType, context, req) {

    var l = new AzureFunctionBaseClass(context, req);
    functionType.call(l, context, req);
    l.__init__();
    return l;
}

function MyAzureFunction(context, req) {

    this.run = function() {

        var s = "Hello " + this.getParameter("name");
        this.log(s);
        this.succeed(s);
    }
}

module.exports = function(context, req) {

    AzureFunctionBaseClass.create(MyAzureFunction, context, req).run();
}


How to call the Lambda Function from CURL.exe

C:\Tools\PortableGit\bin>curl.exe -i -X GET "https://blankfunction.azurewebsites.net/api/HttpTrigger
NodeJS1?code=btguk5d3qu2dbvphut20c6jemi9745qootvk9pwwb61fo8byb98ugt79drusztwfjtahu6p3nmi&name=Freddy
"
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Length: 12
Content-Type: text/plain; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Set-Cookie: ARRAffinity=1d89995dbeffc7cc6215c40b5a2e03653fa822c763f464b0126bbb6bc29cc2d8;Path=/;Doma
in=blankfunction.azurewebsites.net
Date: Wed, 13 Apr 2016 12:54:59 GMT

Hello Freddy
C:\Tools\PortableGit\bin>

MQTT in Python, C# and JavaScript


MQTT in Python, C# and JavaScript

MQTT is on my horizon for a lot of communication projects, I am going to experiment.
So I am gathering basic samples how to use it in different languages.
  • Python, usefull for Linux and Raspberry PI
  • C#, because I am a PC
  • JavaScrip + Node, usefull if used with Azure Function or Amazon Lambda
  • JavaScript in a Browser

Python

Roughly, what to install on Windows.

  • Download Python 2.7
  • Pip package manager. Download and run pip https://bootstrap.pypa.io/get-pip.py
    • C:\Python27\python.exe get-pip.py # to install pip
    • Use pip to download the package paho-mqtt
      • C:\Python27\Scripts\pip install paho-mqtt
For more setup info, see page hivemq.com.

Subscribe

import paho.mqtt.client as paho
 
def on_subscribe(client, userdata, mid, granted_qos):
    print("Subscribed: "+str(mid)+" "+str(granted_qos))
 
def on_message(client, userdata, msg):
    print("topic:"+msg.topic+" qos:"+str(msg.qos)+" payload:"+str(msg.payload))
 
client     = paho.Client()
client.on_subscribe = on_subscribe
client.on_message   = on_message
client.connect("broker.mqttdashboard.com", 1883)
client.subscribe("encyclopedia/temperature", qos=1)
client.loop_forever()

Publish

import paho.mqtt.client as paho
import time
 
def on_publish(client, userdata, mid):
    print("mid: "+str(mid))

client = paho.Client()
client.on_publish = on_publish
client.connect("broker.mqttdashboard.com", 1883)
client.loop_start()
 
temperature = 90

while True:
    print("temperature:%d " % temperature)
    (rc, mid)   = client.publish("encyclopedia/temperature", str(temperature), qos=1)
    time.sleep(2)
    temperature = temperature + 1

C#


For C# I am using the library M2Mqtt, that can be downloaded from NuGet.
Complere Source Code MQTT CSharp.cs

Subscribe

static void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
    Console.WriteLine("Received = " + Encoding.UTF8.GetString(e.Message) + " on topic " + e.Topic);
}

const string mqttServer = "broker.mqttdashboard.com";
const string pusblishedVar = "encyclopedia/temperature";

private static void SubscribeAndListen(string CLIENT_ID_SUB)
{
    MqttClient client;
    Console.WriteLine("Setting up subscribe mode:{0}, clientID:{1}", mqttServer, CLIENT_ID_SUB);
    client = new MqttClient(mqttServer);
    client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
    client.MqttMsgSubscribed += Client_MqttMsgSubscribed;
    client.Connect(CLIENT_ID_SUB);
    client.Subscribe(new string[] { pusblishedVar }, new byte[] { MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE });

    var displayMenu = new Action(delegate()
    {
        Console.Clear();
        Console.WriteLine("Q)uit C)lear - Waiting...");
    }); 
    
    var quit = false;
    displayMenu();
    while (!quit)
    {
        if (Console.KeyAvailable)
        {
            switch (Console.ReadKey().Key)
            {
                case ConsoleKey.Q: quit = true; break;
                case ConsoleKey.C: ; displayMenu(); break;
            }
        }
        Thread.Sleep(250);
    }
    client.Disconnect();
}



Publish

const string mqttServer = "broker.mqttdashboard.com";
const string pusblishedVar = "encyclopedia/temperature";
        
private static void Publish(string CLIENT_ID_PUB)
{
    Console.WriteLine("Setting up publish mode ClientID:{0}", CLIENT_ID_PUB);
    var client = new MqttClient(mqttServer);
    client.Connect(CLIENT_ID_PUB);
    var varValue = 70;
    client.MqttMsgPublished += Client_MqttMsgPublished;

    Console.WriteLine("Publishing {0}:{1}", pusblishedVar, varValue);
    client.Publish(pusblishedVar, Encoding.UTF8.GetBytes(varValue.ToString()), MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE, false);
    
    client.Disconnect();
}

JavaScript + Node.js


To install MQTT package
nmp install mqtt

Publish

// contoller.js and garage.js
var mqtt = require('mqtt')  
var client = mqtt.connect("mqtt://broker.mqttdashboard.com");//, 1883)

client.on('connect', function() {  

 console.log("Connected, Publishing.");
   // Inform controllers that garage is connected
 client.publish('encyclopedia/temperature', '66')
})



/**
 * Want to notify controller that garage is disconnected before shutting down
 */
function handleAppExit (options, err) {  
 console.log("Exiting...")
 if (err) {
  console.log(err.stack)
 }
 if (options.cleanup) {
 
 }
 if (options.exit) {
  process.exit()
 }
}

/**
 * Handle the different ways an application can shutdown
 */
process.on('exit', handleAppExit.bind(null, {  
  cleanup: true
}))
process.on('SIGINT', handleAppExit.bind(null, {  
  exit: true
}))
process.on('uncaughtException', handleAppExit.bind(null, {  
  exit: true
}))

JavaScript in a browser


MQTT publisher or subscriber can also be hosted in a browser using Websockets. See link http://www.hivemq.com/demos/websocket-client

Wednesday, March 16, 2016

Azure VM inbound port to allow SQL server from the internet

To expose a SQL Server instance running in an Azure VM to the internet here how to configure the port.

Also for Reporting Services you need to output port 80 for http.
Turn down the firewall to start



Also follow this link for other steps Provision a SQL Server virtual machine in Azure


SQL Server Management Studio - Script Generation - IF EXISTS

Tools -> Options -> SQL Server Object Explorer -> Scripting -> Check for object existence -> True

Thursday, March 10, 2016

Amazon Lambda Function


What Is AWS Lambda? 



My quick definition: A little bit of JavaScript or Python that can be invoked via an URL and will run in the cloud. A quick NodeJS instance in the cloud. The buzz word is MicroService. Here is the definition from amazon page.

I guess the equivalent on Azure is the new Azure Function, more on that later.

Other functionalities

With AWS Lambda you are allowed to
  • Inlude npm package
  • Execute binary file
AWS Lambda FAQ page


Code Structure

This is hello world lambda example. In the end a Lambda Function is a JavaScript function, an event handler running in a NodeJs environment.
The event object contains the input parameters. The context object allows to return a result.
console.log('Loading function');

exports.handler = function(event, context) {

    console.log('value1 =', event.key1);
    console.log('value2 =', event.key2);
    console.log('value3 =', event.key3);
    context.succeed(event.key1);  // Echo back the first key value
    // context.fail('Something went wrong');
};

Here is my attempt to write a Lambda function and build some re-usable code.
See fjs.lib to access the library Sys and String.  The file Sys.js and String.js were written to be compatible with nodejs or a browser.
The file Sys.js and String.js are located in the sub folder node_modules to be accessible by the lambda script.
require("Sys");
require("String");

/*
    Re usable code for next Lambda Function.
 */
var LambdaFuncBaseClass = function() {

    this.send = function(succeeded, data) {

        var d = new Date();
        var m = "[{0}, {1}]{2}".format(succeeded ? "PASSED":"FAILED", d, data);
        this.log(m);
        if(succeeded)
            this._context.succeed(m);
        else 
            this._context.fail(m);
    }
    this.log = function(data, message) {

        if(sys.isObject(data)) {            

            if(!sys.isDefined(message)) message = "object";
            console.log(message);
            for(var p in data) {
                this.log(" .."+p + ":" + data[p]);
            }
        }
        else {
            if(sys.isDefined(message))
                console.log(message+" ~ "+data);
            else
                console.log(data);
        }
    }
    this.__init__ = function() {

        console.log('Init lambda function:' + this.Name);
    }
}
/*
    A static member to initialize my customized Lambda Function
 */
LambdaFuncBaseClass.create = function(name, functionType) {

    var l            = new functionType(name);
    exports.handler  = l.handler;
    LambdaFuncBaseClass.call(l);
    l.__init__();
    return l;
}

/*
    My new Lambda Function
 */
var MyLambdaFunc = function(name) {

    var $this  = this;
    $this.Name = name;

    this.handler = function(event, context) {

        $this._context = context;
        try{
            $this.log(event, "Input parameters");
            $this.send(true, "Looks OK. ErrorCode:{0}".format(0));
        }
        catch(ex) {
            $this.send(false, "exception "+ex);
        }
    }
}
var myLambdaFunc = LambdaFuncBaseClass.create("myLambdaFunc", MyLambdaFunc);



How to call the Lambda Function from CURL.exe

C:\Tools\PortableGit\bin>curl -i -X GET "https://m956zj9ecj.execute-api.us-west-2.amazonaws.com/prod/FHelloWorld?phoneNumber=19787606031&message=HiMan"
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 52
Connection: keep-alive
Date: Fri, 11 Mar 2016 03:02:48 GMT
x-amzn-RequestId: bc86ed04-e735-11e5-b279-317fad6da791
X-Cache: Miss from cloudfront
Via: 1.1 2d480f42c6a626fc8d8c8aaaf1ec043d.cloudfront.net (CloudFront)
X-Amz-Cf-Id: kk-pRWjjHxOI7OJUEBvaQLC-7o389kuO1Zb4ByjyJOodKjZSpxNbvw==
"[Fri Mar 11 2016 03:02:48 GMT+0000 (UTC)] Looks OK"


C:\Tools\PortableGit\bin>curl  -X GET "https://m956zj9ecj.execute-api.us-west-2.amazonaws.com/prod/FHelloWorld?phoneNumber=19787606031&message=HiMan"
"[Fri Mar 11 2016 03:02:52 GMT+0000 (UTC)] Looks OK"



Tuesday, January 19, 2016

C# unsafe pointer - how to do it?

unsafe { ushort val; byte* valPtr = (byte*) &val; valPtr[1] = bigEndianFirstByte; valPtr[0] = bigEndianSecondByte; // use val here }