Advertisement
Guest User

Untitled

a guest
Mar 16th, 2015
266
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 8.54 KB | None | 0 0
  1. using Couchbase.Lite;
  2. using Couchbase.Lite.Auth;
  3. using Couchbase.Lite.Util;
  4. using Newtonsoft.Json;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Net;
  10. using System.Net.Http;
  11. using System.Net.Http.Headers;
  12. using System.Text;
  13. using System.Threading;
  14. using System.Threading.Tasks;
  15.  
  16. //To run tests:
  17. //*] create bucket: syncdatasample
  18. //*] create bucket: syncdatasample_sync
  19. //*] use a the syncgatway.conf file like this one
  20. //{
  21. //    "adminInterface": ":4985",
  22. //    "interface": ":4984",
  23. //    "log":["HTTP", "Shadow", "CRUD", "Changes"],
  24. //    "verbose": true,
  25. //    "databases": {
  26. //        "syncdatasampledb": {
  27. //            "server": "http://localhost:8091",
  28. //            "bucket": "syncdatasample_sync",
  29. //            "shadow": {
  30. //                   "server": "http://localhost:8091",
  31. //                   "bucket": "syncdatasample"
  32. //                },
  33. //            "users": {
  34. //                "GUEST": {
  35. //                    "disabled": true,
  36. //                    "admin_channels": ["*"]
  37. //                }
  38. //            },
  39. //            "sync": `function(doc, oldDoc) {
  40. //  channel(doc.channels);
  41. //}`
  42. //        }
  43. //    }
  44. //}
  45.  
  46. //To run the below class
  47. // SyncSample syncSample = new SyncSample();
  48. // syncSample.RunSample1();
  49. // Console.ReadKey();
  50.  
  51. namespace SyncSample
  52. {
  53.     public class SyncSample
  54.     {
  55.         protected Manager _manager = null;
  56.         protected Database _database = null;
  57.         protected object _baseModel = null;
  58.         protected int _syncPushPullNonBlockingTime = 60;
  59.         private string _syncDatabaseBasePath = @"..\..\..\TestFolder\cbdb";
  60.         private string _syncGatewayAdminURI = "http://localhost:4985";
  61.         private string _syncGatewayURI = "http://localhost:4984";
  62.         private string _syncDatabase = "syncdatasampledb";
  63.         private string _syncUsername = "testuser";
  64.         private string _syncPassword = "123456";
  65.         private string[] _syncChannels = new string[] { };
  66.         private GatewayUser[] users = new GatewayUser[] {
  67.                 new GatewayUser() {
  68.                     name = "testuser",
  69.                     password = "123456",
  70.                     admin_channels = new string[] { "*" }
  71.                 }
  72.             };
  73.  
  74.         /// <summary>
  75.         /// Sample constructor
  76.         /// </summary>
  77.         public SyncSample()
  78.         {
  79.             _syncDatabaseBasePath = _syncDatabaseBasePath + "\\testdb";
  80.  
  81.             _manager = new Manager(new DirectoryInfo(_syncDatabaseBasePath), Manager.DefaultOptions);
  82.             _database = _manager.GetDatabase(_syncDatabase.ToLower());
  83.  
  84.             InsertGatewayUsers(users);
  85.         }
  86.  
  87.         /// <summary>
  88.         /// Run a sample
  89.         /// </summary>
  90.         public void RunSample1()
  91.         {
  92.             string docId = "doctest:0001";
  93.             string docJson = @"{
  94.              'type': 'doctest',
  95.              'channels' : [ 'userchannel-01' ],
  96.              'item1': 'uno',
  97.              'array1': [
  98.                'i1',
  99.                'i2'
  100.              ]
  101.            }";
  102.  
  103.             Dictionary<string, object> properties = JsonConvert.DeserializeObject<Dictionary<string, object>>(docJson);
  104.  
  105.             Document document = _database.GetDocument(docId);
  106.             UnsavedRevision unsavedRevision = document.CreateRevision();
  107.             unsavedRevision.SetUserProperties(properties);
  108.             unsavedRevision.Save();
  109.  
  110.             Push();
  111.             Pull(new string[] { });
  112.         }
  113.  
  114.         /// <summary>
  115.         /// Gateway user
  116.         /// </summary>
  117.         private struct GatewayUser
  118.         {
  119.             public string name;
  120.             public string password;
  121.             public string[] admin_channels;
  122.         }
  123.  
  124.         /// <summary>
  125.         /// Insert a sync gateway user using rest
  126.         /// </summary>
  127.         /// <param name="users"></param>
  128.         private void InsertGatewayUsers(GatewayUser[] users)
  129.         {
  130.             foreach (GatewayUser user in users)
  131.             {
  132.                 string userjson = JsonConvert.SerializeObject(user);
  133.                 HttpClient client = new HttpClient();
  134.                 string releteDocUrl = _syncGatewayAdminURI + "/" + _syncDatabase + "/_user/" + user.name;
  135.                 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  136.                 var request = new HttpRequestMessage(HttpMethod.Get, releteDocUrl);
  137.                 if (client.SendAsync(request).Result.StatusCode != HttpStatusCode.OK)
  138.                 {
  139.                     request = new HttpRequestMessage(HttpMethod.Put, releteDocUrl);
  140.                     request.Content = new StringContent(userjson, Encoding.UTF8, "application/json");
  141.                     HttpResponseMessage response = client.SendAsync(request).Result;
  142.                     if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Created)
  143.                         Console.WriteLine("SuccessFull inserted/updated user \"" + user.name + "\" in database \"" + _syncDatabase + "\"");
  144.                     else
  145.                         Console.WriteLine("Error inserting user \"" + user.name + "\" in database \"" + _syncDatabase + "\"");
  146.                 }
  147.             }
  148.         }
  149.  
  150.         /// <summary>
  151.         /// Do a Pull
  152.         /// </summary>
  153.         /// <param name="channels"></param>
  154.         /// <returns></returns>
  155.         public bool Pull(string[] channels)
  156.         {
  157.             bool ret = false;
  158.  
  159.             Replication replication = _database.CreatePullReplication(new Uri(_syncGatewayURI + "/" + _syncDatabase));
  160.             if (!String.IsNullOrEmpty(_syncUsername) && !String.IsNullOrEmpty(_syncPassword))
  161.                 replication.Authenticator = AuthenticatorFactory.CreateBasicAuthenticator(_syncUsername, _syncPassword);
  162.             if (channels.Length > 0)
  163.                 replication.Channels = channels.AsEnumerable<string>();
  164.             Log.D(_syncDatabase, "Pull replication start...");
  165.             ret = RunReplication(replication);
  166.             Log.D(_syncDatabase, "Pull replication ends.");
  167.  
  168.             return ret;
  169.         }
  170.  
  171.         /// <summary>
  172.         /// Do a Push
  173.         /// </summary>
  174.         /// <returns></returns>
  175.         public bool Push()
  176.         {
  177.             bool ret = false;
  178.  
  179.             Replication replication = _database.CreatePushReplication(new Uri(_syncGatewayURI + "/" + _syncDatabase));
  180.             if (!String.IsNullOrEmpty(_syncUsername) && !String.IsNullOrEmpty(_syncPassword))
  181.                 replication.Authenticator = AuthenticatorFactory.CreateBasicAuthenticator(_syncUsername, _syncPassword);
  182.             Log.D(_syncDatabase, "Push replication start...");
  183.             ret = RunReplication(replication);
  184.             Log.D(_syncDatabase, "Push replication ends.");
  185.  
  186.             return ret;
  187.         }
  188.  
  189.         /// <summary>
  190.         /// Run Replication
  191.         /// </summary>
  192.         /// <param name="replication"></param>
  193.         /// <returns></returns>
  194.         private bool RunReplication(Replication replication)
  195.         {
  196.             bool ret = false;
  197.  
  198.             replication.Start();
  199.             CountdownEvent replicationDoneSignalPolling = ReplicationWatcherThread(replication);
  200.             if (!replicationDoneSignalPolling.Wait(TimeSpan.FromSeconds(_syncPushPullNonBlockingTime)))
  201.             {
  202.                 Log.D(_syncDatabase, "Timeout replication.");
  203.                 ret = false;
  204.             }
  205.             replication.Stop();
  206.  
  207.             return ret;
  208.         }
  209.  
  210.         /// <summary>
  211.         /// Replication Watcher thread
  212.         /// </summary>
  213.         /// <param name="replication"></param>
  214.         /// <returns></returns>
  215.         private static CountdownEvent ReplicationWatcherThread(Replication replication)
  216.         {
  217.             CountdownEvent doneSignal = new CountdownEvent(1);
  218.             Task.Factory.StartNew(() =>
  219.             {
  220.                 int i = 0;
  221.                 while (replication.Status != ReplicationStatus.Stopped && replication.Status != ReplicationStatus.Idle)
  222.                 {
  223.                     Console.WriteLine("Replication is running...");
  224.                     Thread.Sleep(100);
  225.                     i++;
  226.                     if (i == 10)
  227.                     {
  228.                         i = 0;
  229.                         Log.D(replication.LocalDatabase.ToString(), "Running replication.");
  230.                     }
  231.                 }
  232.                 doneSignal.Signal();
  233.             });
  234.             return doneSignal;
  235.         }
  236.  
  237.  
  238.     }
  239. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement