April 27, 2014

Touchdevelop pt 2

I the first part I started with programming on the phone using touchdevelop.

This time I will go a little bit deeper and finish my bird song quiz app.

Basic functionality is to randomly get six bird sounds from my media list on the phone, display all six and play one of them letting the user guess which one is right. After choosing the app will tell you if it was correct.

In the last part we started out with this to get a random song:

action main()
      var mysongs := media→ songs
      var chosensong := songs→random
      player→play(chosensong)
end action


This time we do the same stuff but six times with a a while clause that adds stuff to a collection.

First we add the chosen song:

var quizlist:=collections→create string collection
quizlist→add(▷ getbirdname(chosensong→name))
var x:=0
while x < 5 do
   var decoy := ▷getbirdname(songs→random→name
   if quizlist→contains(decoy) then
   else
      quizlist→add(decoy)
      x := x+1
   end if
end while

As I want a bird song quiz I have to convert the mp3-name (for example white-tailed swallow.mp3) to a bird name. I do this by removing the .mp3 from the name together with all numbers I can find (sometimes I have many numbered sounds for a bird).  This is done in getbirdname and the symbol ▷  means that it calls a function that returns the bird name from the mp3 file name.

The function looks like this:

private atomic action getbirdname(s:string)
returns (out:string)
do
   out:=s→replace regex("[\\d-]","")→replace(".mp","")
end action

Simple regex to get rid of the digits and then I just remove the .mp-part and return the name.

Then I show the names from the quizlist and plays the chosen one on my phone with:

quizlist→sort 
player→play(chosensong)
"Choose bird:"→post to wall
□ chosen:= -1
while □ chosen < 0 do
   □ chosen := wall→pick string("Which bird is this?", "Choose an alternative.", quizlist)
end while
if quizlist→at(□ chosen)→equals(▷ getbirdname(target→name)
then
   "Correct"→post to wall
else
   "Incorrect"→post to wall
   ▷ getbirdname(target→name)→post to wall
end if

The  chosen means that it can save the result between rounds as a global persistant variable that can be stored in the cloud.

Oh by the way....
the symbol □ looks like this with a bit magnification:

I've just touched on what you can do with touchdevelop (try for example language→speak text("en-US", "female", ▷ getbirdname(chosensong→name)), but since I still haven't found any customer who wants his business system written in the language I will move on to graph databases next time.

See you!




March 25, 2014

Finally I can code on my way to work...

I have a Windows Phone and I love it. Sure, there are a bit fewer apps and in Sweden only one phone company has the Nokia 1520 as a phone of choice. The 1520 is a big phone, most people actually question if its a phone or a tablet when they see it.

For me that is a perfect size.

It barely slips down in my pocket and it is big enough to be used as a small tablet.
When I then discovered TouchDevelop a few weeks ago everything came together. I could finally do some serious coding on my phone!

So... what is TouchDevelop?

It is a programming language by Microsoft Research that lets you create software by clicking. It is made for developing by touch and it lets you use your programs on a windows phone, iPhone, iPad, android phone or tablet or on your PC.

What is it not?

Even though the tutorials use the LOGO-turtle it is not a simple language. TouchDevelop has a lot of power under the hood and it takes a while to get in to. You could use the language to do just about anything, but the more complex the task is the more you would wish that you made it in c# instead. It is simply a perfect tool for quick hacks or games that needs to run on your phone.


So over to the case:
I am a bird watcher and I travel a lot. To be able to recognize birds I need to learn their sounds. This is seriously boring and I usually end up with listening to a couple of songs and then giving up.
This time it should be more fun to learn sounds so I want to create a bird quiz-application on my phone that plays a sound and gives me a number of birds to choose from and in the end gives me a percentage on how many correct answers I made so I can be proud of the results.

Since I only have bird songs in my song list on my phone the first step would be to play a random song.

It is a simple task but it is something that still would take some time to do in a traditional language (c#).

In TouchDevelop this would look like this:

action main()
      var mysongs := media→ songs
      var chosensong := songs→random
      player→play(chosensong)
end action

Just run this and a random song. And all this by clicking on your phone.

To be continued...

October 28, 2013

Six degrees of Kevin Bacon featuring Quickgraph

If you don't know what a Bacon Number is you can look it up here.

The basic idea is to calculate between how many movies there are between Kevin Bacon and another actor, the higher the number the further away. It is a very geeky calculation, in fact it so geeky that it is a part of google. Just google [actor name] bacon number and...


So how would you do this yourself?

First off we will need some data.

I used this to create a movie database. Basically you get an Actor table, a Dvd table and a Dvd_Actor table to link them.

Next we will just have to loop through all the records and create nodes(vertices) for each actor and movie in the database.

I used quickgraph and a sinple class to keep the nodes:

    public class MovieInformationNode
    {
        public int Id { get; set; }
        public NodeTypes NodeType { get; set; }
        public string Name { get; set; }
        public string PresentationName
        {
            get
            {

                if (NodeType == NodeTypes.Actor)
                    return "Actor: " + Name;
                else
                    return "Movie: " + Name;
            }
        }
    }

I declared the graph as:

private UndirectedGraph<MovieInformationNode, Edge<MovieInformationNode>> movieGraph                   = new UndirectedGraph<MovieInformationNode, Edge<MovieInformationNode>>();

For each Actor and Dvd I created a node and inserted it into the graph:

                MovieInformationNode node = new MovieInformationNode();
                node.NodeType = NodeTypes.Movie; //or actor if it is an actor, enum to keep track of type
                node.Id = dvd.Id;
                node.Name = dvd.DVD_Title.Trim();
                movieGraph.AddVertex(node);

For each link in Dvd_Actor I found the nodes in the graph and added an edge between them:

                //find actor
                MovieInformationNode actorNode = movieGraph.Vertices.Where(s => s.Id ==                                                               performance.Id && s.NodeType == NodeTypes.Actor).First();
                //find movie
                MovieInformationNode movieNode = movieGraph.Vertices.Where(s => s.Id ==                                                         performance.dvdid && s.NodeType == NodeTypes.Movie).First();
                Edge<MovieInformationNode> edge = new Edge<MovieInformationNode>(actorNode,                                                                               movieNode);
                movieGraph.AddEdge(edge);

Then you just need to get the shortest path:

            Func<Edge<MovieInformationNode>, double> edgeCost = (edge => 1.0D); //no weights
            var tryPath = movieGraph.ShortestPathsDijkstra(edgeCost, sourceNode);
            IEnumerable<Edge<MovieInformationNode>> path;
            if (tryPath(destinationNode, out path))
            {
                foreach (var item in path)
           {
                    listFrom.Items.Add(item.Source);
                    listFrom.Items.Add(item.Target);
           }
            }

To get this working you will need to get quickgraph here.


October 19, 2013

Converting from an adjacency list to hierarchyid in SQL Server



So many of us have worked with hierarchies in SQL Server, and for those not used to the HierarchyId the most common approach was to create a table with a parent relation to it self.

Consider a company structure where the main company has underlying companies, sections, divisions etc in a hierarcical manor. Something like this:


  • Company
    • SectionA
      • Division1
      • Division2
    • SectionB
      • Division1
        • GroupA

The structure for representing this in a database using an adjacency list approach would be something like this:

CREATE TABLE [dbo].[Organization](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Parent] [int] NULL,
[Name] [nvarchar](255) NOT NULL)

With this structure you can find the children of node 4 by a simple: 

SELECT * FROM Organization WHERE Parent = 4

The problem with this structure is when you need to search for all descendants to a node. Then you would need to first make a SELECT * FROM Organization WHERE Parent = 4 and then for each underlying node search for their children and then their children and so on. 

Recursion complicates things, but recursion coupled with database calls can make things go very slow as well.

So in SQL Server from 2008 (old technology, still so few uses it) there is a special datatype for handling hierarchies, the hierarchyid.

The new organizational structure would be something like:

CREATE TABLE [dbo].[NewOrganization](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Hierarchy] [hierarchyid] NOT NULL,
[Name] [nvarchar](255) NOT NULL)

With this table you would be able to make queries such as:

DECLARE @ParentOrganization hierarchyid
SELECT @ParentOrganization = Hierarchy FROM NewOrganization
WHERE Id = 4

SELECT * FROM NewOrganization
WHERE Hierarchy .IsDescendantOf(@ParentOrganization ) = 1

Giving you the full subtree with only one call. Pretty neat.

So how do you get from the lousy adjacency list to the splendid hierachyid?

Well... given the two tables above (note that they are a bit pseudo-coded, no primary keys for example) a solution would be like this in c#.

To connect to the data base you would need a connection string to point out the correct type library:

    <add name="Organizations" connectionString="Type System Version=SQL Server 2012;Data Source=[database];Initial Catalog=[table];Integrated Security=True" /> see this for more info why and how.

Next up you need a mechanism for reading and writing the data to the database up to you if it's entity framework or something else. Note that you would need a reference to Microsoft.SqlServer.Types to use the hierarchyid from c#.

    public class NewOrganizationItem
    {
public Int32 Id { get; set; }
        public SqlHierarchyId Hierarchy { get; set; }
        public String Name { get; set; }
    }
    public class OrganizationItem
    {
        public Int32 Id { get; set; }
        public Nullable<Int32> Parent { get; set; }
        public String Name { get; set; }
    }

        private void ConvertTree()
        {
//Load all old organizationitems from the database
            List<OrganizationItem> items = OrganizationManager.SelectAll();
//Start the importing 
            InsertOrganizations(items, null, SqlHierarchyId.Null);
        }

We will need to keep track on three things when importing. The old organizations parentId and where it should be placed in the new hierarchy. For that we would need both the parent (new parent) and to keep track of the last child under it (lastSibling) so we can insert the new node after the last child node.

        private void InsertOrganizations(List<OrganizationItem> oldItems, int? parentId, 
                                                         SqlHierarchyId newParent)
        {
            SqlHierarchyId lastSibling = SqlHierarchyId.Null;
//loop through all children
            foreach (var item in oldItems.Where(s=>s.Parent == parentId))
            {
                NewOrganizationItem newItem = new NewOrganizationItem();
                newItem.Name = item.Name.Trim();
                if (parentId != null)
//if not a root item create it under its parent after the last sibling
                    newItem.Hierarchy = newParent.GetDescendant(lastSibling, SqlHierarchyId.Null);
                else
//create it under the root node
                    newItem.Hierarchy = SqlHierarchyId.GetRoot().GetDescendant(lastSibling, 
                                                                               SqlHierarchyId.Null);
//Insert it into the database and return the newly created item
                newItem = NewOrganizationManager.Insert(newItem);
                lastSibling = newItem.Hierarchy;
//recursively continue
                InsertOrganizations(oldItems, item.Id, newItem.Hierarchy);
            }
        }

June 7, 2013

Teched day 4

So... the last day at the conference and the first one where the queues for the really cheap Surfaces where accessible enough for me to go shopping.

I went through the news of Sql Server 2014, some Sqllite on Windows Phone and some DirectX-stuff in C++, but the best one today was about dependency injection and containers called "Understanding Dependency Injection and Those Pesky Containers" going through the basics of Castle Windsor, NInject, Unity etc and focusing on Mef by Miguel Castro

It was a nice overview of something I use but doesn't come natural for me. I think I will be going for Mef in the future after seeing this presentation.

Tonight we will party here:
(credits to Andrew Bishop)
Rumor has it that there will be some famous artist there... we will see.

[comment added] It was Tina Turner.

So... what have I learned during these four days?

  • Lightswitch can actually be useful.
  • OData is a tool in my toolbox that needs to get sharpened.
  • Stop being lazy and always use a dependency container. (read Mef)
  • Use Geoflow as much as possible.
  • Stop hiding behind the fact that I am lousy on UX and start doing something about it.
  • Americans are strange but almost always nice.

June 6, 2013

Teched day 3

A bit of an in-between day for me. Attended a few Windows Phone-lectures that didn't contain any news and went to a webapi/odata lecture that was a bit over my level. (did however make a note to self to learn more immediately)

The gem of the day was a lecture by Billy Hollis called Design or die about something that I've stubbornly been proclaiming the last few years. Applications today needs UI/UX design and those companies that wont provide this will slowly be put away from the face of the earth. You simply cannot have the usual design that programmers make (you know the ugly, cramped, hard to read, bad colour choices and no usability-style) alongside with the often fantastically looking apps in the app stores.

We have left the DOS-era and we have left the Windows XP-era... time to adapt!

I must admit that I am one of those programmers who make really ugly applications. I have blamed the fact that I was born without designing talents, which is true, but it is time to change that and acquire some skills.

So I bought this:
Supposedly "the" design book for developers.
Was supposed to have attended the community party today, but fell asleep at seven and just woke up now at three o clock. Will try to sleep some more now.

Good night.

June 5, 2013

Teched day 2

Not only a conference, but an opportunity to sell stuff too...

The weather in New Orleans is so hot that it feels like walking into a wall every time I leave the air conditioned safety of Hilton Riverside. It is such a hard life to be an IT consultant some days... ;)

I read about Microsoft LightSwitch when it just came out and thought:  MS Access applications.
And not in a flattering way.

I gave it a real chance today and went to a session with Beth Massi on creating HTML 5-based business apps with Azure and Visual Studio LightSwitch.
Developers usually scoff about LightSwitch, because, well, you hardly need to program to create something and, well, Developers are people who excel in just programming. I don't scoff anymore. Anything that can create a decently good looking data editor and browser with filters, paged data, a UI that scales to works on Android, IOS, Windows phone and on desktops and that can deploy this to Azure in a one hour session (including some CSS-changes, customization and third part JavaScript controls) is not to scoff at. Period.

Maybe I will not use LightSwitch in many projects, since I have a hunch that there is a point when high customization will make a LightSwitch project more expensive and harder to manage than using traditional coding methods and  customer needs usually means a lot of customization. BUT, for all my fast hobby projects where I need to fix something simple web-based as quick as possible or need a prototype or just a way to manage data online, LightSwitch at least seems perfect at a glance.

Note to self: Start testing LightSwitch!
LightSwitch was a nice acquaintance

Chris Klug held a talk about patterns and architecture in MVVM with a pragmatic approach on how to build stuff in the best way. Chris is good at that stuff and he held an appreciated session. For me it was the deepest in technical aspects so far this conference and packed with good ideas. Check out his blog here.

Good to show those Americans that Swedes know their stuff too... ;)

A swede in the US
Finally, the dominating crapgadgetgiveaway this year is this: (and it even flashes!)
Who would not want a hat like this?