Dream, not what is, but what can be.

Web Sockets example

Code for web socket server

    public class MyEchoHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            if (context.IsWebSocketRequest)
            {
                context.AcceptWebSocketRequest(WebSocketRequestHandler);
            }
        }

        public bool IsReusable { get { return false; } }

        //Asynchronous request handler.
        public async Task WebSocketRequestHandler(AspNetWebSocketContext ctx)
        {
            //Gets the current WebSocket object.
            WebSocket socket = ctx.WebSocket;

            await socket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes("Connected to the echo server!")), WebSocketMessageType.Text, true, CancellationToken.None);

            ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]);
            while (true)
            {
                var retVal = await socket.ReceiveAsync(buffer, CancellationToken.None);

                if (retVal.CloseStatus != null)
                {
                    await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Goodbye", CancellationToken.None);
                    return;
                }

                await socket.SendAsync(new ArraySegment<byte>(buffer.Array, 0, retVal.Count), retVal.MessageType, retVal.EndOfMessage, CancellationToken.None);
            }
        }
    }

Code for web socket client

<body>
<p>
<input id="txtInput" type="text" value="" />
<input type="button" value="Send" id="btnSend" />
<input type="button" value="Close" id="btnClose" />
</p>
<div id="output">

</div>

<script type="text/javascript">
<!-- ws / wss (SSL) -->
var url = "wss://<service>/MyEchoHandler.ashx";

var webSocket = new WebSocket(url);

var inputTextBox = document.getElementById("txtInput");
document.getElementById("btnSend").addEventListener("click", function () { webSocket.send(inputTextBox.value); });
document.getElementById("btnClose").addEventListener("click", function () { webSocket.close(); });

var outputDiv = document.getElementById("output");
function appendToDiv(text) {
var newElement = document.createElement("p");
newElement.appendChild(document.createTextNode("[" + new Date().toLocaleDateString() + "]" + text));
outputDiv.insertBefore(newElement, outputDiv.firstChild);
}

webSocket.onopen = function () { appendToDiv("Socket Opened!"); };
webSocket.onmessage = function (event) { appendToDiv(event.data); };
webSocket.onerror = function () { appendToDiv("Socket error!"); };
webSocket.onclose = function (event) { appendToDiv("Socket closed with message '" + event.reason + "'."); };
</script>
</body>

Posted on Tuesday, February 07, 2017 6:30 AM


Directly editing IIS 7 applicationHost.config configuration file

File is located: C:\windows\system32\inetsrv\config

Making changes in 32 bit app like Notepad ++ saves the file in c:\Windows\SysWOW64\inetsrv\Config so need to copy the file to C:\windows\system32\inetsrv\config.

Restart IIS

Posted on Wednesday, December 28, 2016 6:43 AM


405 error - Method Not Allowed using IIS - Restful service

Make sure you are including the web page file name in the post URL (http://yoursite/app/Page instead of http://yoursite/app)

Posted on Tuesday, December 27, 2016 9:51 AM


Convert Python numpy and .Net arrays

Python code

from System.Runtime.InteropServices import Marshal
from System import Array, Double, IntPtr
import numpy as np

# Convert .Net array to Python array
def convNetarray2Nparray(arrayIn):
    arrayOut = np.empty(len(arrayIn))
    Marshal.Copy(arrayIn, 0, IntPtr.__overloads__[long](arrayOut.__array_interface__['data'][0]), len(arrayIn))
    return arrayOut

# Convert Python array to .Net array
def convNparray2Netarray(arrayIn):
    arrayOut = Array.CreateInstance(Double,len(arrayIn))
    Marshal.Copy(IntPtr.__overloads__[long](arrayIn.__array_interface__['data'][0]),arrayOut,0, len(arrayOut))
    return arrayOut

    # SLOW FOR LARGE ARRAYS
    #arrayOut = Array.CreateInstance(Single,len(arrayIn))
    #it = np.nditer(arrayIn,flags=['multi_index'])
    #while not it.finished:
    #    ix = it.multi_index
    #    if len(ix)==1:
    #        arrayOut[ix[0]] = arrayIn[ix[0]]
    #    else:
    #        arrayOut[ix] = arrayIn[ix]
    #    it.iternext()
    #return arrayOut

Posted on Thursday, October 13, 2016 9:49 AM


32 bit dll in a 64 bit app

If use a 32 bit dll in a 64 bit application you will get a BadFormatException.

Created an out-of-process COM Server to host the 32 bit dll / logic. Register it on the PC and then can call it from the application.

Used COM Server from CSExeCOMServer

In the Build Event added

echo Generate and register type library.
C:\Windows\Microsoft.NET\Framework\v4.0.30319\regasm.exe /tlb "$(TargetPath)"
echo Register the component.
C:\Windows\Microsoft.NET\Framework\v4.0.30319\regasm.exe "$(TargetPath)"

Client Code:

Type comType = Type.GetTypeFromProgID("COMServerName.ObjecteName");
dynamic targetCom = Activator.CreateInstance(comType);
dynamic target = targetCom.TargetProperty;

Posted on Saturday, October 22, 2016 3:17 PM


Python.Net

python.net

using (Py.GIL())
{
    dynamic imp = Py.Import("imp");
    dynamic rem = imp.load_source("CustomPyFile", string.Format("{0}/CustomPyFile.py", Directory.GetCurrentDirectory()));

    // named tuple
    dynamic argList = rem.NamedTupleVar;
    argList.Name1 = new PyInt(1000);
    dynamic myRem = rem.CustomClassName(argList);

    // array test
    dynamic np = Py.Import("numpy");
    List<float> floats = new List<float>();
    Random rand = new Random();

    for (int i = 0; i < 240000; i++)
    {
        floats.Add(rand.Next());
    }
    myRem.Method1(np.array(floats));

    // get
    dynamic getValues = myRem.Method3();
    Console.WriteLine(getValues.GetAttr("propertyName").ToString();

    Console.Read();
}

Posted on Thursday, September 15, 2016 12:22 PM


Real Ear Measurement using NAudio and Python.Net

Integrated Python For .Net and NAudio (ASIO sound drivers) for a Real Ear Measurement (REM) system.

Posted on Friday, August 19, 2016 7:24 PM


NAudio to record / play ASIO sound drivers

Using NAudio for record and play ASIO sound drivers

Posted on Friday, August 19, 2016 7:22 PM


Integrating Python into .Net app using Python For .Net

Using Python For .Net to call Python methods from C#

Also to call the methods from a class I had to decorate the Python class method with @ClassMethod

Also, still need to find a way to pass an array into the method. So far have to pass a List and convert in the Python method :(

PythonEngine.Initialize();
var lck = PythonEngine.AcquireLock();

PyObject pyportal = PythonEngine.ImportModule(@"SomePyFile"); // .py file
PyObject c = pyportal.GetAttr("ClassName"); // class name in .py file

PyList ls = new PyList(new PyObject[3] { new PyFloat(1.0), new PyFloat(1.0), new PyFloat(1.0) });
c.InvokeMethod("SomeMethod", ls).ToString(); // some method in ClassName

string fromPython = "";
for (int i = 0; i < 100; i++)
{
    fromPython = c.InvokeMethod("AnotherMethod").ToString();
}

PythonEngine.ReleaseLock(lck);
PythonEngine.Shutdown();

IronPython does not implement some CPython packages like scipy.fftpack - get cannot import multiarray from numpy.core error

Posted on Friday, August 12, 2016 2:42 PM


Tour de Tonka 2016

Rode 100 mile route with Kelly Fitz and Adrian Lister. Very fast - rode with the pack the whole way.

Posted on Saturday, August 06, 2016 6:49 PM