Advertisement
Guest User

Untitled

a guest
Mar 16th, 2015
251
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 7.64 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. namespace SyncSample
  47. {
  48.     public class SyncSampleReplicationObserver
  49.     {
  50.         protected Manager _manager = null;
  51.         protected Database _database = null;
  52.         protected object _baseModel = null;
  53.         protected int _syncPushPullNonBlockingTime = 60;
  54.         private string _syncDatabaseBasePath = @"..\..\..\TestFolder\cbdb";
  55.         private string _syncGatewayAdminURI = "http://localhost:4985";
  56.         private string _syncGatewayURI = "http://localhost:4984";
  57.         private string _syncDatabase = "syncdatasampledb";
  58.         private string _syncUsername = "testuser";
  59.         private string _syncPassword = "123456";
  60.         private string[] _syncChannels = new string[] { };
  61.         private GatewayUser[] users = new GatewayUser[] {
  62.                 new GatewayUser() {
  63.                     name = "testuser",
  64.                     password = "123456",
  65.                     admin_channels = new string[] { "*" }
  66.                 }
  67.             };
  68.  
  69.         /// <summary>
  70.         /// Sample constructor
  71.         /// </summary>
  72.         public SyncSampleReplicationObserver()
  73.         {
  74.             _syncDatabaseBasePath = _syncDatabaseBasePath + "\\testdb";
  75.  
  76.             _manager = new Manager(new DirectoryInfo(_syncDatabaseBasePath), Manager.DefaultOptions);
  77.             _database = _manager.GetDatabase(_syncDatabase.ToLower());
  78.  
  79.             InsertGatewayUsers(users);
  80.         }
  81.  
  82.         /// <summary>
  83.         /// Run a sample
  84.         /// </summary>
  85.         public void RunSample1()
  86.         {
  87.             string docId = "doctest:0001";
  88.             string docJson = @"{
  89.              'type': 'doctest',
  90.              'channels' : [ 'userchannel-01' ],
  91.              'item1': 'uno',
  92.              'array1': [
  93.                'i1',
  94.                'i2'
  95.              ]
  96.            }";
  97.  
  98.             Dictionary<string, object> properties = JsonConvert.DeserializeObject<Dictionary<string, object>>(docJson);
  99.  
  100.             Document document = _database.GetDocument(docId);
  101.             UnsavedRevision unsavedRevision = document.CreateRevision();
  102.             unsavedRevision.SetUserProperties(properties);
  103.             unsavedRevision.Save();
  104.  
  105.             Push();
  106.             Pull(new string[] { });
  107.         }
  108.  
  109.         /// <summary>
  110.         /// Gateway user
  111.         /// </summary>
  112.         private struct GatewayUser
  113.         {
  114.             public string name;
  115.             public string password;
  116.             public string[] admin_channels;
  117.         }
  118.  
  119.         /// <summary>
  120.         /// Insert a sync gateway user using rest
  121.         /// </summary>
  122.         /// <param name="users"></param>
  123.         private void InsertGatewayUsers(GatewayUser[] users)
  124.         {
  125.             foreach (GatewayUser user in users)
  126.             {
  127.                 string userjson = JsonConvert.SerializeObject(user);
  128.                 HttpClient client = new HttpClient();
  129.                 string releteDocUrl = _syncGatewayAdminURI + "/" + _syncDatabase + "/_user/" + user.name;
  130.                 client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  131.                 var request = new HttpRequestMessage(HttpMethod.Get, releteDocUrl);
  132.                 if (client.SendAsync(request).Result.StatusCode != HttpStatusCode.OK)
  133.                 {
  134.                     request = new HttpRequestMessage(HttpMethod.Put, releteDocUrl);
  135.                     request.Content = new StringContent(userjson, Encoding.UTF8, "application/json");
  136.                     HttpResponseMessage response = client.SendAsync(request).Result;
  137.                     if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Created)
  138.                         Console.WriteLine("SuccessFull inserted/updated user \"" + user.name + "\" in database \"" + _syncDatabase + "\"");
  139.                     else
  140.                         Console.WriteLine("Error inserting user \"" + user.name + "\" in database \"" + _syncDatabase + "\"");
  141.                 }
  142.             }
  143.         }
  144.  
  145.         /// <summary>
  146.         /// Do a Pull
  147.         /// </summary>
  148.         /// <param name="channels"></param>
  149.         /// <returns></returns>
  150.         public bool Pull(string[] channels)
  151.         {
  152.             bool ret = false;
  153.  
  154.             Replication replication = _database.CreatePullReplication(new Uri(_syncGatewayURI + "/" + _syncDatabase));
  155.             if (!String.IsNullOrEmpty(_syncUsername) && !String.IsNullOrEmpty(_syncPassword))
  156.                 replication.Authenticator = AuthenticatorFactory.CreateBasicAuthenticator(_syncUsername, _syncPassword);
  157.             if (channels.Length > 0)
  158.                 replication.Channels = channels.AsEnumerable<string>();
  159.             Log.D(_syncDatabase, "Pull replication start...");
  160.             ret = RunReplication(replication);
  161.             Log.D(_syncDatabase, "Pull replication ends.");
  162.  
  163.             return ret;
  164.         }
  165.  
  166.         /// <summary>
  167.         /// Do a Push
  168.         /// </summary>
  169.         /// <returns></returns>
  170.         public bool Push()
  171.         {
  172.             bool ret = false;
  173.  
  174.             Replication replication = _database.CreatePushReplication(new Uri(_syncGatewayURI + "/" + _syncDatabase));
  175.             if (!String.IsNullOrEmpty(_syncUsername) && !String.IsNullOrEmpty(_syncPassword))
  176.                 replication.Authenticator = AuthenticatorFactory.CreateBasicAuthenticator(_syncUsername, _syncPassword);
  177.             Log.D(_syncDatabase, "Push replication start...");
  178.             ret = RunReplication(replication);
  179.             Log.D(_syncDatabase, "Push replication ends.");
  180.  
  181.             return ret;
  182.         }
  183.  
  184.         /// <summary>
  185.         /// Run Replication
  186.         /// </summary>
  187.         /// <param name="replication"></param>
  188.         /// <returns></returns>
  189.         private bool RunReplication(Replication replication)
  190.         {
  191.             bool ret = false;
  192.  
  193.  
  194.             CountdownEvent replicationSignal = new CountdownEvent(1);
  195.             ReplicationObserver replicationObserver = new ReplicationObserver(replicationSignal);
  196.             replication.Changed += replicationObserver.Changed;
  197.             replication.Start();
  198.             if (!replicationSignal.Wait(TimeSpan.FromSeconds(_syncPushPullNonBlockingTime)))
  199.             {
  200.                 Console.WriteLine("Timeout replication.");
  201.                 Log.D(_syncDatabase, "Timeout replication.");
  202.                 ret = false;
  203.             }
  204.             replication.Stop();
  205.  
  206.             return ret;
  207.         }
  208.  
  209.     }
  210. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement