Monday, 20 June 2016

Searching data in Elasticsearch using C#

To help beginners I decided to write the article with step by step approach using Elasticsearch with C#, since it is a NOSQL, distributed full text database. Which means that this database is document based instead of using tables or schema, we use documents… lots and lots of documents. I have written this article specially focusing on newcomers and anyone new wants to learn or thinking of using ES in their .NET program. This sample illustrates a way to let user search data from Elasticsearch from their app.


Work In Progress.

Overview:

This article covers 3 major aspects
·         What is Elasticseach?
·         Getting started with ES in Visual Studio
·         Perform some search operation using C#

What is Elasticsearch?

http://www.elasticsearch.org/
ElasticSearch is a distributed RESTful search engine built for the cloud. Features include:
·         Distributed and Highly Available Search Engine.
·         Each index is fully sharded with a configurable number of shards.
·         Each shard can have one or more replicas.
·         Read / Search operations performed on either one of the replica shard.
·         Multi Tenant with Multi Types.
·         Support for more than one index.
·         Support for more than one type per index.
·         Index level configuration (number of shards, index storage, …).
·         Various set of APIs
·         HTTP RESTful API
·         Native Java API.
·         All APIs perform automatic node operation rerouting.
·         Document oriented
·         No need for upfront schema definition.
·         Schema can be defined per type for customization of the indexing process.
·         Reliable, Asynchronous Write Behind for long term persistency.
·         (Near) Real Time Search.
·         Built on top of Lucene
·         Each shard is a fully functional Lucene index
·         All the power of Lucene easily exposed through simple configuration / plugins.
·         Per operation consistency
·         Single document level operations are atomic, consistent, isolated and durable.
·         Open Source under Apache 2 License.

Installing Elasticsearch

Installing Elastic Search on a Windows server

·         Pre-requisites:
·         Java Runtime Environment (JRE)http://www.oracle.com/technetwork/java/javase/downloads/index.html
·         After installing JRE, do yourself a favor and set the JAVA___HOME environment variable
·         My Computer -> Properties -> Advanced tab -> Environment variables button
·         Under System Variables, click Add New
·         Name: JAVA___HOME
·         Path: c:\progra~1\Java\jre7
·         Assumes Java JRE is installed at c:\program files\Java\jre[X]
·         You can download the Elasticsearch runtime from the Elasticsearch website and follow the standard installation instructions (it's really quite simple)
·         OR, if you'd like the Elasticsearch engine to run as a Windows service, you can download an installer from here: http://ruilopes.com/elasticsearch-setup/
·         Basically the installer just unzips the Elasticsearch package, then creates a Windows service wrapping the engine
·         Install to [DRIVE]:\Elasticsearch (avoid installing to the Program Files directory to help avoid UAC issues)
·         An Elasticsearch service will be created, but you may need to start the service manually (Administrative tools -> Services) and set it to startup automatically
·         Confirm Elasticsearch is running by browsing to: http://localhost:9200/_cluster/health
·         If you receive a JSON response with a property named "status" that has a value of "green" or "yellow", all systems are go.
·         By default, Elasticsearch listens on port 9200.
·         I like the Kibana for cluster/node/index monitoring - https://www.elastic.co/products/kibana
·         I also like the Sense plugin for Google Chrome for testing queries -https://chrome.google.com/webstore/detail/sense/doinijnbnggojdlcjifpdckfokbbfpbo
·         Another great client elasticsearch-head also good for monitoring cluster -https://mobz.github.io/elasticsearch-head/
·         Several other options/tools available here: http://www.elasticsearch.org/guide/clients/
·         Scroll to the "Health and Performance Monitoring" and "Front Ends" sections

ElasticSearch-with-Csharp

ElasticSearch with C#
Example project for using Elasticsearch with C#. This is a autosearch feature demonstration in Elasticsearch using C#.NET. User cansearch any name by typing its first character. Example for searching user "Abby" jusy type A and it will list all the name that has A in it.

Getting Started

Download NEST package using the below command and then run the program. You can learn more about Elasticsearch.NET & NEST here.
PM> Install-Package NEST

Sample Data

You could use the attached data in the project folder and do a bulk insert into ES or you can use your own data. If you use you own data please change the index name in the Form1.cs code to your index name and type to your type name. Also you need to update the getter and setter.

Sample code will be look like as follows

C#
using Nest; 
using System; 
using System.Windows.Forms; 
 
namespace ESsearchTest 
{ 
    public partial class Form1 : Form 
    { 
        ConnectionSettings connectionSettings; 
        ElasticClient elasticClient; 
 
        public Form1() 
        { 
            InitializeComponent(); 
        } 
 
        private void Form1_Load(object sender, EventArgs e) 
        { 
            //Establishing connection with ES 
            connectionSettings = new ConnectionSettings(new Uri("http://localhost:9200/"));
 //local PC             
            elasticClient = new ElasticClient(connectionSettings); 
        } 
 
        //Get suggestion under search textbox 
        private void tbxName_TextChanged(object sender, EventArgs e) 
        { 
            //Search query to retrieve info 
            var response = elasticClient.Search<disney>(s => s 
                .Index("disney") 
                .Type("character") 
                .Query(q => q.QueryString(qs => qs.Query(tbxName.Text + "*")))); 
 
            AutoCompleteStringCollection collection = new AutoCompleteStringCollection(); 
            foreach (var hit in response.Hits) 
            { 
                collection.Add(hit.Source.name); 
            } 
 
            tbxName.AutoCompleteSource = AutoCompleteSource.CustomSource; 
            tbxName.AutoCompleteMode = AutoCompleteMode.Suggest; 
            tbxName.AutoCompleteCustomSource = collection; 
 
 
 
            if (tbxName.Text == "") 
            { 
                rtxSearchResult.Clear(); 
            } 
        } 
 
        private void tbxName_KeyPress(object sender, KeyPressEventArgs e) 
        { 
            if (e.KeyChar == '\b') 
            { 
                rtxSearchResult.Clear(); 
            } 
        } 
    } 
} 




Technicalities:

The application retrieves all names from Elasticsearch. That means that if a name didn't create in the index that information will not show.
Note
·         For more about query DSL please see this page Query DSL
·         More about Elasticsearch visit website


Tuesday, 14 June 2016

The Top 10 Mistakes That KnockoutJS Developers Make

Introduction

Knockout is a popular JavaScript framework that offers convenient data binding functionality without the complexity of similar frameworks such as Angular. It's a great choice for prototyping small applications or introducing data binding into a legacy codebase. This article captures a number of common Knockout pitfalls I've run into over the past few years deploying Knockout code in production. Hopefully it'll save you a headache or two!
Note: All the code in this article can be found on GitHub. Some modifications have been made to examples that contain HTML files so that you can run them in your browser, but the important parts are all the same. If you notice errors in any of the code, please ping me on twitter @fivethirtyam or make a pull request to the GitHub repo.

1 Modules

Unlike other UI frameworks, Knockout does not come with a built in way to modularize your application. It's possible to write an entire Knockout app in a single HTML file:
    <html>
        <head>
            <title>My Bad App</title>
            <script type="text/javascript" src="knockout.js"></script>
        </head>
        <body>
            <span data-bind="text: message"></span>
            <script type="text/javascript">
                function ViewModel() {
                    this.message = ko.observable("This is bad!");
                }
                ko.applyBindings(new ViewModel());
            </script>
        </body>
    </html>
While this runs, it definitely won't scale to applications of any significant complexity. The official Knockout docs suggest using RequireJS for Asynchronous Module Definition (AMD), and I wholeheartedly second this recommendation. Using RequireJS and the domReady module, the above code refactors into three separate files.
Good.html:
    <html>
        <head>
            <title>My Good App</title>
            <script type="text/javascript" data-main="main.js" src="require.js"></script>
        </head>
        <body>
            <span data-bind="text: message"></span>
        </body>
    </html>
main.js:
    require(['knockout', 'viewModel', 'domReady!'], function(ko, viewModel) {
        ko.applyBindings(new viewModel());
    });
viewModel.js:
    define(['knockout'], function(ko) {
        return function viewModel() {
            this.message = ko.observable("This is good!");
        }
    });

2 var self = this;

Keeping track of this in Knockout can be tough. Setting var self = this; at the top of every view model makes it easy.
For example, if var self = this; is not set then this must be passed into every computed observable:
    function viewModel() {
        this.cat = ko.observable("cat");
        this.pants = ko.observable("pants");
        this.catpants = ko.computed(function() {
            return this.cat() + this.pants();
        }, this);
    }
Forgetting to pass in this is easy to do and can result in hard to track down bugs. Ifvar self = this; is set then passing this is not necessary:
    function viewModel() {
        var self = this;

        self.cat = ko.observable("cat");
        self.pants = ko.observable("pants");
        self.catpants = ko.computed(function() {
            return self.cat() + self.pants();
        });
    }
var self = this; can also help avoid bugs when one binding context refers to another. Consider the following code that displays a list of names. When a user clicks on an name in the list, that name is displayed in the <span> below.
HTML:
    <ul data-bind="foreach: people">
        <li data-bind="click: $parent.selectPerson, text: name"></li>
    </ul>

    <!-- ko if: selectedPerson -->
        <span data-bind="text: selectedPerson().name"></span>
    <!-- /ko -->
JavaScript:
    function viewModel() {
        var self = this;

        self.people = [
            {
                name: "Mike"
            },
            {
                name: "Sara"
            },
            ...
        ];

        self.selectedPerson = ko.observable();
        self.selectPerson = function() {
            // this = the object in people corresponding to the name clicked on
            self.selectedPerson(this);
        };
    }
When selectPerson is called its scope is set to the object in person corresponding to the name clicked. However, because var self = this; is set the view model object is still accessible within the event callback. This would not be the case otherwise.
In production code I almost always define var self = this;. However, for the sake of brevity, I won't use it in some examples in this article.

3 Logic in templates

Knockout makes it easy to write complicated logic in HTML templates. Avoid doing this at all costs! It results in difficult to test and maintain code. Instead of using logic in templates...
    <span data-bind="text: firstName() + ' ' + lastName()"></span>
    function viewModel() {
        this.firstName = ko.observable("Mike");
        this.lastName = ko.observable("Mellenthin");
    };
...push all logic into computed observables:
    <span data-bind="text: fullName"></span>
    function viewModel() {
        var self = this;

        self.firstName = ko.observable("Mike");
        self.lastName = ko.observable("Mellenthin");
        self.fullName = ko.computed(function() {
            return self.firstName() + ' ' + self.lastName();
        });
    };

4 Testing

Speaking of testing, by default Knockout offers no tools to help you. This does not mean you shouldn't write tests! There are ample JS testing frameworks, and you should be able to pick up and drop any of them into your Knockout application. As with anything, the earlier you start writing tests the better. I usually don't start a new Knockout project without also including a testing framework.

5 ko.mapping

ko.mapping is a plugin for Knockout that makes working with data fetched from REST endpoints much more enjoyable.
Without ko.mapping, a view model that consumes objects from a REST API might look like this:
    function viewModel() {
        /*
        * Gets data about a person from the server:
        * person = {
        *   firstName: "John",
        *   lastName: "Stewart"
        * }
        */
        var person = getPersonFromServer();

        this.person = {};
        this.person.firstName = ko.observable(person.firstName);
        this.person.lastName = ko.observable(person.lastName);
    }
With ko.mapping the view model is much simpler:
    function viewModel() {
        var person = getPersonFromServer();
        this.person = ko.mapping.fromJS(person);
    }
Want to convert part of the view model back to plain JSON so that you can POST it back to the API? That's a one-liner too:
    var json = ko.mapping.toJS(this.person);
While ko.mapping is to some degree officially part of Knockout (it's in the official documentation), it is a separate project that you'll have to download and include.
It's also worth nothing that some people prefer the functionally analogousko.viewModel plugin to ko.mapping. ko.mapping has always worked fine for me, but it only seemed fair to link to both. Use one or the other, but don't use neither!

6 textInput and valueUpdate

This may seem minor, but it's caused me so many headaches that it's worth including. Knockout binds the value of input elements a somewhat strange way. To illustrate, let's say we have an input element and want to update some text on the page in real time as the input's value changes:
    <input type="text" data-bind="value: myValue">
    Value: <span data-bind="text: myValue"></span>
    function viewModel() {
        this.myValue = ko.observable();
    }
Surprisingly, the above won't work. The myValue observable (and thus our text in the span) updates whenever the input loses or gains focus, not as it's value changes. Why? For performance reasons this is how Knockout behaves by default.
To fix this in Knockout 3.2 (current at the time of writing) or newer, use the textInput binding instead of the value binding.
    <input type="text" data-bind="textInput: myValue">
This will provide immediate updates to myValue with the minor caveat that it won't guarantee that the value attribute of the input is always synced with myValue.
If you are using an older version of Knockout or if you are dead set on using the value binding, then you must use the valueUpdate flag.
    <input type="text" data-bind="value: myValue, valueUpdate='afterkeydown'">
In Knockout 3.2 there are 4 possible values for valueUpdate, each with its own idiosyncrasies:
  • + input - Updates when the value of the element changes. Doesn't work in IE8-.
  • + keyup - Updates when a keyup event is fired
  • + keypress - Updates when a keypress event is fired.
  • + afterkeydown - Updates as soon as the user starts typing a character. Does not work on all mobile browsers -- notably Safari on IOS7.
Using the textInput binding is strongly recommended over using the valueUpdateflag.

7 Don't repeatedly push into observable arrays

Pushing multiple times into observable arrays can cause significant performance issues with your application:
    function viewModel() {
        var arr = [0, 1, ..., 999];

        this.numbers = ko.observableArray();

        for (var i = 0; i < arr.length; i++) {
            this.numbers.push(arr[i]);
        }
    }
Running the for loop above will cause Knockout to redraw the page 1000 times -- one for each push. To avoid this, simply overwrite the old value of our entire array:
    function viewModel() {
        var arr = [0, 1, ..., 999];
        this.numbers = ko.observableArray(arr);
    }
To transform data before putting it into our new array, use ko.utils.arrayMap.
    function Number(number) {
        this.number = number;
    }

    function viewModel() {
        var arr = [0,1, ..., 999];

        // creates an array of Number objects
        this.numbers = ko.observableArray(ko.utils.arrayMap(arr, function(number) {
            return new Number(number)
        }));

    }
To append many items to an existing observable array, exploit the fact that pushaccepts a variable number of arguments and use apply to push them in all at once.
    function viewModel() {
        var arr = [500, 501, ... 999];

        this.numbers = ko.observableArray([0, 1, ..., 499]);
        this.numbers.push.apply(self.numbers, arr);
    }

8 Observable arrays don't automatically have observable members

Observable arrays track changes to which objects are in the array. They do not track changes to the state of those objects.
    <ul data-bind="foreach: people">
        <li data-bind="text: name"></li>
    </ul>
    <button data-bind="click: makeDerekMike">Make Derek Mike</button>
    function viewModel() {
        var self = this;

        self.people = ko.observableArray([
            {
                name: 'Derek',
            },
            {
                name: 'Sara'
            },
            ...
        ]);

        self.makeDerekMike = function() {
            for (var i = 0; i < self.people().length; i++) {
                if (self.people()[i].name === 'Derek') {
                    self.people()[i].name = 'Mike';
                }
            }
        };
    }
Clicking the button in the first example will not trigger a page refresh despite the fact that it will modify an object in the array underlying people. This is because the same objects still belong topeople. To trigger a page refresh, we need to explicitly make the fields of the elements in people observable:
    function viewModel() {
        var self = this;

        self.people = ko.observableArray([
            {
                name: ko.observable('Derek')
            },
            {
                name: ko.observable('Sara')
            },
            ...
        ]);

        self.makeDerekMike = function() {
            for (var i = 0; i < self.people().length; i++) {
                if (self.people()[i].name() === 'Derek') {
                    self.people()[i].name('Mike');
                }
            }
        };
    }

9 Components

Because Knockout makes building interactive widgets so simple, it's easy to write similar code in different parts of your application. Use Knockout components to abstract common UI widgets and promote code reuse.
Using components, we can build a simple reusable list builder as follows:
    <span>This is a list with no initial values</span>
    <div data-bind="component: 'list-builder'"></div>

    <span>This is a list with some initial values</span>
    <div data-bind="component: {
        name: 'list-builder',
        params: { list: ['item', 'another item'] }
    }"></div>
    function Item(text) {
        this.text = text;
    }

    ko.components.register('list-builder', {
        viewModel: function(params) {
            var self = this;

            self.list = ko.observableArray([]);

            if (params && params.list) {
                self.list(ko.utils.arrayMap(params.list, function(item) {
                    return new Item(text);
                }));
            }

            self.newText = ko.observable();
            self.add = function() {
                self.list.push(new Item(text));
                self.newText('');
            };
        },
        template:
            '<ul data-bind="foreach: list">' +
                '<li data-bind="text: text"></li>' +
            '</ul>' +
            '<input type="text" data-bind="textInput: newText" />' +
            '<button data-bind="click: add">Add</button>'
    });
Note that you probably don't want to inline the viewModel and template as above in any production code code. Fortunately, this can be solved using require.js (see #1). For a description of how to do this check out the official components documentation.

10 Tutorials

This sounds like a cop out given that I just wrote a Knockout guide of sorts, but if you're new to Knockout the official tutorials are great! They offer a interactive sandbox to play around with the framework in a guided fashion. They helped me a ton when I was first starting out and hopefully they'll help you too. And if you're still confused, well, there's always AirPair.

Angular Tutorial (Update to Angular 7)

As Angular 7 has just been released a few days ago. This tutorial is updated to show you how to create an Angular 7 project and the new fe...