// NoSQL
        public bool AddNoSql(CustomerNavigation customerNavigation)
        {
            // save in Couchbase
            using (var cluster = new Cluster())
            {
                // users config
                // pass to connectionstrings
                var authenticator = new PasswordAuthenticator(AppSettings.NoSqlUser, AppSettings.NoSqlPass);
                cluster.Authenticate(authenticator);

                // open bucket
                using (var bucket = cluster.OpenBucket(AppSettings.NoSqlBucket))
                {
                    var document = new Document <dynamic>
                    {
                        Id      = "CustomerNavigation::" + customerNavigation.Id,
                        Content = customerNavigation
                    };
                    // upset in base
                    var upsert = bucket.Upsert(document);
                    return(upsert.Success);
                }
            }
        }
        public void SetAuthenticator_Using_PasswordAuthenticator()
        {
            if (!TestConfiguration.Settings.EnhancedAuth)
            {
                Assert.Ignore("PasswordAuthenticator requires CB 5.0 or greater.");
            }

            try
            {
                var config        = TestConfiguration.GetDefaultConfiguration();
                var authenticator = new PasswordAuthenticator(TestConfiguration.Settings.AdminUsername, TestConfiguration.Settings.AdminPassword);
                config.SetAuthenticator(authenticator);

                ClusterHelper.Initialize(config);
                var bucket = ClusterHelper.GetBucket("default");

                Assert.IsNotNull(bucket);
                Assert.AreEqual("default", bucket.Name);
            }
            finally
            {
                ClusterHelper.Close();
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// initialize the couchbase configuration values (for use when processing actions)
        /// </summary>
        public void Initialize()
        {
            ParseEnvironmentVariables();
            VerifyEnvironmentVariables();

            ClientConfiguration config = new ClientConfiguration();

            config.BucketConfigs.Clear();
            config.Servers = ServerUris;

            // add all the buckets to the config
            Buckets.ForEach(bucket => config.BucketConfigs.Add(bucket, new BucketConfiguration {
                BucketName = bucket, Username = Username, Password = Password
            }));

            // set up cluster
            Cluster = new Cluster(config);

            PasswordAuthenticator authenticator = new PasswordAuthenticator(Username, Password);

            Cluster.Authenticate(authenticator);

            ClusterHelper.Initialize(Cluster.Configuration);
        }
Exemplo n.º 4
0
        public static void Register()
        {
            var couchbaseServer = ConfigurationManager.AppSettings.Get("CouchbaseServer");
            var username        = ConfigurationManager.AppSettings.Get("CouchbaseUser");
            var password        = ConfigurationManager.AppSettings.Get("CouchbasePassword");
            var bucketName      = ConfigurationManager.AppSettings.Get("CouchbaseTravelBucket");

            var cluster = new Cluster(new ClientConfiguration
            {
                Servers = new List <Uri> {
                    new Uri("http://localhost:8091")
                }
            });

            var authenticator = new PasswordAuthenticator(username, password);

            cluster.Authenticate(authenticator);
            ClusterHelper.Initialize();
            var bucket = cluster.OpenBucket(bucketName, password);


            //var config = new ClientConfiguration
            //{
            //    Servers = new List<Uri>() { new Uri("http://localhost:8091/") },
            //    UseSsl = true,
            //    DefaultOperationLifespan = 1000,
            //    BucketConfigs = new Dictionary<string, BucketConfiguration>
            //    {
            //         {"travel-sample", new BucketConfiguration
            //           {
            //                BucketName = "travel-sample",
            //                UseSsl = false,
            //                Password = "******",
            //                DefaultOperationLifespan = 2000,
            //                PoolConfiguration = new PoolConfiguration
            //                {
            //                    MaxSize = 10,
            //                    MinSize = 5,
            //                    SendTimeout = 12000
            //                }
            //          }
            //        }
            //    }
            //};


            //using (var cluster_ = new Cluster(config))
            //{
            //    IBucket bucket_ = null;
            //    try
            //    {
            //        //bucket_ = cluster.OpenBucket();
            //        bucket_ = cluster.OpenBucket(bucketName, password);
            //        //use the bucket here
            //    }
            //    finally
            //    {
            //        if (bucket_ != null)
            //        {
            //            cluster.CloseBucket(bucket_);
            //        }
            //    }
            //}

            EnsureIndexes(bucketName, username, password);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Authenticate using a username and password.
        /// </summary>
        /// <remarks>Internally uses a <see cref="PasswordAuthenticator" />.</remarks>
        /// <param name="username">The username.</param>
        /// <param name="password">The password.</param>
        public void Authenticate(string username, string password)
        {
            var authenticator = new PasswordAuthenticator(username, password);

            _configuration.SetAuthenticator(authenticator);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Establishes a connection with Couchbase.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <returns>A message indicating connection success</returns>
        public override async Task <ConnectResponse> Connect(ConnectRequest request, ServerCallContext context)
        {
            // validate settings passed in
            try
            {
                _server.Settings = JsonConvert.DeserializeObject <Settings>(request.SettingsJson);
                _server.Settings.Validate();
            }
            catch (Exception e)
            {
                Logger.Error(e, e.Message, context);
                return(new ConnectResponse
                {
                    OauthStateJson = request.OauthStateJson,
                    ConnectionError = "",
                    OauthError = "",
                    SettingsError = e.Message
                });
            }

            // initialize cluster factory
            try
            {
                var servers = _server.Settings.Servers.Select(s => new Uri(s)).ToList();
                var config  = new ClientConfiguration
                {
                    Servers = servers
                };
                var credentials = new PasswordAuthenticator(_server.Settings.Username, _server.Settings.Password);
                _clusterFactory.Initialize(config, credentials);
            }
            catch (Exception e)
            {
                Logger.Error(e, e.Message, context);
                return(new ConnectResponse
                {
                    OauthStateJson = request.OauthStateJson,
                    ConnectionError = "",
                    OauthError = "",
                    SettingsError = e.Message
                });
            }

            // test cluster factory
            try
            {
                var cluster = _clusterFactory.GetCluster();
                var version = cluster.GetClusterVersion();

                if (version.HasValue)
                {
                    _server.Connected = true;
                    Logger.Info($"Connected to Couchbase Version: {version.Value}");
                }
                else
                {
                    return(new ConnectResponse
                    {
                        OauthStateJson = request.OauthStateJson,
                        ConnectionError = "Unable to connect to Couchbase",
                        OauthError = "",
                        SettingsError = ""
                    });
                }
            }
            catch (Exception e)
            {
                Logger.Error(e, e.Message, context);

                return(new ConnectResponse
                {
                    OauthStateJson = request.OauthStateJson,
                    ConnectionError = e.Message,
                    OauthError = "",
                    SettingsError = ""
                });
            }

            return(new ConnectResponse
            {
                ConnectionError = "",
                OauthError = "",
                SettingsError = ""
            });
        }
Exemplo n.º 7
0
        static void Main(string[] args)
        {
            var cluster = new Cluster(new ClientConfiguration
            {
                Servers = new List <Uri> {
                    new Uri("http://127.0.0.1:8091/")
                }
            });

            var authenticator = new PasswordAuthenticator("nav", "5522567n!");

            cluster.Authenticate(authenticator);
            var bucket = cluster.OpenBucket("travel-sample");
            //var bucket = cluster.OpenBucket();
            string a        = "new sample";
            var    document = new Document <dynamic>
            {
                Id      = "Hello",
                Content = new
                {
                    name  = a,
                    name2 = "asdsad"
                }
            };

            //var upsert = bucket.Upsert(document);
            //if (upsert.Success)
            //{
            //    var get = bucket.GetDocument<dynamic>(document.Id);
            //    document = get.Document;
            //    var msg = string.Format("{0} {1}!", document.Id, document.Content.name);
            //    Console.WriteLine(msg);
            //}

            //var document2 = new Document<dynamic>
            //{
            //    Id = "airline_10"

            //};
            //document2.Id = "airline_10123";
            var get2      = bucket.GetDocument <dynamic>("airline_10");
            var document2 = get2.Document;
            var msg2      = string.Format("{0} {1} {2} {3}!", document2.Id, document2.Content.name, document2.Content.country, document2.Content.type);

            Console.WriteLine(msg2);
            //string a="UPDATE `travel - sample` SET name = `change` WHERE name=`Couchbase`";
            //var document2 = new Document<dynamic>
            //document2 =bucket.GetDocument(airline_10);
            //var req = new QueryRequest().Statement("UPDATE `travel - sample` SET name = `change` WHERE name=`Couchbase`");
            //if (req.)
            //{
            //    Console.WriteLine("a");
            //}
            Console.WriteLine("Sample Select");
            var query = new QueryRequest("SELECT name FROM `travel-sample` LIMIT 4");

            foreach (var row in bucket.Query <dynamic>(query))
            {
                Console.WriteLine(JsonConvert.SerializeObject(row));
            }

            var query2 = new QueryRequest("UPDATE `travel-sample` SET name = \"new sample\" WHERE name=\"change\"");

            if (bucket.Query <dynamic>(query2) != null)
            {
                Console.WriteLine("Hi");
            }
            string ab        = document2.ToString();
            var    document3 = new Document <dynamic>
            {
            };

            Console.WriteLine(ab);
            Console.Read();
        }
Exemplo n.º 8
0
 public CouchbaseClient(ClientConfiguration clientConfiguration, PasswordAuthenticator passwordAuthenticator)
 {
     ////TODO: Need to move to couchbase Core implementation
     ClusterHelper.Initialize(clientConfiguration, passwordAuthenticator);
 }
Exemplo n.º 9
0
 public void Initialize(ClientConfiguration config, PasswordAuthenticator credentials)
 {
     _credentials         = credentials;
     _clientConfiguration = config;
     ClusterHelper.Initialize(config, credentials);
 }
 public void Teardown()
 {
     _authenticator = null;
 }
Exemplo n.º 11
0
        public static void Start(IConfiguration configuration)
        {
            var tftpServerPort = int.Parse(configuration["TftpServer:Port"]);

            var couchbaseBootstrapServers =
                configuration
                .GetSection("Couchbase:BootstrapServers")
                .AsEnumerable()
                .Where(x => x.Value != null)
                .Select(x =>
                        new Uri(x.Value)
                        )
                .ToList();

            var couchbaseBucket        = configuration["TftpServer:Bucket:Name"];
            var couchbaseUsername      = configuration["TftpServer:Bucket:Username"];
            var couchbasePassword      = configuration["TftpServer:Bucket:Password"];
            var receivedDocumentPrefix = configuration["TftpServer:ReceivedDocumentPrefix"];

            var DbCluster = new Cluster(
                new ClientConfiguration
            {
                Servers    = couchbaseBootstrapServers,
                Serializer = () =>
                {
                    JsonSerializerSettings serializerSettings =
                        new JsonSerializerSettings()
                    {
                        ContractResolver     = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(),
                        DateTimeZoneHandling = DateTimeZoneHandling.Utc
                    };

                    serializerSettings.Converters.Add(new IPAddressConverter());
                    serializerSettings.Converters.Add(new IPEndPointConverter());

                    return(new DefaultSerializer(serializerSettings, serializerSettings));
                }
            }
                );

            var authenticator = new PasswordAuthenticator(couchbaseUsername, couchbasePassword);

            DbCluster.Authenticate(authenticator);

            libtftp.TftpServer.Instance.LogSeverity = libtftp.ETftpLogSeverity.Debug;

            libtftp.TftpServer.Instance.FileReceived +=
                new EventHandler <libtftp.TftpTransferCompleteEventArgs>(async(sender, ev) =>
            {
                ev.Stream.Position = 0;
                var reader         = new StreamReader(ev.Stream);
                var buffer         = await reader.ReadToEndAsync();

                Console.WriteLine(
                    "Received file from " +
                    ev.RemoteHost.ToString() +
                    " called [" + ev.Filename + "] with " +
                    ev.Stream.Length.ToString() +
                    " bytes"
                    );

                using (var bucket = await DbCluster.OpenBucketAsync(couchbaseBucket))
                {
                    var document = new Document <dynamic>
                    {
                        Id      = receivedDocumentPrefix + ev.Filename,
                        Content = new ConfigurationDocument
                        {
                            Type          = "tftp::configuration",
                            Configuration = buffer
                        }
                    };

                    var insert = await bucket.InsertAsync(document);
                    if (insert.Success)
                    {
                        Console.WriteLine(document.Id);
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine(insert.Status.ToString());
                    }
                }
            }
                                                                         );

            libtftp.TftpServer.Instance.FileTransmitted +=
                new EventHandler <libtftp.TftpTransferCompleteEventArgs>((sender, ev) =>
            {
                Console.WriteLine(
                    "Transmitted file to " +
                    ev.RemoteHost.ToString() +
                    " called [" + ev.Filename + "]"
                    );
            }
                                                                         );

            libtftp.TftpServer.Instance.Log +=
                new EventHandler <libtftp.TftpLogEventArgs>((sender, ev) =>
            {
                switch (ev.Severity)
                {
                case libtftp.ETftpLogSeverity.Error:
                    Console.ForegroundColor = ConsoleColor.Red;
                    break;

                case libtftp.ETftpLogSeverity.Debug:
                    Console.ForegroundColor = ConsoleColor.Gray;
                    break;

                default:
                    Console.ForegroundColor = ConsoleColor.White;
                    break;
                }

                Console.Write("[" + ev.TimeStamp.ToString() + "]: ");

                Console.ForegroundColor = ConsoleColor.White;

                Console.WriteLine(ev.Message);
            }
                                                            );

            //libtftp.TftpServer.Instance.GetStream += new Func<object, libtftp.TftpGetStreamEventArgs, Task>(
            //    async (sender, ev) =>
            //    {
            //        var buffer = await File.ReadAllBytesAsync(@"Sample Data/LorumIpsum.txt");
            //        ev.Result = new MemoryStream(buffer);
            //    }
            //);

            libtftp.TftpServer.Instance.Start(tftpServerPort);
        }
Exemplo n.º 12
0
        public ProductDataAccess()
        {
            var authenticator = new PasswordAuthenticator("Administrator", "Tesco123");

            cluster.Authenticate(authenticator);
        }