Beispiel #1
0
        public static void Main(string[] args)
        {
            // Connect to cassandra cluster  (Cassandra API on Azure Cosmos DB supports only TLSv1.2)
            var options = new Cassandra.SSLOptions(SslProtocols.Tls12, true, ValidateServerCertificate);

            options.SetHostNameResolver((ipAddress) => CassandraContactPoint);
            Cluster  cluster = Cluster.Builder().WithCredentials(UserName, Password).WithPort(CassandraPort).AddContactPoint(CassandraContactPoint).WithSSL(options).Build();
            ISession session = cluster.Connect();

            session = cluster.Connect("uprofile");
            IMapper mapper = new Mapper(session);

            // Inserting Data into user table
            int i = 0;

            while (true)
            {
                try
                {
                    Thread.Sleep(250);
                    Console.WriteLine("inserting record:" + i);
                    mapper.Insert <User>(new User(i, "record" + i, "record" + i));
                    i++;
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error writing record:" + e);
                }
            }
        }
        public void ChangeFeedPull()
        {
            // Connect to cassandra cluster  (Cassandra API on Azure Cosmos DB supports only TLSv1.2)
            var options = new Cassandra.SSLOptions(SslProtocols.Tls12, true, ValidateServerCertificate);

            options.SetHostNameResolver((ipAddress) => CassandraContactPoint);
            Cluster cluster = Cluster.Builder().WithCredentials(UserName, Password).WithPort(CassandraPort).AddContactPoint(CassandraContactPoint).WithSSL(options).Build();

            session = cluster.Connect();
            Setup(); //drop and create keyspace and table
            session = cluster.Connect("uprofile");
            IMapper mapper = new Mapper(session);

            Console.WriteLine("pulling from change feed: ");

            //set initial start time for pulling the change feed
            DateTime timeBegin = DateTime.UtcNow;

            //initialise variable to store the continuation token
            byte[] pageState = null;
            while (true)
            {
                try
                {
                    IStatement changeFeedQueryStatement = new SimpleStatement(
                        $"SELECT * FROM uprofile.user where COSMOS_CHANGEFEED_START_TIME() = '{timeBegin.ToString("yyyy-MM-ddTHH:mm:ss.fffZ", CultureInfo.InvariantCulture)}'");
                    if (pageState != null)
                    {
                        changeFeedQueryStatement = changeFeedQueryStatement.SetPagingState(pageState);
                    }
                    Console.WriteLine("getting records from change feed at last page state....");
                    RowSet rowSet = session.Execute(changeFeedQueryStatement);

                    //store the continuation token here
                    pageState = rowSet.PagingState;

                    List <Row> rowList = rowSet.ToList();
                    if (rowList.Count != 0)
                    {
                        for (int i = 0; i < rowList.Count; i++)
                        {
                            string value = rowList[i].GetValue <string>("user_name");
                            int    key   = rowList[i].GetValue <int>("user_id");
                            // do something with the data - e.g. compute, forward to another event, function, etc.
                            // here, we just print the user name field
                            Console.WriteLine("user_name: " + value);
                        }
                    }
                    else
                    {
                        Console.WriteLine("zero documents read");
                    }
                    Thread.Sleep(300);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Exception " + e);
                }
            }
        }
Beispiel #3
0
        public DBService(IConfiguration configuration, ILogger <DBService> logger)
        {
            _configuration = configuration;
            _logger        = logger;

            var options = new Cassandra.SSLOptions(SslProtocols.Tls12, true, ValidateServerCertificate);

            options.SetHostNameResolver((ipAddress) => _configuration["DatabaseSettings:ContactPoint"]);

            cluster = Cluster.Builder().WithCredentials(_configuration["DatabaseSettings:UserName"], _configuration["DatabaseSettings:Password"])
                      .WithPort(Convert.ToInt32(_configuration["DatabaseSettings:Port"])).AddContactPoint(_configuration["DatabaseSettings:ContactPoint"]).WithSSL(options).Build();
        }
Beispiel #4
0
        public static void Main(string[] args)
        {
            // Connect to cassandra cluster  (Cassandra API on Azure Cosmos DB supports only TLSv1.2)
            var options = new Cassandra.SSLOptions(SslProtocols.Tls12, true, ValidateServerCertificate);

            options.SetHostNameResolver((ipAddress) => CassandraContactPoint);
            Cluster cluster = Cluster.Builder().WithCredentials(UserName, Password).WithPort(CassandraPort).AddContactPoint(CassandraContactPoint).WithSSL(options).Build();


            //Cluster cluster = Cluster.Builder().WithConnectionString("AccountEndpoint=https://mydatabasegraph.documents.azure.com:443/;AccountKey=sQfe98WUdRPkN4PSYNDArSjPO4sGpBTFEy9S44CSkdjtO1vD3yLgvIRqyAOHqDRXbTrVMDATTmyV7ir5VZ9WTg==;ApiKind=Gremlin;").WithPort(CassandraPort).AddContactPoint(CassandraContactPoint).WithSSL(options).Build();
            ISession session = cluster.Connect();

            // Creating KeySpace and table
            session.Execute("DROP KEYSPACE IF EXISTS uprofile");
            session.Execute("CREATE KEYSPACE uprofile WITH REPLICATION = { 'class' : 'NetworkTopologyStrategy', 'datacenter1' : 1 };");
            Console.WriteLine(String.Format("created keyspace uprofile"));
            session.Execute("CREATE TABLE IF NOT EXISTS uprofile.user (user_id int PRIMARY KEY, user_name text, user_bcity text)");
            Console.WriteLine(String.Format("created table user"));

            session = cluster.Connect("uprofile");
            IMapper mapper = new Mapper(session);

            // Inserting Data into user table
            mapper.Insert <User>(new User(1, "LyubovK", "Dubai"));
            mapper.Insert <User>(new User(2, "JiriK", "Toronto"));
            mapper.Insert <User>(new User(3, "IvanH", "Mumbai"));
            mapper.Insert <User>(new User(4, "LiliyaB", "Seattle"));
            mapper.Insert <User>(new User(5, "JindrichH", "Buenos Aires", "Edu"));
            Console.WriteLine("Inserted data into user table");

            Console.WriteLine("Select ALL");
            Console.WriteLine("-------------------------------");
            foreach (User user in mapper.Fetch <User>("Select * from user"))
            {
                Console.WriteLine(user);
            }

            Console.WriteLine("Getting by id 3");
            Console.WriteLine("-------------------------------");
            User userId3 = mapper.FirstOrDefault <User>("Select * from user where user_id = ?", 3);

            Console.WriteLine(userId3);

            // Clean up of Table and KeySpace
            session.Execute("DROP table user");
            session.Execute("DROP KEYSPACE uprofile");

            // Wait for enter key before exiting
            Console.ReadLine();
        }
        public static void Main(string[] args)
        {
            // Connect to cassandra cluster  (Cassandra API on Azure Cosmos DB supports only TLSv1.2)
            var options = new Cassandra.SSLOptions(SslProtocols.Tls12, true, ValidateServerCertificate);

            options.SetHostNameResolver((ipAddress) => CassandraContactPoint);
            Cluster  cluster = Cluster.Builder().WithCredentials(UserName, Password).WithPort(CassandraPort).AddContactPoint(CassandraContactPoint).WithSSL(options).Build();
            ISession session = cluster.Connect();

            // Creating KeySpace and table
            session.Execute("DROP KEYSPACE IF EXISTS speakingengagements");
            session.Execute("CREATE KEYSPACE speakingengagements WITH REPLICATION = { 'class' : 'NetworkTopologyStrategy', 'datacenter1' : 1 };");
            Console.WriteLine(String.Format("created keyspace speakingengagements"));
            session.Execute("CREATE TABLE IF NOT EXISTS speakingengagements.presentation (presentation_id text PRIMARY KEY, presentation_owneremailaddress text, presentation_title text, presentation_abstract text, presentation_elevatorpitch text, presentation_importantinformation text, presentation_languagecode text, presentation_language text)");
            Console.WriteLine(String.Format("created table Presentation"));

            session = cluster.Connect("speakingengagements");
            IMapper mapper = new Mapper(session);

            // Inserting Data into presentation table
            mapper.Insert <Presentation>(Generate.Presentation(ExistingPresentation.EventDrivenArchitectureInTheCloud));
            mapper.Insert <Presentation>(Generate.Presentation(ExistingPresentation.GraphingYourWayThroughTheCosoms));
            mapper.Insert <Presentation>(Generate.Presentation(ExistingPresentation.TheHitchhikersGuideToTheCosoms));
            Console.WriteLine("Inserted data into presetnation table");

            Console.WriteLine("Select ALL");
            Console.WriteLine("-------------------------------");
            foreach (Presentation presentation in mapper.Fetch <Presentation>("Select * from presentation"))
            {
                Console.WriteLine(presentation);
            }

            Console.WriteLine("Getting by id Green.3");
            Console.WriteLine("-------------------------------");


            Presentation presentationId3 = mapper.FirstOrDefault <Presentation>("Select * from presentation where presentation_owneremailaddress = ?", "*****@*****.**");

            Console.WriteLine(presentationId3.presentation_title);

            // Clean up of Table and KeySpace
            //session.Execute("DROP table presetnation");
            //session.Execute("DROP KEYSPACE speakingengagements");

            // Wait for enter key before exiting
            Console.ReadLine();
        }
        public static void Main(string[] args)
        {
            // Connect to cassandra cluster  (Cassandra API on Azure Cosmos DB supports only TLSv1.2)
            var options = new Cassandra.SSLOptions(SslProtocols.Tls12, true, ValidateServerCertificate);

            options.SetHostNameResolver((ipAddress) => CassandraContactPoint);
            Cluster  cluster = Cluster.Builder().WithCredentials(Username, Password).WithPort(CassandraPort).AddContactPoint(CassandraContactPoint).WithSSL(options).Build();
            ISession session = cluster.Connect();

            // Creating KeySpace and table
            session.Execute("DROP KEYSPACE IF EXISTS uprofile");
            session.Execute("CREATE KEYSPACE uprofile WITH REPLICATION = { 'class' : 'NetworkTopologyStrategy', 'datacenter1' : 1 };");
            Console.WriteLine(String.Format("created keyspace uprofile"));
            session.Execute("CREATE TABLE IF NOT EXISTS uprofile.user (user_id int PRIMARY KEY, user_name text, user_bcity text)");
            Console.WriteLine(String.Format("created table user"));

            session = cluster.Connect("uprofile");
            IMapper mapper = new Mapper(session);

            // Inserting Data into user table
            mapper.Insert <UserEntity>(new UserEntity(1, "LyubovK", "Dubai"));
            mapper.Insert <UserEntity>(new UserEntity(2, "JiriK", "Toronto"));
            mapper.Insert <UserEntity>(new UserEntity(3, "IvanH", "Mumbai"));
            mapper.Insert <UserEntity>(new UserEntity(4, "LiliyaB", "Seattle"));
            mapper.Insert <UserEntity>(new UserEntity(5, "JindrichH", "Buenos Aires"));
            Console.WriteLine("Inserted data into user table");

            Console.WriteLine("Select ALL");
            Console.WriteLine("-------------------------------");
            foreach (UserEntity user in mapper.Fetch <UserEntity>("Select * from user"))
            {
                Console.WriteLine(user);
            }

            Console.WriteLine("Getting by id 3");
            Console.WriteLine("-------------------------------");
            UserEntity userId3 = mapper.FirstOrDefault <UserEntity>("Select * from user where user_id = ?", 3);

            Console.WriteLine(userId3);

            // Clean up of Table and KeySpace
            session.Execute("DROP table user");
            session.Execute("DROP KEYSPACE uprofile");

            // Wait for enter key before exiting
            Console.ReadLine();
        }
        private ICluster ConfigureCluster(IConfiguration configuration)
        {
            var host     = configuration["Cassandra:Hosts"];
            var port     = int.Parse(configuration["Cassandra:Port"]);
            var user     = configuration["Cassandra:Username"];
            var password = configuration["Cassandra:Password"];

            var options = new Cassandra.SSLOptions(SslProtocols.Tls12, true, ValidateServerCertificate);

            options.SetHostNameResolver((ipAddress) => host);

            return(Cluster.Builder()
                   .WithCredentials(user, password)
                   .WithPort(port)
                   .AddContactPoint(host)
                   .WithSSL(options)
                   .Build());
        }
Beispiel #8
0
        public static void Main(string[] args)
        {
            var options = new Cassandra.SSLOptions(SslProtocols.Tls12, true, ValidateServerCertificate);

            options.SetHostNameResolver((ipAddress) => contactPoint);

            Cluster cluster = Cluster.Builder()
                              .AddContactPoint(contactPoint)
                              .WithCredentials(username, password)
                              .WithPort(port)
                              .WithSSL(options)
                              .WithLoadBalancingPolicy(new CosmosDnsAwareRRPolicy(contactPoint))
                              .Build();
            ISession session      = cluster.Connect();
            string   keyspaceName = "ks1";
            string   tableName    = "tb1";

            try
            {
                session.Execute($"CREATE KEYSPACE IF NOT EXISTS {keyspaceName} with foo='bar'");
                session.Execute($"CREATE TABLE IF NOT EXISTS {keyspaceName}.{tableName} (pk int PRIMARY KEY, r1 int)");
                int i = 0;
                for (; i < 100; i++)
                {
                    session.Execute($"INSERT INTO {keyspaceName}.{tableName} (pk, r1) VALUES ({i}, {i})");
                    Console.WriteLine($"Written row {i}");
                    Thread.Sleep(500);
                }

                Console.WriteLine("Please trigger a manual failover from CosmosDB portal. Once it is done, hit ENTER, and new requests will be routed to the new write region.");
                Console.ReadKey();
                for (; i < 200; i++)
                {
                    session.Execute($"INSERT INTO {keyspaceName}.{tableName} (pk, r1) VALUES ({i}, {i})");
                    Console.WriteLine($"Written row {i}");
                    Thread.Sleep(1000);
                }
            }
            finally
            {
                session.Execute("DROP KEYSPACE IF EXISTS ks1");
            }
        }
Beispiel #9
0
        static void Main(string[] args)
        {
            // Connect to cassandra cluster  (Cassandra API on Azure Cosmos DB supports only TLSv1.2)
            var options = new Cassandra.SSLOptions(SslProtocols.Tls12, true, ValidateServerCertificate);

            options.SetHostNameResolver((ipAddress) => CassandraContactPoint);
            Cluster cluster = Cluster.Builder().WithCredentials(UserName, Password)
                              .WithPort(CassandraPort).AddContactPoint(CassandraContactPoint)
                              .WithSSL(options).Build();
            ISession session = cluster.Connect();

            session = cluster.Connect("keyspace01");

            IMapper mapper = new Mapper(session);

            mapper.Insert <People>(new People(1, "Reza", "*****@*****.**"));
            mapper.Insert <People>(new People(2, "John", "*****@*****.**"));
            mapper.Insert <People>(new People(3, "Mary", "*****@*****.**"));
        }
Beispiel #10
0
        public static async Task ProcessAsync()
        {
            // Connect to cassandra cluster  (Cassandra API on Azure Cosmos DB supports only TLSv1.2)
            var options = new Cassandra.SSLOptions(SslProtocols.Tls12, true, ValidateServerCertificate);

            options.SetHostNameResolver((ipAddress) => CASSANDRACONTACTPOINT);
            Cluster cluster = Cluster
                              .Builder()
                              .WithCredentials(USERNAME, PASSWORD)
                              .WithPort(CASSANDRAPORT)
                              .AddContactPoint(CASSANDRACONTACTPOINT)
                              .WithSSL(options)
                              .Build()
            ;

            ISession session = await cluster.ConnectAsync();

            // Creating KeySpace and table
            await session.ExecuteAsync(new SimpleStatement("DROP KEYSPACE IF EXISTS uprofile"));

            await session.ExecuteAsync(new SimpleStatement("CREATE KEYSPACE uprofile WITH REPLICATION = { 'class' : 'NetworkTopologyStrategy', 'datacenter1' : 1 };"));

            Console.WriteLine(String.Format("created keyspace uprofile"));
            await session.ExecuteAsync(new SimpleStatement("CREATE TABLE IF NOT EXISTS uprofile.user (user_id int PRIMARY KEY, user_name text, user_bcity text)"));

            Console.WriteLine(String.Format("created table user"));

            session = await cluster.ConnectAsync("uprofile");

            IMapper mapper = new Mapper(session);

            // Inserting Data into user table
            await mapper.InsertAsync <User>(new User(1, "LyubovK", "Dubai"));

            await mapper.InsertAsync <User>(new User(2, "JiriK", "Toronto"));

            await mapper.InsertAsync <User>(new User(3, "IvanH", "Mumbai"));

            await mapper.InsertAsync <User>(new User(4, "LiliyaB", "Seattle"));

            await mapper.InsertAsync <User>(new User(5, "JindrichH", "Buenos Aires"));

            Console.WriteLine("Inserted data into user table");

            Console.WriteLine("Select ALL");
            Console.WriteLine("-------------------------------");
            foreach (User user in await mapper.FetchAsync <User>("Select * from user"))
            {
                Console.WriteLine(user);
            }

            Console.WriteLine("Getting by id 3");
            Console.WriteLine("-------------------------------");
            User userId3 = await mapper.FirstOrDefaultAsync <User>("Select * from user where user_id = ?", 3);

            Console.WriteLine(userId3);

            // Clean up of Table and KeySpace - commented out since other QuickStarts do not immediately delete what was done,
            // and so QuickStart user (that's you) has chance to go look at this data in Cosmos DB
            //session.Execute("DROP table user");
            //session.Execute("DROP KEYSPACE uprofile");
        }
Beispiel #11
0
        public static void Main(string[] args)
        {
            // validate UserName
            if (string.IsNullOrEmpty(UserName))
            {
                Console.WriteLine("Invalid User Name\n\nExport cname environment value");
                return;
            }

            // validate password
            if (string.IsNullOrEmpty(Password))
            {
                Console.WriteLine("Invalid Password\n\nExport cpass environment value");
                return;
            }

            string CassandraContactPoint = UserName + ".cassandra.cosmosdb.azure.com";
            int    CassandraPort         = 10350;

            // Connect to cassandra cluster  (Cassandra API on Azure Cosmos DB supports only TLSv1.2)
            var options = new Cassandra.SSLOptions(SslProtocols.Tls12, true, ValidateServerCertificate);

            options.SetHostNameResolver((ipAddress) => CassandraContactPoint);
            Cluster  cluster = Cluster.Builder().WithCredentials(UserName, Password).WithPort(CassandraPort).AddContactPoint(CassandraContactPoint).WithSSL(options).Build();
            ISession session = cluster.Connect("myapp");

            Console.WriteLine("connected to myapp");

            // create a new table each time the app runs
            session.Execute("DROP TABLE IF EXISTS user;");

            // Create table
            // Set CosmosDB RUs to 400 (lowest possible)
            session.Execute("CREATE TABLE IF NOT EXISTS user (userid int, name text, PRIMARY KEY (userid)) WITH cosmosdb_provisioned_throughput=400");

            const string sql = "insert into user (userid, name) values ({0}, '{1}')";
            int          id  = 0;

            // insert via execute
            session.Execute(string.Format(sql, ++id, "Bart"));
            session.Execute(string.Format(sql, ++id, "Carla"));
            session.Execute(string.Format(sql, ++id, "Joshua"));
            session.Execute(string.Format(sql, ++id, "Sasha"));

            IMapper mapper = new Mapper(session);

            // insert via mapper (just another way to insert)
            mapper.Insert <User>(new User(++id, "Matthew"));

            // query via mapper
            Console.WriteLine("Select ALL");
            Console.WriteLine("-------------------------------");
            foreach (User user in mapper.Fetch <User>("Select * from user"))
            {
                Console.WriteLine(user);
            }

            Console.WriteLine("\n\nSelect one user");
            Console.WriteLine("-------------------------------");

            // query via RowSet
            var rs = session.Execute("select userid, name from user where userid = 1");

            foreach (var r in rs)
            {
                int    userid = r.GetValue <int>(0);
                string name   = r.GetValue <string>(1);
                Console.WriteLine(string.Format(" {0} | {1} ", userid, name));
            }
        }