Friday, August 22, 2014

Android app development start up with Xamarin + C#



When I get to know the about Xamarin , following questions are popping up in my mind. I believe, right now in your mind, same questions are floating in gray cell area. Let’s try to have a brief over view.

Why?
Android app development industry is booming now. That means the market requirement is getting very high. When a development industry grows, it needs more developer. To fill the gap experienced developer need to shift their technical domain. It’s a very challenging situation when a set of developer need to develop a new skill quick and do it efficiently. After working years with a development environment and language, it takes some time span to do the shift. As an example, when a c# developer need to shift from c# and visual studio to Eclipse and java for android development , it is definitely not a smooth transition for them and also require some time. Xamarin is basically is the answer to it.

How it is helpful?
Xamarin provides a development environment which is just same as c# development environment for android app development. Not only android but also iPhone, and windows app can be developed using Xamarin. And the best thing is reusable code. The same code can be used in iPhone, android, windows phone, as we are using Xamarin.
Basically normal c# code is running on its own Mono (.net) framework on the top of android os and talking with hardware. Mono framework officially release in 2004 for linux. Mono is nothing but .net for the environment other than windows.
Java libraries or existing code also can be imported using c# binding. It is really awesome to have this feature. We can use any existing java library created for Android native environment.  Java code will be wrapped by c# code to use in c# Xamarin development. To build android app, we may need access to java widget and sdk. We can expose those using bindings. It will expose any java class or library as per needed. We can use these classes in c# code just as in c# itself. Awesome. J

How it works?
It acts like almost desktop app development for c#.  The compiler is producing IL (Intermediate Language), then package that IL in apk. The apk is running on top of .net mono framework which runs over Andrid os. There is no java involvement in deployment. It runs over Mono and Delvik runtime, which runs parallel in android os. Other things like- view, resources, manifest are maintained as in android native development. These are the simple self explanatory xml files. I will not talk about android development here. Please refer to android development tutorial blogs- http://www.xoriant.com/blog/?s=android+basics

Ok, enough. Now give it a try.

Setting up development environment
Download latest Xamarin from http://xamarin.com and install it.  After you finish, you will get free GUI xamarin studio and visual studio integrated development environment. You can use any of them. Xamarin studio is free, almost feels like visual studio and has intellisense also. If you have visual studio licence, you can use visual studio flawlessly. To run & test the app in simulator you need to use ADT. You can create a virtual device using Android virtual device manager. But it is slower than you can imagine. You can also use third parties, like- Genymotion (faster, but not freeL )

 
Let’s create a project using following instruction-

Open Xamarin studio.


Fellow these steps: File -> New -> Solution
Select Android Application as shown bellow. Provide suitable name to the project and path to save.


 





After saving project, you will get a first view of code, which is basically associated with the views

in xml in “resource/layout” folder. It (MainActivity.cs) is inherited from activity which acts like view controller, just as in android. 
Now as you can see, the code is pretty simple. It is basically associating a click event to a button on view creation time, and printing the number of clicks on the button itself. Run the above code by clicking Run (>) button to see the actual effect on simulator. 

The stage is set for you to play around.  

So you are ready to go further. Create your own native apps using Xamarin.

Further study & ref: 
·         http://api.xamarin.com/
·         http://developer.xamarin.com/samples/android/all/
·         http://www.genymotion.com/

Monday, February 17, 2014

MongoDB with MVC4 Web-API C#

Mongo db is a document oriented database. Mongo db has a free and commercial version. It is scalable, open source and document oriented. All Nosql db are document oriented mostly.  Main data base types are RDBMS, OLAP & NoSql. NoSql db are for Big data store and faster access. It is scalable. Scalable means db can be stored in commodity computers, so NoSql databases is horizontal scalable. (Hadoop).

NoSql has mainly 3 types-
1>Key-Value, 2> Tabular, 3> Document Oriented. Mongo is document oriented NoSql Db. NoSql does not have relations. It does not support complex database. But the features are there is - Fast Performance, Query-able, scalable.  In brief, NoSql is for performance, RDBMS is for functionality, though it is not cent right from all aspects.
In case of Mongo, collections are same as tables in RDBMS. Table has recorded in row. But in mongodb stores document (BSON) in collection.

Example-
{_id:”123”, name:”subhadip”,address:”agarpara”},{_id:”124”,name:”nemo”,addresses:[{address:”add1”},{address:”add2”}]}

You can see an unstructured data collection.

Now , query to extract data from collection is there in No-Sql.
Example- db.employee.find({name:”subhadip”});

Indexing is possible in MongoDB. Ad hoc queries like- search by field, regular expression can be used. Distributed database supported in mongodb. Load-balancing is a build in feature. Mongodb has file storage functions available (GridFS). Aggregation in MongoDB is possible using map reduce. Mongo db understands longitude and latitude in its own. For business logics no need to convert record to object, it is already structured as object in code.

It supports almost all popular OS (Windows, Linux, Mac, etc).

Now lets jump to code using MVC 4, C#, MongoDriver.
Create a db in mongo called company and it should have a collection -employees.[_id,Name,Address](_id will be auto generated).
Create DB Command- >use Company (enter)
Create Collection Command->  db.Employees.insert({Name:'Subha',Address:'agarpara;}) (enter)

Install MongoC#Driver from Add Libary Package Reference. 
Ok, Lets start coding.
First , Create Model-
    public class Employee
    {
        [ScaffoldColumn(false)]
        [BsonId]
        public ObjectId EmpId { get; set; }

        [ScaffoldColumn(false)]
        public string Name { get; set; }

        [ScaffoldColumn(false)]
        public string Address { get; set; }
    }

Now , Create MongoDBContext-
public class MongoDBCS
    {
        public MongoDatabase db;
        public MongoDBCS()
        {
            var con =
                new MongoConnectionStringBuilder(ConfigurationManager.ConnectionStrings["MongoDBString"].ConnectionString);

            var server = MongoServer.Create(con);
             db = server.GetDatabase(con.DatabaseName);
        }

        public MongoCollection<Employee> Employees
        {
            get
            {
                return db.GetCollection<Employee>("Employees");
            }
            set { }
        }

    }

Now, Create controller(API)-
public class EmployeeController : ApiController
    {
        private MongoDBCS MongoContext;

        public  EmployeeController()
        {
            MongoContext = new MongoDBCS();
        }
        // GET api/employee
        public IEnumerable<Employee> Get()
        {
         
            var el = MongoContext.Employees;
            return el.FindAll();
        }

     

        // POST api/employee
        public void Post(Employee emp)
        {
            var el = MongoContext.Employees;
            el.Save(emp);
        }


        // DELETE api/employee/5
        public void Delete(string name)
        {
            var el = MongoContext.Employees;
            el.Remove(Query.EQ("Name", name));
        }
    
    }

Web.config will have db connection string –
<add name="MongoDBString" connectionString="server=127.0.0.1;database=company" />

That’s it.Now, You know how to work with MongoDB and C# MVC4.


Saturday, February 8, 2014

Knockout Js Quick Start



Knockout js is a Javascript library which follows MVVM. It interacts or binds model with dom(view) element using ViewModel.  Now through this we can bind text, events, conditions and iterators(loop). The syntax is- data-bind=”<kind of binding> :<scope param>.  

 Example-
   <span data-bind="text: name"></span>

Another example-
   <div data-bind="if: address!=''"><span data-bind="text: address"></span></div>

Here, a conditional data binding is happening and under it, another text binding shown.

Now, let have a bit more in to it. It will cover few real scenarios-

HTML
   <div id="div_test">
    <ul data-bind="foreach: products"><!--scope starts-->
        <li><label data-bind="text: $index" ></label>&nbsp; <!--shows index count-->
            <span data-bind="text: name"></span>&nbsp;<!--conditional binding template starts-->
            <div data-bind="ifnot: rate > 20"><span data-bind="text: rate"></span></div>
            <div data-bind="with:plot">
                <span data-bind="text: width + '-' +height"></span></div> 
            <a data-bind="attr: {href:'#/'+name}" >click</a>          
            <div data-bind="if: address!=''"><span data-bind="text: address"></span></div>
        </li>

<!--conditional binding template starts-->
     </ul>
<!--scope ends-->
     <button data-bind="click: onclick">Click</button><!--event binding-->
   </div>


 Javascript

function scope(){
    var $scope=this;

//Json binding---->
    $scope.products=[{name:"test",

                                   address:"agarpara",
                                   rate:22,
                                   plot:{width:1110,height:800}
                                 },               
                                {name:"test2",
                                  rate:18,
                                  plot:{width:1500,height:600}}];
//Event binding------>
    $scope.onclick=function(){
        alert("Clicked");
    };
}
ko.applyBindings(new scope(),document.getElementById("div_test"));//apply a scope by a dom id


Few more working examples are in here