Wednesday, May 27, 2015

Run PHP from Visual Studio Code

In my previous posts I explained examples using a solution file to compile and debug .NET (mono) in Visual Studio Code.

This post shows how to set up a task to run PHP using the build in Development Server of PHP.

In Visual Studio Code open the folder with the php file(s).

Then start the Command Palette and choose Configure Task Runner.
This creates a tasks.son file. Clear all and replace with the settings below:

{
"version": "0.1.0",
"command": "php",
"args": [
"-S", "127.0.0.1:8080",
"-t", "${workspaceRoot}"
]
}

Save the file and start the task from the Command Palette, choose Run Task and then 'php'.

A PHP Development Server has been started on port 8080. Start your browser, go to http://127.0.0.1:8080 and you will see the website from the selected folder.



At this moment it is not possible to debug PHP from Visual Studio Code.

Wednesday, May 06, 2015

Debug a Visual Studio solution in Visual Studio Code on OSX

In my previous post I showed how to compile a .NET solution with Visual Studio Code with Mono on a Mac. This post shows how to set up debugging with Visual Studio Code with Mono on a Mac.

After the solution is build set a breakpoint in de code go to the 'Debug'-panel and press the green play-button in top. It will create a file named launch.json. This file is configured for node, but with some minor adjustments it can work for mono as well.

{
  "version": "0.1.0",
  "configurations": [
    {
      // Name of configuration;
      "name": "Hello",
      // Type of configuration.
      "type": "mono",
      // Workspace relative or absolute path to the program.
      "program": "bin/Debug/Hello.exe",
      // Automatically stop program after launch.
      "stopOnEntry": true,
      // Command line arguments passed to the program.
      "args": [],
      // Workspace relative or absolute path to the working directory of the program being debugged. Default is the current workspace.
      "cwd": ".",
      // Workspace relative or absolute path to the runtime executable to be used. Default is the runtime executable on the PATH.
      "runtimeExecutable": null,
      // Environment variables passed to the program.
      "env": { }
    }, 
    {
      "name": "Attach",
      "type": "mono",
      // TCP/IP address. Default is "localhost".
      "address": "localhost",
      // Port to attach to.
      "port": 5858
    }
  ]
}

Save the file and you are ready to go!

Thursday, April 30, 2015

Compile a Visual Studio solution in Visual Studio Code on OSX

Microsoft has launched Visual Studio Code, an IDE for C#, Javascript, Typescript and many more. It is a shell over Atom and runs also on OSX and Linux!

I wanted to see if it is possible to compile a Visual Studio solution (.sln file from Windows) in Visual Studio Code on my Mac (using Mono).

As you can see in the screenshot below; it worked! All I had to do is add a task
(CMD+P => 'Configure Task Runner', this will create and show the tasks.json file. Erase all and just type in the command and the args)

{
   "command" : "xbuild",
   "args": ["Hello.sln"]
}

Visual Studio Solution in Visual Studio Code on OSX

SHIFT+CMD+B Builds the solution.

Update: I made a new post how to DEBUG the solution in Visual Studio Code with mono on the Mac!

Tuesday, March 10, 2015

HUAWEI HG659 5G WLAN with iPad, iMac and MacBook Pro

Recently I received an HUAWEI HG695 router. It has a dual band wireless for 2.4 and 5 Ghz. But even the 5G was enabled on the router it did not show up on my wifi-list on my iMac, iPad and MacBook.
The answer lies in one advanced WLAN setting:


Change the bandwidth from 20Mhz to 20/40Mhz and all works like a charm.

Friday, March 06, 2015

JSON serialized object in NHibernate

The other day I needed to store some user settings into the database. The settings involved the properties of a chart, with title, axis, series, manual series etc. Normally there would be a entity for the chart, entities for the series with some kind of inheritance and then create all the mappings.

A lot of overhead for storing some settings, in case of a NoSQL database like MongoDB you just save the settings object.

I thought it would be nice to just map the settings object as a single column like:

 Property(p => p.Settings);

Therefore I developed a  JSONMappableType for NHibernate:

Property(p => p.Settingsm =>
        {
            m.Length(8096);
          m.Type<JsonMappableType<Settings>>();
        });

This serializes the complete Settings object to a JSON-string into a single column. And when retrieving from the database the Settings object is deserialized from the JSON-string.

I derived the mapping from NHibernates IUserType and used Newtonsoft.Json for the (de-)serialisation of the object. I had to override the DefaultContractResolver, because the order of the properties is random at each call which made object 'dirty' all the time. Ordering the properties by name solved that problem.


using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using NHibernate;
using NHibernate.SqlTypes;
using NHibernate.UserTypes;
using System;
using System.Linq;
namespace My.Mappings
{
    public class JsonMappableType<T> :IUserType
    {
        public object Assemble(object cachedobject owner)
        {
            //Used for casching, as our object is immutable we can just return it as is
            return cached;
        }
        public object DeepCopy(object value)
        {
            //We deep copy the Translation by creating a new instance with the same contents
            if (value == null)
                return null;
            if (value.GetType() != typeof(T))
                return null;
            return FromJson(ToJson((T)value));
        }
        
       
        public object Disassemble(object value)
        {
            //Used for casching, as our object is immutable we can just return it as is
            return value;
        }
        public new bool Equals(object xobject y)
        {
            //Use json-query-string to see if their equal 
            // on value so we use this implementation
            if (x == null || y == null)
                return false;
            if (x.GetType() != typeof(T) || y.GetType() != typeof(T))
                return false;
            return ToJson((T)x).Equals(ToJson((T)y));
        }
        public int GetHashCode(object x)
        {
            if (x != null && x.GetType() == typeof(T))
                return ToJson((T)x).GetHashCode();
            return x.GetHashCode();
        }
        public bool IsMutable
        {
            get { return false; }
        }
        public object NullSafeGet(System.Data.IDataReader rsstring[] namesobject owner)
        {
            //We get the string from the database using the NullSafeGet used to get strings 
            string jsonString = (string)NHibernateUtil.String.NullSafeGet(rsnames[0]);
            //And save it in the T object. This would be the place to make sure that your string 
            //is valid for use with the T class
            return FromJson(jsonString);
        }
        public void NullSafeSet(System.Data.IDbCommand cmdobject valueint index)
        {
            //Set the value using the NullSafeSet implementation for string from NHibernateUtil
            if (value == null)
            {
                NHibernateUtil.String.NullSafeSet(cmdnullindex);
                return;
            }
            value = ToJson((T)value);
            NHibernateUtil.String.NullSafeSet(cmdvalueindex);
        }
        public object Replace(object originalobject targetobject owner)
        {
            //As our object is immutable we can just return the original
            return original;
        }
        public Type ReturnedType
        {
            get { return typeof(T); }
        }

        public SqlType[] SqlTypes
        {
            get
            {
                //We store our translation in a single column in the database that can contain a string
                SqlType[] types = new SqlType[1];
                types[0] = new SqlType(System.Data.DbType.String);
                return types;
            }
        }
        private static JsonSerializerSettings jsonSetting = new JsonSerializerSettings
        {
            ContractResolver = new OrderedContractResolver(),
            Formatting = Formatting.None,
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
            PreserveReferencesHandling = PreserveReferencesHandling.Objects,
            DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate
            
        };
        public static T FromJson(string jsonString)
        {
            if (!string.IsNullOrWhiteSpace(jsonString))
                return JsonConvert.DeserializeObject<T>(jsonStringjsonSetting);
            return Activator.CreateInstance<T>();
        }

        public static string ToJson(T obj)
        {
            return JsonConvert.SerializeObject(objjsonSetting);
        }
        /// <summary>
        /// Order the json-properties to create a simple equals case for JsonMappableType.Equals
        /// </summary>
        private class OrderedContractResolver : DefaultContractResolver
        {
            protected override System.Collections.Generic.IList<JsonPropertyCreateProperties(System.Type typeMemberSerialization memberSerialization)
            {
                return base.CreateProperties(typememberSerialization).OrderBy(p => p.PropertyName).ToList();
            }
        }
    }


}