Beispiel #1
0
        public LinqUserManagementService(IDseSession session, PreparedStatementCache statementCache, IBus bus, UserManagementOptions options)
        {
            if (session == null)
            {
                throw new ArgumentNullException(nameof(session));
            }
            if (statementCache == null)
            {
                throw new ArgumentNullException(nameof(statementCache));
            }
            if (bus == null)
            {
                throw new ArgumentNullException(nameof(bus));
            }
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }
            _session        = session;
            _statementCache = statementCache;
            _bus            = bus;
            _options        = options;

            _userProfileTable     = new Table <LinqDtos.UserProfile>(session);
            _userCredentialsTable = new Table <UserCredentials>(session);
        }
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;

            String create_keyspace   = @"CREATE KEYSPACE IF NOT EXISTS driver_test 
                                          WITH REPLICATION = { 
                                           'class' : 'NetworkTopologyStrategy', 
                                           'DC1' : 1 
                                          } ;
                                        ";
            String create_user_table = @"CREATE TABLE IF NOT EXISTS driver_test.user (
                                            id uuid, 
                                            first_name text, 
                                            last_name text, 
                                            PRIMARY KEY (id)
                                        );";

            IDseCluster cluster = DseCluster.Builder()
                                  .AddContactPoint("127.0.0.1")
                                  .Build();
            IDseSession session = cluster.Connect();

            session.Execute(create_keyspace);
            session.Execute(create_user_table);

            session.Dispose();
        }
Beispiel #3
0
 public DataStaxEnterpriseSearch(IDseSession session, PreparedStatementCache statementCache,
                                 IFindServices serviceDiscovery, Func <Uri, IRestClient> createRestClient,
                                 SearchOptions options)
 {
     if (session == null)
     {
         throw new ArgumentNullException(nameof(session));
     }
     if (statementCache == null)
     {
         throw new ArgumentNullException(nameof(statementCache));
     }
     if (serviceDiscovery == null)
     {
         throw new ArgumentNullException(nameof(serviceDiscovery));
     }
     if (createRestClient == null)
     {
         throw new ArgumentNullException(nameof(createRestClient));
     }
     if (options == null)
     {
         throw new ArgumentNullException(nameof(options));
     }
     _session          = session;
     _statementCache   = statementCache;
     _serviceDiscovery = serviceDiscovery;
     _createRestClient = createRestClient;
     _options          = options;
     _dseSearchUri     = null;
 }
Beispiel #4
0
        public static void Main()
        {
            IDseCluster cluster = DseCluster.Builder().
                                  AddContactPoint("127.0.0.1").
                                  WithGraphOptions(new GraphOptions().SetName("killrvideo")).
                                  Build();
            IDseSession session = cluster.Connect();
            var         killr   = DseGraph.Traversal(session);

            PrintHeader("Actors for Young Guns", "killr.Movies(\"Young Guns\").Actors().Values(\"name\")");
            var results = killr.Movies("Young Guns").Actors().Values <string>("name").ToList();

            PrintItems(results);

            PrintHeader("Ratings Distribution by Age for Young Guns", "killr.Movies(\"Young Guns\").Ratings().DistributionForAges(18, 40)");
            IDictionary <string, long> ratingsByAge = killr.Movies("Young Guns").Ratings().DistributionForAges(18, 40).Next();
            var pairs = String.Join(", ", ratingsByAge.Select(kvp => kvp.Key + "=" + kvp.Value.ToString()));

            Console.WriteLine($"[{pairs}]");

            PrintHeader("Failed Validation", "killr.Movies(\"Young Guns\").Ratings().DistributionForAges(17,40)");
            try
            {
                killr.Movies("Young Guns").Ratings().DistributionForAges(17, 40).Next();
            }
            catch (ArgumentException ae)
            {
                Console.WriteLine($"Caught ArgumentException: {ae.Message}");
            }

            PrintHeader("Five Recommendations for u460", "killr.Users(\"u460\").Recommend(5, 7).Values(KEY_TITLE)");
            results = killr.Users("u460").Recommend(5, 7).Values <string>(KeyTitle).ToList();
            PrintItems(results);

            PrintHeader("Five Recommendations for u460 that are comedies", "killr.Users(\"u460\").Recommend(5, 7, Genre(COMEDY)).Values(KEY_TITLE)");
            results = killr.Users("u460").Recommend(5, 7, Genre(Comedy)).Values <string>(KeyTitle).ToList();
            PrintItems(results);

            PrintHeader("Five Recommendations for u460 that use larger actor sampling and are comedies", "killr.users(\"u460\").recommend(5, 7, genre(COMEDY)).values(KEY_TITLE)");
            results = killr.Users("u460").Recommend(5, 7, LargeSample, Genre(Comedy)).Values <string>(KeyTitle).ToList();
            PrintItems(results);

            PrintHeader("Include some additional graph statistics about Young Guns", "killr.movies(\"Young Guns\").enrich(IN_DEGREE, OUT_DEGREE)");
            IDictionary <object, object> enriched = killr.Movies("Young Guns").enrich(InDegree, OutDegree).Next();

            pairs = String.Join(", ", enriched.Select(kvp => kvp.Key + "=" + kvp.Value.ToString()));
            Console.WriteLine($"[{pairs}]");

            PrintHeader("Insert/update movie and a actors for that movie", "killr.movie(\"m100000\", \"Manos: The Hands of Fate\",...).actor(...)");
            killr.Movie("m100000", "Manos: The Hands of Fate", 1966, 70, "USA", "Sun City Films").
            Ensure <Vertex, object, Vertex>(__KillrVideo.Actor("p1000000", "Tom Neyman")).
            Ensure <Vertex, object, Vertex>(__KillrVideo.Actor("p1000001", "John Reynolds")).
            Ensure <Vertex, object, Vertex>(__KillrVideo.Actor("p1000002", "Diane Mahree")).
            Iterate();
            Console.WriteLine("Updated 'Manos: The Hands of Fate'");

            PrintHeader("Get the actors for the newly added movie", "killr.movies(\"Manos: The Hands of Fate\").actors().values(\"name\")");
            results = killr.Movies("Manos: The Hands of Fate").Actors().Values <String>("name").ToList();
            PrintItems(results);
        }
 public void TestFixtureSetup()
 {
     if (Values == null || Values.Length == 0)
     {
         throw new InconclusiveException("You must specify the values to test");
     }
     CcmHelper.Start(1);
     Cluster = DseCluster.Builder().AddContactPoint(CcmHelper.InitialContactPoint).Build();
     Trace.TraceInformation("Waiting additional time for test Cluster to be ready");
     Thread.Sleep(15000);
     Session = Cluster.Connect();
     Session.Execute(string.Format(CreateKeyspaceQuery, Keyspace));
     Session.Execute(string.Format("USE {0}", Keyspace));
     _queries = new[]
     {
         string.Format("CREATE TABLE geotable1 (id text, value '{0}', PRIMARY KEY (id))", TypeName),
         string.Format("CREATE TABLE keyed (id '{0}', value text, PRIMARY KEY (id))", TypeName),
         string.Format("INSERT INTO keyed (id, value) VALUES ('{0}', 'hello')", Values[0]),
         string.Format("CREATE TYPE geo_udt (f text, v '{0}')", TypeName),
         "CREATE TABLE tbl_udts (id uuid PRIMARY KEY, value frozen<geo_udt>)",
         string.Format("CREATE TABLE tbl_tuple (id uuid PRIMARY KEY, value tuple<int, '{0}'>)", TypeName),
         string.Format("CREATE TABLE tbl_list (id uuid PRIMARY KEY, value list<'{0}'>)", TypeName),
         string.Format("CREATE TABLE tbl_set (id uuid PRIMARY KEY, value set<'{0}'>)", TypeName),
         string.Format("CREATE TABLE tbl_map (id uuid PRIMARY KEY, value map<text, '{0}'>)", TypeName)
     };
     foreach (var query in _queries)
     {
         Session.Execute(query);
     }
 }
 /// <summary>
 /// Creates a graph using the current session
 /// </summary>
 public void CreateClassicGraph(IDseSession session, string name)
 {
     session.ExecuteGraph(new SimpleGraphStatement(string.Format("system.graph('{0}').ifNotExists().create()", name)));
     session.ExecuteGraph(new SimpleGraphStatement(MakeStrict).SetGraphName(name));
     session.ExecuteGraph(new SimpleGraphStatement(AllowScans).SetGraphName(name));
     session.ExecuteGraph(new SimpleGraphStatement(ClassicSchemaGremlinQuery).SetGraphName(name));
     session.ExecuteGraph(new SimpleGraphStatement(ClassicLoadGremlinQuery).SetGraphName(name));
 }
        public SessionManager()
        {
            cluster = DseCluster.Builder().AddContactPoint("127.0.0.1").Build();
            session = cluster.Connect("test");
            var row = session.Execute("select * from system.local").First();

            Console.WriteLine("Podłączono do klastra " + row.GetValue <string>("cluster_name"));
            PrepareStatements();
        }
        /// <summary>
        /// Create a new TaskCache using the provided factoryFunc to generate items from keys.
        /// </summary>
        public PreparedStatementCache(IDseSession session)
        {
            if (session == null)
            {
                throw new ArgumentNullException(nameof(session));
            }
            _session = session;

            _cachedItems = new ConcurrentDictionary <string, Lazy <Task <PreparedStatement> > >();
        }
Beispiel #9
0
 public void OneTimeSetUp()
 {
     TestClusterManager.CreateNew(1, new TestClusterOptions {
         Workloads = new[] { "graph" }
     });
     CreateClassicGraph(TestClusterManager.InitialContactPoint, GraphName);
     _cluster = DseCluster.Builder()
                .AddContactPoint(TestClusterManager.InitialContactPoint)
                .WithGraphOptions(new GraphOptions().SetName(GraphName))
                .Build();
     _session = _cluster.Connect();
 }
 /// <summary>
 /// Constructor with proper injection
 /// </summary>
 public YouTubeVideoAddedEventConsumer(IDseSession session, IBus bus)
 {
     if (session == null)
     {
         throw new ArgumentNullException(nameof(session));
     }
     if (bus == null)
     {
         throw new ArgumentNullException(nameof(bus));
     }
     _session = session;
     _bus     = bus;
 }
Beispiel #11
0
 public UpdateSearchOnVideoAdded(IDseSession session, PreparedStatementCache statementCache)
 {
     if (session == null)
     {
         throw new ArgumentNullException(nameof(session));
     }
     if (statementCache == null)
     {
         throw new ArgumentNullException(nameof(statementCache));
     }
     _session        = session;
     _statementCache = statementCache;
 }
Beispiel #12
0
 /// <summary>
 /// Constructor with proper injection
 /// </summary>
 public UserCreatedEventConsumer(IDseSession session, IBus bus)
 {
     if (session == null)
     {
         throw new ArgumentNullException(nameof(session));
     }
     if (bus == null)
     {
         throw new ArgumentNullException(nameof(bus));
     }
     _session = session;
     _bus     = bus;
 }
Beispiel #13
0
 public StatisticsServiceImpl(IDseSession session, PreparedStatementCache statementCache)
 {
     if (session == null)
     {
         throw new ArgumentNullException(nameof(session));
     }
     if (statementCache == null)
     {
         throw new ArgumentNullException(nameof(statementCache));
     }
     _session        = session;
     _statementCache = statementCache;
 }
        public Guid Post([FromBody] User user)
        {
            IDseCluster cluster = DseCluster.Builder()
                                  .AddContactPoint("127.0.0.1")
                                  .Build();
            IDseSession session     = cluster.Connect();
            Guid        user_id     = Guid.NewGuid();
            var         insert_user = session.Prepare(
                "INSERT INTO driver_test.user (id, first_name, last_name) VALUES(?,?,?)"
                );
            RowSet results = session.Execute(insert_user.Bind(user_id, user.first_name, user.last_name));

            return(user_id);
        }
        public CassandraDBRepository(IOptions <CassandraDBOptions> optionsAccessor, ILoggerFactory loggerFactory)
        {
            var         options = optionsAccessor.Value;
            IDseCluster cluster = DseCluster.Builder()
                                  .AddContactPoints(options.ContactPoints.Split(','))
                                  .WithAuthProvider(new DsePlainTextAuthProvider(options.Username, options.Password))
                                  .Build();

            session = cluster.Connect();

            tableName = options.Tablename;

            logger = loggerFactory.CreateLogger <CassandraDBRepository>();
        }
Beispiel #16
0
        static WarmPathFunction()
        {
            var contactPoints = Environment.GetEnvironmentVariable("CassandraContactPoints", EnvironmentVariableTarget.Process);
            var username      = Environment.GetEnvironmentVariable("CassandraUsername", EnvironmentVariableTarget.Process);
            var password      = Environment.GetEnvironmentVariable("CassandraPassword", EnvironmentVariableTarget.Process);

            tableName = Environment.GetEnvironmentVariable("CassandraTableName", EnvironmentVariableTarget.Process);

            IDseCluster cluster = DseCluster.Builder()
                                  .AddContactPoints(contactPoints.Split(','))
                                  .WithAuthProvider(new DsePlainTextAuthProvider(username, password))
                                  .Build();

            session = cluster.Connect();
        }
Beispiel #17
0
 public RatingsServiceImpl(IDseSession session, PreparedStatementCache statementCache, IBus bus)
 {
     if (session == null)
     {
         throw new ArgumentNullException(nameof(session));
     }
     if (statementCache == null)
     {
         throw new ArgumentNullException(nameof(statementCache));
     }
     if (bus == null)
     {
         throw new ArgumentNullException(nameof(bus));
     }
     _session        = session;
     _statementCache = statementCache;
     _bus            = bus;
 }
 public UpdateUploadedVideoWhenPublished(IDseSession session, PreparedStatementCache statementCache, IBus bus)
 {
     if (session == null)
     {
         throw new ArgumentNullException(nameof(session));
     }
     if (statementCache == null)
     {
         throw new ArgumentNullException(nameof(statementCache));
     }
     if (bus == null)
     {
         throw new ArgumentNullException(nameof(bus));
     }
     _session        = session;
     _statementCache = statementCache;
     _bus            = bus;
 }
        public Table <User> GetTable()
        {
            IDseCluster cluster = DseCluster.Builder()
                                  .AddContactPoint("127.0.0.1")
                                  .Build();
            IDseSession session = cluster.Connect();

            MappingConfiguration.Global.Define(
                new Map <User>()
                .TableName("user")
                .PartitionKey(u => u.Id)
                .Column(u => u.Id, cm => cm.WithName("id"))
                .Column(u => u.FirstName, cm => cm.WithName("first_name"))
                .Column(u => u.LastName, cm => cm.WithName("last_name")));
            var users = new Table <User>(session);

            return(users);
        }
Beispiel #20
0
 public VideoCatalogServiceImpl(IDseSession session, PreparedStatementCache statementCache, IBus bus)
 {
     if (session == null)
     {
         throw new ArgumentNullException(nameof(session));
     }
     if (statementCache == null)
     {
         throw new ArgumentNullException(nameof(statementCache));
     }
     if (bus == null)
     {
         throw new ArgumentNullException(nameof(bus));
     }
     _session        = session;
     _statementCache = statementCache;
     _bus            = bus;
     Logger.Information("Video Catalog is initialized");
 }
        public string Get(Guid id)
        {
            IDseCluster cluster = DseCluster.Builder()
                                  .AddContactPoint("127.0.0.1")
                                  .Build();
            IDseSession session = cluster.Connect();

            var    get_user = session.Prepare("SELECT * FROM driver_test.user where id = ?");
            RowSet results  = session.Execute(get_user.Bind(id));

            if (results.Any())
            {
                session.Dispose();
                Row user = results.First();
                return(user.GetValue <String>("first_name") + user.GetValue <String>("last_name"));
            }
            else
            {
                session.Dispose();
                return("User not found");
            }
        }
        public IEnumerable <string> Get()
        {
            IDseCluster cluster = DseCluster.Builder()
                                  .AddContactPoint("127.0.0.1")
                                  .Build();
            IDseSession session = cluster.Connect();

            var    get_users = session.Prepare("SELECT * FROM driver_test.user");
            RowSet results   = session.Execute(get_users.Bind());

            List <string> final_results = new List <string>();

            foreach (Row row in results.AsEnumerable())
            {
                final_results.Add(row.GetValue <Guid>("id").ToString() + " " +
                                  row.GetValue <String>("first_name") + " " +
                                  row.GetValue <String>("last_name") + "\n");
            }


            return(final_results);
        }
 public UserManagementServiceImpl(IDseSession session, PreparedStatementCache statementCache, IBus bus, UserManagementOptions options)
 {
     if (session == null)
     {
         throw new ArgumentNullException(nameof(session));
     }
     if (statementCache == null)
     {
         throw new ArgumentNullException(nameof(statementCache));
     }
     if (bus == null)
     {
         throw new ArgumentNullException(nameof(bus));
     }
     if (options == null)
     {
         throw new ArgumentNullException(nameof(options));
     }
     _session        = session;
     _statementCache = statementCache;
     _bus            = bus;
     _options        = options;
 }
Beispiel #24
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            IDseCluster cluster = DseCluster.Builder().
                                  AddContactPoint("127.0.0.1").
                                  WithGraphOptions(new GraphOptions().SetName("STUDIO_TUTORIAL_GRAPH")).
                                  Build();
            IDseSession session = cluster.Connect();
            var         g       = DseGraph.Traversal(session);

            System.Console.WriteLine(g.V().Gods().As("g").Select <string>("g").By("name").Next());
            System.Console.WriteLine(g.V().Gods().As("g").As("t").SelectBy <string>("g.name").Next());
            System.Console.WriteLine(g.V().Gods().As("g").SelectValues <string>("g").Next());
            var items = g.V().Gods().As("g").SelectValueMap <Dictionary <string, object> >("g").ToList();

            foreach (var item in items)
            {
                Console.WriteLine(item);
            }

            var arr = new string[] { "g.name", "t.name" };
            var t   = g.V().Gods().As("g").As("t").SelectBy <Object>(arr).Next();

            foreach (var r in t)
            {
                Console.WriteLine(r);
            }

            arr = new string[] { "g.name", "t.name", "p.name" };
            var l = g.V().Gods().As("g").As("t").As("p").SelectBy <Object>(arr).Next();

            foreach (var r in l)
            {
                Console.WriteLine(r);
            }
        }
        /// <summary>
        /// Register the singleton ISession instance with the container once we can connect to the killrvideo schema.
        /// </summary>
        public async Task RegisterDseOnceAvailable(DryIoc.IContainer container)
        {
            IDseSession session  = null;
            int         attempts = 0;

            Logger.Information("Initializing connection to DSE Cluster...");
            while (session == null)
            {
                try
                {
                    Logger.Information("+ Reading node addresses from ETCD.");
                    IEnumerable <string> hosts = await _serviceDiscovery
                                                 .LookupServiceAsync(ConfigKeys.EtcdCassandraKey)
                                                 .ConfigureAwait(false);

                    // Create cluster builder with contact points
                    var builder = DseCluster.Builder().AddContactPoints(hosts.Select(ToIpEndPoint));

                    // Authentication
                    if (!string.IsNullOrEmpty(_kvConfig[ConfigKeys.DseUsername]) &&
                        !string.IsNullOrEmpty(_kvConfig[ConfigKeys.DsePassword]))
                    {
                        Logger.Information("+ Enable Authentication with user {user}", _kvConfig[ConfigKeys.DseUsername]);
                        builder.WithAuthProvider(
                            new DsePlainTextAuthProvider(_kvConfig[ConfigKeys.DseUsername],
                                                         _kvConfig[ConfigKeys.DsePassword]));
                    }
                    else
                    {
                        Logger.Information("+ No Authentication");
                    }

                    // SSL : To be tested (first try based on documentation)
                    if (Boolean.Parse(_kvConfig[ConfigKeys.DseEnableSsl]))
                    {
                        String certPath     = _kvConfig[ConfigKeys.DseSslCertPath];
                        String certPassword = _kvConfig[ConfigKeys.DseSslCertPassword];
                        if (string.IsNullOrEmpty(certPath))
                        {
                            throw new ArgumentNullException("Cannot read SSL File " + certPath);
                        }
                        if (string.IsNullOrEmpty(certPath))
                        {
                            throw new ArgumentNullException("Cannot read SSL Certificate password " + certPath);
                        }
                        Logger.Information("+ Setup SSL options with {certPath}", certPath);
                        SSLOptions         sslOptions = new SSLOptions();
                        X509Certificate2[] certs      = new X509Certificate2[] { new X509Certificate2(ReadX509Certificate(certPath), certPassword) };
                        sslOptions.SetCertificateCollection(new X509CertificateCollection(certs));
                        sslOptions.SetRemoteCertValidationCallback((a1, a2, a3, a4) => true);
                        //sslOptions.SetHostNameResolver((internalIPAddress) => { return "test_client"; });
                        builder.WithSSL(sslOptions);
                    }
                    else
                    {
                        Logger.Information("+ No SSL");
                    }

                    // Query options
                    var queryOptions = new QueryOptions();
                    queryOptions.SetConsistencyLevel(ConsistencyLevel.LocalQuorum);
                    builder.WithQueryOptions(queryOptions);

                    // Graph Options
                    Logger.Information("+ Graph connection to {graphName}", _kvConfig[ConfigKeys.DseGraphName]);
                    var graphOptions = new GraphOptions();
                    graphOptions.SetName(_kvConfig[ConfigKeys.DseGraphName]);
                    graphOptions.SetReadTimeoutMillis(int.Parse(_kvConfig[ConfigKeys.DseGraphReadTimeout]));
                    graphOptions.SetReadConsistencyLevel(ConsistencyLevel.One);
                    graphOptions.SetWriteConsistencyLevel(ConsistencyLevel.One);
                    builder.WithGraphOptions(graphOptions);

                    // Cassandra
                    session = builder.Build().Connect(_kvConfig[ConfigKeys.DseKeySpace]);
                    Logger.Information("+ Session established to keyspace {keyspace}", _kvConfig[ConfigKeys.DseKeySpace]);
                }
                catch (Exception e)
                {
                    attempts++;
                    session = null;

                    // Don't log exceptions until we've tried 6 times
                    if (attempts >= int.Parse(_kvConfig[ConfigKeys.MaxRetry]))
                    {
                        Logger.Error(e,
                                     "Cannot connection to DSE after {max} attempts, exiting",
                                     _kvConfig[ConfigKeys.MaxRetry]);
                        Environment.Exit(404);
                    }
                }

                if (session != null)
                {
                    continue;
                }

                Logger.Information("+ Attempt #{nb}/{max} failed.. trying in {delay} seconds, waiting Dse to Start",
                                   attempts,
                                   _kvConfig[ConfigKeys.MaxRetry],
                                   _kvConfig[ConfigKeys.RetryDelay]);
                await Task.Delay(int.Parse(_kvConfig[ConfigKeys.RetryDelay])).ConfigureAwait(false);
            }

            // Since session objects should be created once and then reused, register the instance with the container
            // which will register it as a singleton by default
            container.RegisterInstance(session);
        }
Beispiel #26
0
            public DseGraphNativeQueryProvider(IDseSession session)
            {
                this._session = session;

                this.TraversalSource = GremlinQuery.Create((this._session.Cluster as IDseCluster)?.Configuration.GraphOptions.Source ?? "g");
            }
Beispiel #27
0
 public static INativeGremlinQueryProvider CreateQueryProvider(this IDseSession session)
 {
     return(new DseGraphNativeQueryProvider(session));
 }
 /// <summary>
 /// Creates a graph using the current session
 /// </summary>
 public void CreateClassicGraph(IDseSession session, string name)
 {
     session.ExecuteGraph(new SimpleGraphStatement(string.Format("system.graph('{0}').ifNotExists().create()", name)));
     session.ExecuteGraph(new SimpleGraphStatement(MakeStrict).SetGraphName(name));
     session.ExecuteGraph(new SimpleGraphStatement(AllowScans).SetGraphName(name));
     session.ExecuteGraph(new SimpleGraphStatement(ClassicSchemaGremlinQuery).SetGraphName(name));
     session.ExecuteGraph(new SimpleGraphStatement(ClassicLoadGremlinQuery).SetGraphName(name));
 }