Sony Arouje

a programmer's log

Posts Tagged ‘json

simdb a simple json db in GO

leave a comment »

Some days ago I decided to learn GO. GO is pretty easy to learn and could learn syntax and semantics in couple of hours. To completely learn a language I normally write a small app in that language. So in my free time, I rewrote the expense service created in nodejs to GO and is now live and we are using it. This whole exercise allow me to learn GO in detail.

For me GO looks to be a great simple language with static type checking. Seems like I will be using GO for my future RPi projects than nodejs. In RPi more often I use a simple json as a db to store, retrieve and update execution rules, Sensor details, etc. In nodejs I use tingodb, couldn’t find some thing very similar in GO, so decided to write one, and is called simdb, a simple json db.

Using simdb I can persist stuct or retrieve or update or delete them from the json db. The db file created by simdb is a simple json file. Let’s see some of the functions in simdb.

 

Create a new instance of db

driver, err:=db.New("customer")

Insert a new Customer to db

customer:=Customer { CustID:"CUST1", Name:"sarouje", Address: "address", Contact: Contact { Phone:"45533355", Email:"someone@gmail.com", }, } err=driver.Insert(customer) if(err!=nil){ panic(err) }

Get a Customer

var customerFirst Customer err=driver.Open(Customer{}).Where("custid","=","CUST1").First().AsEntity(&customerFirst) if(err!=nil){ panic(err) }

Update a customer

customerFirst.Name="Sony Arouje" err=driver.Update(customerFirst) if(err!=nil){ panic(err) }

Delete a customer

toDel:=Customer{ CustID:"CUST1", } err=driver.Delete(toDel) if(err!=nil){ panic(err) }

Update and Delete operation uses the ID field of the struct to perform it’s operation.

 

Let’s see the full code.

package main import ( "github.com/sonyarouje/simdb/db" "fmt" ) type Customer struct { CustID string `json:"custid"` Name string `json:"name"` Address string `json:"address"` Contact Contact } type Contact struct { Phone string `json:"phone"` Email string `json:"email"` } //ID any struct that needs to persist should implement this function defined //in Entity interface. func (c Customer) ID() (jsonField string, value interface{}) { value=c.CustID jsonField="custid" return } func main(){ fmt.Println("starting....") driver, err:=db.New("dbs") if(err!=nil){ panic(err) } customer:=Customer { CustID:"CUST1", Name:"sarouje", Address: "address", Contact: Contact { Phone:"45533355", Email:"someone@gmail.com", }, } //creates a new Customer file inside the directory passed as the //parameter to New(). If the Customer file already exist //then insert operation will add the customer data to the array err=driver.Insert(customer) if(err!=nil){ panic(err) } //GET ALL Customer //opens the customer json file and filter all the customers with name sarouje. //AsEntity takes an address to Customer array and fills the result to it. //we can loop through the customers array and retireve the data. var customers []Customer err=driver.Open(Customer{}).Where("name","=","sarouje").Get().AsEntity(&customers) if(err!=nil){ panic(err) } // fmt.Printf("%#v \n", customers) //GET ONE Customer //First() will return the first record from the results //AsEntity takes the address to Customer variable (not an array pointer) var customerFirst Customer err=driver.Open(Customer{}).Where("custid","=","CUST1").First().AsEntity(&customerFirst) if(err!=nil){ panic(err) } //Update function uses the ID() to get the Id field/value to find the record and update the data. customerFirst.Name="Sony Arouje" err=driver.Update(customerFirst) if(err!=nil){ panic(err) } driver.Open(Customer{}).Where("custid","=","CUST1").First().AsEntity(&customerFirst) fmt.Printf("%#v \n", customerFirst) // Delete toDel:=Customer{ CustID:"CUST1", } err=driver.Delete(toDel) if(err!=nil){ panic(err) } }

TODO

The query syntax in simdb is not really great, I need to find a better approach.

 

Source Code: https://github.com/sonyarouje/simdb

Advertisements

Written by Sony Arouje

August 6, 2018 at 2:30 pm

Posted in GO

Tagged with , , ,

Bind JSON REST result using Knockout

leave a comment »

Last couple of hours I was trying to bind json data from a WCF service to a simple HTML UI using Knockout js. This is a very simple application I created to learn Knockout. This application is also a tracer to test  whether I can bind json result from the service directly to the UI, without creating an elaborate javascript view model at the client side. In real world services returns complex json, so it’s not possible to create the same model at the client side.

ko.mapping

Knockout provides mapping as a plugin, you can see more details here. Please  go through the link before you proceed.

So let’s see how I created my view model and the html UI.

I created a js file named customerviewmodel.js and added the  below code.

function customerViewModel() {
    var self = this;

    self.customerList = ko.observableArray();

    self.getCustomers = function () {
        $.ajax({
            type: 'GET',   
            url: 'http://10.0.0.2:8081/CustomerService/customers',
            contentType: "application/javascript",
            dataType: "jsonp",
            success: function(data) {
                var observableData = ko.mapping.fromJS(data);
                var array = observableData();
                self.customerList(array);
            },
            error:function(jq, st, error){
                alert(error);
            }
        });
    };
}

$(document).ready(function () {
    ko.applyBindings(new customerViewModel());
});

And the html UI. For this tracer app, I created a MVC4 web application and removed all the html code from the Views/Home/index.cshtml and replaced it with the below code.

<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/knockout-2.2.0.debug.js"></script>
<script src="~/Scripts/knockout.mapping-latest.debug.js"></script>
<script src="~/MyScripts/customerviewmodel.js"></script>

<table>
    <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
        </tr>
    </thead>
    <tbody data-bind="foreach: customerList">
        <tr>
            <td data-bind="text: Id"></td>
            <td data-bind="text: Name"></td>
        </tr>
    </tbody>
</table>
<br/>

<input type="button" id="btnGetCustomers" value="Get Customers" data-bind="click: getCustomers">

 

customerList is a ko.observablearray and the data will get filled when the user clicks the button. I was able to call the WCF  REST api and get the json but unable to populate customerList or show the data to the  UI.  I fixed the issue with the  help of a post from Stackoverflow, see the code snippet below.

 

            success: function(data) {
                var observableData = ko.mapping.fromJS(data);
                var array = observableData();
                self.customersResult(array);}
WCF Configuration changes

As you can see, my WCF REST service is running in a different machine, and when I do an ajax call with datatype:json I am getting some errors. After some googling I came to know that I have to call the service with datatype:jsonp. So I changed it to jsonp and started getting the below error.

 

jQuery18206380491638767738_1396378264364 was not called

 

So I modified the  WCF service configuration as shown below to work with jsonp request.

 

    <bindings>
        <webHttpBinding>
          <binding name="webHttpBindingJson" crossDomainScriptAccessEnabled="true" />
        </webHttpBinding>    
    </bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServicesBehavior">
           <serviceMetadata httpGetEnabled="true"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="webby">
          <webHttp helpEnabled="true" />
        </behavior>
      </endpointBehaviors>
    </behaviors>

I configured the service as shown below. I use a custom hosting, so need to provide baseaddresses.

    <services>
      <service name="WCFRestTest.Services.CustomerService" behaviorConfiguration="ServicesBehavior">
        <host>
          <baseAddresses>
            <add baseAddress="http://10.0.0.2:8082/CustomerService/Details"/>
          </baseAddresses>
        </host>
        <endpoint name="customerServiceRest" address="http://10.0.0.2:8081/CustomerService" 
               bindingConfiguration="webHttpBindingJson" binding="webHttpBinding" 
               contract="WCFRestTest.Services.ICustomerService" behaviorConfiguration="webby"/>
      </service>
    </services>

 

After this WCF configuration changes I could able to get json from the REST  api and bind the result to html UI using Knockout.

Let me know if you have any questions.

 

Happy coding…

Written by Sony Arouje

April 2, 2014 at 12:46 am

Posted in JavaScript

Tagged with , , ,

%d bloggers like this: