Xamarin with MongoDB

This application is developed in Visual Studio 2015.

If you want to install Xamarin and MongoDB, then please use the following procedure.

  1. Download and install Xamarin.
  2. Download and install MongoDB

First, create a Web API project to interact with MongoDB and Xamarine App.

Add one Class Library project to implement the MongoDB interaction.

web application

Add MongoDB driver packages using Nuget Packages

nuget

Now you are able to see the reference DLL related to MongoDB

MongoDB

1. Create one class MongoHelper.

  1. public class MongoHelper<T> where T : class  
  2. {  
  3.     public MongoCollection<T> Collection { getprivate set; }  
  4.   
  5.     public MongoHelper()  
  6.     {  
  7.         var con = new MongoConnectionStringBuilder("server=127.0.0.1;database=galary");  
  8.   
  9.         var server = MongoServer.Create(con);  
  10.         var db = server.GetDatabase(con.DatabaseName);  
  11.         Collection = db.GetCollection<T>(typeof(T).Name.ToLower());  
  12.     }  

This class is for creating a connection to MongoDB.

2. Create one class MobileService.

This class actually has the CRUD logic implementation to interact with MongoDB.

  1. public class MobileService  
  2. {  
  3.     private readonly MongoHelper<Mobile> _mob;  
  4.   
  5.     public MobileService()  
  6.     {  
  7.         _mob = new MongoHelper<Mobile>();  
  8.     }  
  9.   
  10.     public void Create(Mobile mob)  
  11.     {  
  12.         _mob.Collection.Save(mob);  
  13.     }  
  14.   
  15.     public void Edit(Mobile mob)  
  16.     {  
  17.         _mob.Collection.Update(  
  18.             Query.EQ("_id", mob.MobileID),  
  19.             Update.Set("Name", mob.Name)  
  20.                 .Set("Details", mob.Details));  
  21.     }  
  22.   
  23.     public void Delete(ObjectId postId)  
  24.     {  
  25.         _mob.Collection.Remove(Query.EQ("_id", postId));  
  26.     }  
  27.   
  28.     public IList<Mobile> GetMobiles()  
  29.     {  
  30.         return _mob.Collection.FindAll().ToList();  
  31.     }  
  32.   
  33.     public Mobile GetMobile(ObjectId id)  
  34.     {  
  35.         var mob = _mob.Collection.Find(Query.EQ("_id", id)).Single();  
  36.   
  37.         return mob;  
  38.     }          
  39. }

3. The class Mobile is the model for the data interaction.

  1. public class Mobile  
  2. {  
  3.    [BsonId]  
  4.    public Guid ID { getset; }  
  5.    public int MobileID { getset; }  
  6.    public string Name { getset; }  
  7.    public string Details{ getset; }  
  8. }

4. Use the following code to add a new item.

  1. serv.Create(new Mobile { ID= Guid.NewGuid(), MobileID = 1, Name = "Apple", Details = "Testing Application" }); 

5. Using this code you can retrieve all the data records from MongoDB.

  1. var datalst = serv.GetMobiles(); 

For testing the application first start the MongoDB service on your local system.

The following is the procedure to start with MongoDB.

Go to a command prompt snd enter:

C:\MongoDB\bin>mongod

The press Enter. Then the MongoDB service is started.

Here's the screenshot.

Adding Xamarin Project

Add a Xamarin project to the solution.

blank app

Now you can see the Xamarin project has been added to the solution:

program code

When the Xamarin application is running absolute file you will be able to see the following screen.

output

Now we can call the WebAPI from the Xamarin application.

Here's the code that is calling the WPI from Xamarin code:

  1. [Activity(Label = "AndroidApp1", MainLauncher = true, Icon = "@drawable/icon")]  
  2. public class MainActivity : Activity  
  3. {  
  4.     int count = 1;  
  5.   
  6.     internal Task<JsonValue> JsonObject { getprivate set; }  
  7.   
  8.     protected override void OnCreate(Bundle bundle)  
  9.     {  
  10.         base.OnCreate(bundle);  
  11.           
  12.         SetContentView(Resource.Layout.Main);  
  13.                       
  14.         string url = "http://localhost/MobileGalaryWeb/API/values";  
  15.         var request = HttpWebRequest.Create(url);  
  16.                       
  17.         request.ContentType = "application/json";  
  18.         request.Method = "GET";  
  19.         Button button = FindViewById<Button>(Resource.Id.MyButton);  
  20.           
  21.   
  22.         button.Click += delegate {  
  23.             //button.Text = string.Format("{0} clicks!", count++);  
  24.             using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)  
  25.             {  
  26.                 if (response.StatusCode != HttpStatusCode.OK)  
  27.                     Console.Out.WriteLine("Error fetching data. Server returned status code: {0}", response.StatusCode);  
  28.                 using (StreamReader reader = new StreamReader(response.GetResponseStream()))  
  29.                 {  
  30.                     var content = reader.ReadToEnd();  
  31.                     if (string.IsNullOrWhiteSpace(content))  
  32.                     {  
  33.                         Console.Out.WriteLine("Response contained empty body...");  
  34.                     }  
  35.                     else  
  36.                     {  
  37.                         Console.Out.WriteLine("Response Body: \r\n {0}", content);  
  38.                     }  
  39.                     button.Text = string.Format(content);  
  40.                     //Assert.NotNull(content);  
  41.                 }  
  42.             }  
  43.         };  
  44.     }          
  45. }