Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using Couchbase.Lite;
- using Couchbase.Lite.Auth;
- using Couchbase.Lite.Util;
- using Newtonsoft.Json;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Net.Http.Headers;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- //To run tests:
- //*] create bucket: syncdatasample
- //*] create bucket: syncdatasample_sync
- //*] use a the syncgatway.conf file like this one
- //{
- // "adminInterface": ":4985",
- // "interface": ":4984",
- // "log":["HTTP", "Shadow", "CRUD", "Changes"],
- // "verbose": true,
- // "databases": {
- // "syncdatasampledb": {
- // "server": "http://localhost:8091",
- // "bucket": "syncdatasample_sync",
- // "shadow": {
- // "server": "http://localhost:8091",
- // "bucket": "syncdatasample"
- // },
- // "users": {
- // "GUEST": {
- // "disabled": true,
- // "admin_channels": ["*"]
- // }
- // },
- // "sync": `function(doc, oldDoc) {
- // channel(doc.channels);
- //}`
- // }
- // }
- //}
- namespace SyncSample
- {
- public class SyncSampleReplicationObserver
- {
- protected Manager _manager = null;
- protected Database _database = null;
- protected object _baseModel = null;
- protected int _syncPushPullNonBlockingTime = 60;
- private string _syncDatabaseBasePath = @"..\..\..\TestFolder\cbdb";
- private string _syncGatewayAdminURI = "http://localhost:4985";
- private string _syncGatewayURI = "http://localhost:4984";
- private string _syncDatabase = "syncdatasampledb";
- private string _syncUsername = "testuser";
- private string _syncPassword = "123456";
- private string[] _syncChannels = new string[] { };
- private GatewayUser[] users = new GatewayUser[] {
- new GatewayUser() {
- name = "testuser",
- password = "123456",
- admin_channels = new string[] { "*" }
- }
- };
- /// <summary>
- /// Sample constructor
- /// </summary>
- public SyncSampleReplicationObserver()
- {
- _syncDatabaseBasePath = _syncDatabaseBasePath + "\\testdb";
- _manager = new Manager(new DirectoryInfo(_syncDatabaseBasePath), Manager.DefaultOptions);
- _database = _manager.GetDatabase(_syncDatabase.ToLower());
- InsertGatewayUsers(users);
- }
- /// <summary>
- /// Run a sample
- /// </summary>
- public void RunSample1()
- {
- string docId = "doctest:0001";
- string docJson = @"{
- 'type': 'doctest',
- 'channels' : [ 'userchannel-01' ],
- 'item1': 'uno',
- 'array1': [
- 'i1',
- 'i2'
- ]
- }";
- Dictionary<string, object> properties = JsonConvert.DeserializeObject<Dictionary<string, object>>(docJson);
- Document document = _database.GetDocument(docId);
- UnsavedRevision unsavedRevision = document.CreateRevision();
- unsavedRevision.SetUserProperties(properties);
- unsavedRevision.Save();
- Push();
- Pull(new string[] { });
- }
- /// <summary>
- /// Gateway user
- /// </summary>
- private struct GatewayUser
- {
- public string name;
- public string password;
- public string[] admin_channels;
- }
- /// <summary>
- /// Insert a sync gateway user using rest
- /// </summary>
- /// <param name="users"></param>
- private void InsertGatewayUsers(GatewayUser[] users)
- {
- foreach (GatewayUser user in users)
- {
- string userjson = JsonConvert.SerializeObject(user);
- HttpClient client = new HttpClient();
- string releteDocUrl = _syncGatewayAdminURI + "/" + _syncDatabase + "/_user/" + user.name;
- client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
- var request = new HttpRequestMessage(HttpMethod.Get, releteDocUrl);
- if (client.SendAsync(request).Result.StatusCode != HttpStatusCode.OK)
- {
- request = new HttpRequestMessage(HttpMethod.Put, releteDocUrl);
- request.Content = new StringContent(userjson, Encoding.UTF8, "application/json");
- HttpResponseMessage response = client.SendAsync(request).Result;
- if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Created)
- Console.WriteLine("SuccessFull inserted/updated user \"" + user.name + "\" in database \"" + _syncDatabase + "\"");
- else
- Console.WriteLine("Error inserting user \"" + user.name + "\" in database \"" + _syncDatabase + "\"");
- }
- }
- }
- /// <summary>
- /// Do a Pull
- /// </summary>
- /// <param name="channels"></param>
- /// <returns></returns>
- public bool Pull(string[] channels)
- {
- bool ret = false;
- Replication replication = _database.CreatePullReplication(new Uri(_syncGatewayURI + "/" + _syncDatabase));
- if (!String.IsNullOrEmpty(_syncUsername) && !String.IsNullOrEmpty(_syncPassword))
- replication.Authenticator = AuthenticatorFactory.CreateBasicAuthenticator(_syncUsername, _syncPassword);
- if (channels.Length > 0)
- replication.Channels = channels.AsEnumerable<string>();
- Log.D(_syncDatabase, "Pull replication start...");
- ret = RunReplication(replication);
- Log.D(_syncDatabase, "Pull replication ends.");
- return ret;
- }
- /// <summary>
- /// Do a Push
- /// </summary>
- /// <returns></returns>
- public bool Push()
- {
- bool ret = false;
- Replication replication = _database.CreatePushReplication(new Uri(_syncGatewayURI + "/" + _syncDatabase));
- if (!String.IsNullOrEmpty(_syncUsername) && !String.IsNullOrEmpty(_syncPassword))
- replication.Authenticator = AuthenticatorFactory.CreateBasicAuthenticator(_syncUsername, _syncPassword);
- Log.D(_syncDatabase, "Push replication start...");
- ret = RunReplication(replication);
- Log.D(_syncDatabase, "Push replication ends.");
- return ret;
- }
- /// <summary>
- /// Run Replication
- /// </summary>
- /// <param name="replication"></param>
- /// <returns></returns>
- private bool RunReplication(Replication replication)
- {
- bool ret = false;
- CountdownEvent replicationSignal = new CountdownEvent(1);
- ReplicationObserver replicationObserver = new ReplicationObserver(replicationSignal);
- replication.Changed += replicationObserver.Changed;
- replication.Start();
- if (!replicationSignal.Wait(TimeSpan.FromSeconds(_syncPushPullNonBlockingTime)))
- {
- Console.WriteLine("Timeout replication.");
- Log.D(_syncDatabase, "Timeout replication.");
- ret = false;
- }
- replication.Stop();
- return ret;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement