Exemple #1
0
 public RiakLoader(IRiakClient riakClient, IEventReader eventReader)
 {
     if (riakClient == null) throw new ArgumentNullException("riakClient");
     if (eventReader == null) throw new ArgumentNullException("eventReader");
     _riakClient = riakClient;
     _eventReader = eventReader;
 }
Exemple #2
0
        private static void FetchData()
        {
            Console.WriteLine("[ChaosMonkeyApp] fetch thread starting");
            IRiakClient client = cluster.CreateClient();
            var         r      = new Random((int)DateTimeUtil.ToUnixTimeMillis(DateTime.Now));

            try
            {
                while (true)
                {
                    int k    = r.Next(0, key);
                    var id   = new RiakObjectId("chaos-monkey", k.ToString());
                    var rslt = client.Get(id);
                    if (rslt.IsSuccess)
                    {
                        Console.WriteLine("[ChaosMonkeyApp] got key: {0}", k);
                    }
                    else
                    {
                        Console.WriteLine("[ChaosMonkeyApp] error getting key {0}, {1}", k, rslt.ErrorMessage);
                    }
                    Thread.Sleep(fetchDataInterval);
                    ct.ThrowIfCancellationRequested();
                }
            }
            finally
            {
                Console.WriteLine("[ChaosMonkeyApp] fetch thread stopping");
            }
        }
        public static Func <RiakResult <RiakSearchResult> > RunSolrQuery(this IRiakClient client, RiakSearchRequest req)
        {
            Func <RiakResult <RiakSearchResult> > runSolrQuery =
                () => client.Search(req);

            return(runSolrQuery);
        }
Exemple #4
0
        private static void FetchServerInfo()
        {
            Console.WriteLine("[ChaosMonkeyApp] fetch server info thread starting");
            IRiakClient client = cluster.CreateClient();

            try
            {
                while (true)
                {
                    var cmd  = new FetchServerInfo();
                    var rslt = client.Execute(cmd);
                    if (rslt.IsSuccess)
                    {
                        var rsp = cmd.Response;
                        var n   = rsp.Value.Node;
                        var v   = rsp.Value.ServerVersion;
                        // Console.WriteLine("[ChaosMonkeyApp] got server info: {0}, {1}", n, v);
                    }
                    else
                    {
                        Console.WriteLine("[ChaosMonkeyApp] error getting server info: {0}", rslt.ErrorMessage);
                    }
                    Thread.Sleep(fetchDataInterval);
                    ct.ThrowIfCancellationRequested();
                }
            }
            finally
            {
                Console.WriteLine("[ChaosMonkeyApp] fetch server info thread stopping");
            }
        }
Exemple #5
0
        private static void StoreData()
        {
            Console.WriteLine("[ChaosMonkeyApp] store thread starting");
            IRiakClient client = cluster.CreateClient();

            try
            {
                while (true)
                {
                    var id  = new RiakObjectId("chaos-monkey", key.ToString());
                    var obj = new RiakObject(id, Guid.NewGuid().ToString());
                    obj.ContentEncoding = RiakConstants.CharSets.Utf8;
                    obj.ContentType     = RiakConstants.ContentTypes.TextPlain;

                    var rslt = client.Put(obj);
                    if (rslt.IsSuccess)
                    {
                        Console.WriteLine("[ChaosMonkeyApp] stored key: {0}", key);
                    }
                    else
                    {
                        Console.WriteLine("[ChaosMonkeyApp] error storing key {0}, {1}", key, rslt.ErrorMessage);
                    }

                    ++key;
                    Thread.Sleep(storeDataInterval);
                    ct.ThrowIfCancellationRequested();
                }
            }
            finally
            {
                Console.WriteLine("[ChaosMonkeyApp] store thread stopping");
            }
        }
        public override void Initialize(string name, NameValueCollection config)
        {
            if (config == null)
                throw new ArgumentNullException("config");

            if (String.IsNullOrEmpty(name))
                name = "RiakSessionStateStore";

            base.Initialize(name, config);

            ApplicationName = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath;

            Configuration cfg = WebConfigurationManager.OpenWebConfiguration(ApplicationName);
            _config = (SessionStateSection)cfg.GetSection("system.web/sessionState");

            var container = UnityBootstrapper.Bootstrap();
            _client = container.Resolve<IRiakClient>();

            var riakSessionConfiguration = container.Resolve<RiakSessionStateConfiguration>();
            int expiredSessionDeletionInterval = riakSessionConfiguration.TimeoutInMilliseconds;

            _expiredSessionDeletionTimer = new System.Timers.Timer(expiredSessionDeletionInterval);
            _expiredSessionDeletionTimer.Elapsed += ExpiredSessionDeletionTimerElapsed;
            _expiredSessionDeletionTimer.Enabled = true;
            _expiredSessionDeletionTimer.AutoReset = true;
        }
Exemple #7
0
        static void Main(string[] args)
        {
            using (IRiakEndPoint endpoint = RiakCluster.FromConfig("riakConfig"))
            {
                IRiakClient        client       = endpoint.CreateClient();
                UserRepository     userRepo     = new UserRepository(client);
                MsgRepository      msgRepo      = new MsgRepository(client);
                TimelineRepository timelineRepo = new TimelineRepository(client);
                TimelineManager    timelineMgr  = new TimelineManager(timelineRepo, msgRepo);

                // Create and save users
                var marleen = new User("marleenmgr", "Marleen Manager", "*****@*****.**");
                var joe     = new User("joeuser", "Joe User", "*****@*****.**");
                userRepo.Save(marleen);
                userRepo.Save(joe);

                // Create new Msg, post to timelines
                Msg msg = new Msg(marleen.UserName, joe.UserName, "Welcome to the company!");
                timelineMgr.PostMsg(msg);

                // Get Joe's inbox for today, get first message
                Timeline joesInboxToday = timelineMgr.GetTimeline(joe.UserName, Timeline.TimelineType.Inbox, DateTime.UtcNow);
                Msg      joesFirstMsg   = msgRepo.Get(joesInboxToday.MsgKeys.First());

                Console.WriteLine("From: " + joesFirstMsg.Sender);
                Console.WriteLine("Msg : " + joesFirstMsg.Text);
            }
        }
Exemple #8
0
        //eejmplo

        public Form1()
        {
            InitializeComponent();
            IRiakEndPoint cluster = RiakCluster.FromConfig("riakConfig");

            client = cluster.CreateClient();
        }
Exemple #9
0
 public Repository(IRiakClient client)
 {
     if (client == null)
     {
         throw new ArgumentNullException("client");
     }
     this.client = client;
 }
Exemple #10
0
        public static Func <RiakResult <RiakMapReduceResult> > RunMapReduceQuery(
            this IRiakClient client, RiakMapReduceQuery req)
        {
            Func <RiakResult <RiakMapReduceResult> > runMapRedQuery =
                () => client.MapReduce(req);

            return(runMapRedQuery);
        }
Exemple #11
0
 public UnitOfWork(IRiakClient client, IMessageMapper mapper)
 {
     _client    = client;
     _mapper    = mapper;
     _tracked   = new ConcurrentDictionary <RiakObjectId, RiakObject>();
     _saves     = new ConcurrentDictionary <RiakObjectId, RiakObject>();
     _updates   = new ConcurrentDictionary <RiakObjectId, RiakObject>();
     _deletions = new ConcurrentBag <RiakObjectId>();
 }
        public YakRiak(IRiakClient riakClient)
        {
            _riakClient = riakClient;
            // used for waiting for random periods of time
            _rnd = new Random();

            // this is the start date that we need to compare times against to
            // keep the timestamps in sync with YakRiak server
            _timeStart = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        }
        public BlogPostRepository(IRiakClient client, string bucket)
            : base(client)
        {
            if (string.IsNullOrWhiteSpace(bucket))
            {
                throw new ArgumentNullException("bucket");
            }

            this.bucket = bucket;
        }
        public RiakPersistenceStrategy(IRiakClusterConfiguration riakClusterConfiguration, IEventReaderWriterPair eventReaderWriterPair)
        {
            if (riakClusterConfiguration == null) throw new ArgumentNullException("riakClusterConfiguration");
            if (eventReaderWriterPair == null) throw new ArgumentNullException("eventReaderWriterPair");

            _riakClient = new RiakCluster(riakClusterConfiguration, new RiakConnectionFactory()).CreateClient();

            _storer = new RiakStorer(_riakClient, eventReaderWriterPair.Writer);
            _loader = new RiakLoader(_riakClient, eventReaderWriterPair.Reader);
        }
Exemple #15
0
        public void ShortReadTimeoutMayResultInError()
        {
            IRiakEndPoint cluster = RiakCluster.FromConfig("riakShortReadConfiguration");
            IRiakClient   client  = cluster.CreateClient();
            RiakResult    result  = client.Ping();

            if (!result.IsSuccess)
            {
                Assert.IsTrue(result.ErrorMessage.Contains("the connected party did not properly respond after a period of time"), result.ErrorMessage);
            }
        }
Exemple #16
0
        public void ShortConnectTimeoutMayResultInError()
        {
            IRiakEndPoint cluster = RiakCluster.FromConfig("riakShortConnectConfiguration");
            IRiakClient   client  = cluster.CreateClient();
            RiakResult    result  = client.Ping();

            if (!result.IsSuccess)
            {
                Assert.IsTrue(result.ErrorMessage.Contains("Connection to remote server timed out"), result.ErrorMessage);
            }
        }
Exemple #17
0
        static void Main(string[] args)
        {
            Console.WriteLine("Creating Data");
            Customer            customer     = CreateCustomer();
            IEnumerable <Order> orders       = CreateOrders(customer);
            OrderSummary        orderSummary = CreateOrderSummary(customer, orders);


            Console.WriteLine("Starting Client");
            using (IRiakEndPoint endpoint = RiakCluster.FromConfig("riakConfig"))
            {
                IRiakClient client = endpoint.CreateClient();

                Console.WriteLine("Storing Data");

                client.Put(ToRiakObject(customer));

                foreach (Order order in orders)
                {
                    // NB: this adds secondary index data as well
                    client.Put(ToRiakObject(order));
                }

                client.Put(ToRiakObject(orderSummary));

                Console.WriteLine("Fetching related data by shared key");
                string key = "1";

                var result = client.Get(customersBucketName, key);
                CheckResult(result);
                Console.WriteLine("Customer     1: {0}\n", GetValueAsString(result));

                result = client.Get(orderSummariesBucketName, key);
                CheckResult(result);
                Console.WriteLine("OrderSummary 1: {0}\n", GetValueAsString(result));

                Console.WriteLine("Index Queries");

                // Query for order keys where the SalesPersonId index is set to 9000
                var riakIndexId = new RiakIndexId(ordersBucketName, ordersSalesPersonIdIndexName);
                RiakResult <RiakIndexResult> indexRiakResult = client.GetSecondaryIndex(riakIndexId, 9000); // NB: *must* use 9000 as integer here.
                CheckResult(indexRiakResult);
                RiakIndexResult indexResult = indexRiakResult.Value;
                Console.WriteLine("Jane's orders (key values): {0}", string.Join(", ", indexResult.IndexKeyTerms.Select(ikt => ikt.Key)));

                // Query for orders where the OrderDate index is between 2013-10-01 and 2013-10-31
                riakIndexId     = new RiakIndexId(ordersBucketName, ordersOrderDateIndexName);
                indexRiakResult = client.GetSecondaryIndex(riakIndexId, "2013-10-01", "2013-10-31"); // NB: *must* use strings here.
                CheckResult(indexRiakResult);
                indexResult = indexRiakResult.Value;
                Console.WriteLine("October orders (key values): {0}", string.Join(", ", indexResult.IndexKeyTerms.Select(ikt => ikt.Key)));
            }
        }
        protected void SetUp()
        {
            ConnMock = new Mock<IRiakConnection>();
            ClusterConfigMock = new Mock<IRiakClusterConfiguration>();
            ConnFactoryMock = new Mock<IRiakConnectionFactory>();
            NodeConfigMock = new Mock<IRiakNodeConfiguration>();

            ConnFactoryMock.Setup(m => m.CreateConnection(It.IsAny<IRiakNodeConfiguration>())).Returns(ConnMock.Object);
            NodeConfigMock.SetupGet(m => m.PoolSize).Returns(1);
            ClusterConfigMock.SetupGet(m => m.RiakNodes).Returns(new List<IRiakNodeConfiguration>
                                                                     {NodeConfigMock.Object});

            Cluster = new RiakCluster(ClusterConfigMock.Object, ConnFactoryMock.Object);
            Client = Cluster.CreateClient();
        }
Exemple #19
0
        private async Task InsertMessagesIntoDatabase(string table, List <Message> allMessages)
        {
            IRiakEndPoint cluster = RiakCluster.FromConfig("riakConfig");
            IRiakClient   client  = cluster.CreateClient();

            while (allMessages.Count() > 0)
            {
                List <Message> messages = allMessages.Take(80).ToList();
                allMessages.RemoveRange(0, messages.Count());

                var rows = new List <Row>();

                foreach (Message message in messages)
                {
                    var cells = new Cell[]
                    {
                        new Cell("LT"),
                        new Cell(message.SerialNo),
                        new Cell(message.DeviceName),
                        new Cell(message.Timestamp),
                        new Cell(message.Value)
                    };
                    rows.Add(new Row(cells));
                }

                var columns = new Column[]
                {
                    new Column("Country", ColumnType.Varchar),
                    new Column("SerialNo", ColumnType.Varchar),
                    new Column("DeviceName", ColumnType.Varchar),
                    new Column("Time", ColumnType.Timestamp),
                    new Column("Value", ColumnType.Double)
                };

                var cmd = new Store.Builder()
                          .WithTable(table)
                          .WithColumns(columns)
                          .WithRows(rows)
                          .Build();

                RiakResult rslt = client.Execute(cmd);

                if (!rslt.IsSuccess)
                {
                    throw new Exception("Connection to Riak was not successful. AllMessages: " + allMessages.Count());
                }
            }
        }
        public TestBase()
        {
#if NOAUTH
            cluster = RiakCluster.FromConfig("riak1NodeNoAuthConfiguration");
#else
            if (MonoUtil.IsRunningOnMono)
            {
                cluster = RiakCluster.FromConfig("riak1NodeNoAuthConfiguration");
            }
            else
            {
                cluster = RiakCluster.FromConfig("riak1NodeConfiguration");
            }
#endif
            client = cluster.CreateClient();
        }
Exemple #21
0
        public TimeSeries(IRiakClient client, IFuture future)
        {
            _client = client;

            if (!_first)
            {
                return;
            }

            _first = false;

            //future.FireRepeatedly(TimeSpan.FromMinutes(5), dispatcher, (state) =>
            //{
            //    (state as IDispatcher).Dispatch<ReduceMetrics>(x => { });
            //}, Description: "Runs metric reducing to reduce space used by older metrics");
        }
        public TestBase(bool auth = true)
        {
#if NOAUTH
            cluster = RiakCluster.FromConfig("riak1NodeNoAuthConfiguration");
#else
            if (auth == false || MonoUtil.IsRunningOnMono)
            {
                cluster = RiakCluster.FromConfig("riak1NodeNoAuthConfiguration");
            }
            else
            {
                cluster = RiakCluster.FromConfig("riak1NodeConfiguration");
            }
#endif
            client = cluster.CreateClient();
        }
        protected void SetUpInternal()
        {
            ConnMock          = new Mock <IRiakConnection>();
            ClusterConfigMock = new Mock <IRiakClusterConfiguration>();
            NodeConfigMock    = new Mock <IRiakNodeConfiguration>();

            ConnMock.Setup(m => m.PbcWriteRead <TRequest, TResult>(It.IsAny <IRiakEndPoint>(), It.IsAny <TRequest>()).ConfigureAwait(false).GetAwaiter().GetResult()).Returns(() => Result);
            NodeConfigMock.SetupGet(m => m.PoolSize).Returns(1);
            NodeConfigMock.SetupGet(m => m.BufferSize).Returns(2097152);
            ClusterConfigMock.SetupGet(m => m.RiakNodes).Returns(new List <IRiakNodeConfiguration> {
                NodeConfigMock.Object
            });
            ClusterConfigMock.SetupGet(m => m.DefaultRetryCount).Returns(100);
            ClusterConfigMock.SetupGet(m => m.DefaultRetryWaitTime).Returns(100);

            Cluster = new RiakCluster(ClusterConfigMock.Object);
            Client  = Cluster.CreateClient();
        }
Exemple #24
0
        protected void SetUpInternal()
        {
            ConnMock          = new Mock <IRiakConnection>();
            ClusterConfigMock = new Mock <IRiakClusterConfiguration>();
            ConnFactoryMock   = new Mock <IRiakConnectionFactory>();
            NodeConfigMock    = new Mock <IRiakNodeConfiguration>();

            ConnMock.Setup(m => m.PbcWriteRead <TRequest, TResult>(It.IsAny <TRequest>())).Returns(() => Result);
            ConnFactoryMock.Setup(m => m.CreateConnection(It.IsAny <IRiakNodeConfiguration>())).Returns(ConnMock.Object);
            NodeConfigMock.SetupGet(m => m.PoolSize).Returns(1);
            ClusterConfigMock.SetupGet(m => m.RiakNodes).Returns(new List <IRiakNodeConfiguration> {
                NodeConfigMock.Object
            });
            ClusterConfigMock.SetupGet(m => m.DefaultRetryCount).Returns(100);
            ClusterConfigMock.SetupGet(m => m.DefaultRetryWaitTime).Returns(100);

            Cluster = new RiakCluster(ClusterConfigMock.Object, ConnFactoryMock.Object);
            Client  = Cluster.CreateClient();
        }
Exemple #25
0
        private void InsertMessageIntoDatabase(string table, Message message)
        {
            IRiakEndPoint cluster = RiakCluster.FromConfig("riakConfig");
            IRiakClient   client  = cluster.CreateClient();

            var cells = new Cell[]
            {
                new Cell("LT"),
                new Cell(message.SerialNo),
                new Cell(message.DeviceName),
                new Cell(message.Timestamp),
                new Cell(message.Value)
            };

            var rows = new Row[]
            {
                new Row(cells)
            };

            var columns = new Column[]
            {
                new Column("Country", ColumnType.Varchar),
                new Column("SerialNo", ColumnType.Varchar),
                new Column("DeviceName", ColumnType.Varchar),
                new Column("Time", ColumnType.Timestamp),
                new Column("Value", ColumnType.Double)
            };

            var cmd = new Store.Builder()
                      .WithTable(table)
                      .WithColumns(columns)
                      .WithRows(rows)
                      .Build();

            RiakResult rslt = client.Execute(cmd);

            if (!rslt.IsSuccess)
            {
                throw new Exception("Connection to Riak was not successful.");
            }
        }
        public MainForm()
        {
            InitializeComponent();

            _cluster = RiakCluster.FromConfig("riakConfig");
            _client = _cluster.CreateClient();

            _worker = new BackgroundWorker
            {
                WorkerReportsProgress = true,
                WorkerSupportsCancellation = false
            };

            _worker.DoWork += AsyncLoadImages;

            _resizeSettings = new ResizeSettings
            {
                MaxWidth = 120,
                MaxHeight = 100,
                Format = "jpg"
            };
        }
Exemple #27
0
        public TestBase(bool useTtb = false, bool auth = true)
        {
            var config = RiakClusterConfiguration.LoadFromConfig("riakConfiguration");
            var noAuthConfig = RiakClusterConfiguration.LoadFromConfig("riakNoAuthConfiguration");
            if (useTtb)
            {
                config.UseTtbEncoding = true;
                noAuthConfig.UseTtbEncoding = true;
            }
#if NOAUTH
            cluster = new RiakCluster(noAuthConfig);
#else
            if (auth == false || MonoUtil.IsRunningOnMono)
            {
                cluster = new RiakCluster(noAuthConfig);
            }
            else
            {
                cluster = new RiakCluster(config);
            }

#endif
            client = cluster.CreateClient();
        }
Exemple #28
0
        public TestBase(bool useTtb = false, bool auth = true)
        {
            var config       = RiakClusterConfiguration.LoadFromConfig("riakConfiguration");
            var noAuthConfig = RiakClusterConfiguration.LoadFromConfig("riakNoAuthConfiguration");

            if (useTtb)
            {
                config.UseTtbEncoding       = true;
                noAuthConfig.UseTtbEncoding = true;
            }
#if NOAUTH
            cluster = new RiakCluster(noAuthConfig);
#else
            if (auth == false || MonoUtil.IsRunningOnMono)
            {
                cluster = new RiakCluster(noAuthConfig);
            }
            else
            {
                cluster = new RiakCluster(config);
            }
#endif
            client = cluster.CreateClient();
        }
 public void CreateClient()
 {
     client = endpoint.CreateClient();
 }
        private static void SetUpRiakClient()
        {
            var factory = new CorrugatedIron.Comms.RiakConnectionFactory();
              var clusterconfig = new CorrugatedIron.Config.Fluent.RiakClusterConfiguration()
            .SetNodePollTime(5000)
            .SetDefaultRetryWaitTime(200)
            .SetDefaultRetryCount(3)
            .AddNode(a => a
              .SetHostAddress("169.254.11.11")
              .SetPbcPort(8087)
              .SetRestPort(8098)
              .SetPoolSize(20)
              .SetName("Riak")
             );
              var cluster = new RiakCluster(clusterconfig, factory);
              riakClient = cluster.CreateClient();

              Log("Initialized Riak client");
              ConfigureBucketAllowMult(true);
        }
Exemple #31
0
 public UserRepository(IRiakClient client)
     : base(client)
 {
 }
Exemple #32
0
 public MyContext(IRiakClient client) : base(client)
 {
 }
 public RiakAsyncClient(IRiakClient client)
 {
     _client = client;
 }
 public EntityManager(IRiakClient client)
 {
     this.client = client;
 }
 public RiakCompetes(IRiakClient riak)
 {
     _riak = riak;
 }
 public DinnerRepository()
 {
     _cluster = new RiakCluster(_clusterConfig, new RiakConnectionFactory());
     _client = _cluster.CreateClient();
 }
Exemple #37
0
 public RiakAsyncClient(IRiakClient client)
 {
     _client = client;
 }
Exemple #38
0
 public S(IRiakClient client, Store command) : base(client, command)
 {
     _command = command;
 }
Exemple #39
0
 public Database(IRiakClient client)
 {
     Client = client;
 }
Exemple #40
0
 public Q(IRiakClient client, Query command) : base(client, command)
 {
     _command = command;
 }
Exemple #41
0
 public TimelineRepository(IRiakClient client)
     : base(client)
 {
 }
Exemple #42
0
 public void SetUp()
 {
     Client = Cluster.CreateClient();
 }
Exemple #43
0
 public override void SetUp()
 {
     base.SetUp();
     cluster = RiakCluster.FromConfig("riakConfig");
     client = cluster.CreateClient();
     fixture.Inject(client);
     userDocumentMapper = fixture.Freeze<IMapper<User, UserDocument>>();
     userMapper = fixture.Freeze<IMapper<UserDocument, User>>();
     sut = fixture.Create<UserRepository>();
 }
 public virtual void SetUp()
 {
     Client = Cluster.CreateClient();
 }
 public RiakCheckpoints(IRiakClient riak)
 {
     _riak = riak;
 }
Exemple #46
0
 public MsgRepository(IRiakClient client)
     : base(client)
 {
 }
Exemple #47
0
 public E(IRiakClient client, IRiakCommand command)
 {
     _client  = client;
     _command = command;
 }
        private static void Run(IRiakClient client)
        {
            // is the server alive?
            Console.WriteLine("Pinging the server ...");
            var pingResult = client.Ping();
            System.Diagnostics.Debug.Assert(pingResult.IsSuccess);

            // here's how you'd go about setting the properties on a bucket
            // (there are lots more than demoed here).
            Console.WriteLine("Setting some bucket properties via REST ...");
            var restProps = new RiakBucketProperties()
                .SetAllowMultiple(true)
                .SetWVal(3);
            client.SetBucketProperties(Bucket, restProps);
            // you'll notice that this is slow, because behind the scenes the client
            // has detected properties that can't be set via the PBC interface
            // so instead it has degraded to the REST api.

            // here's a sample which uses just the PBC properties and hence runs a
            // lot faster.
            Console.WriteLine("Setting some bucket properties via PBC ...");
            var pbcProps = new RiakBucketProperties()
                .SetAllowMultiple(false);
            client.SetBucketProperties(Bucket, pbcProps);

            // we'll keep track of the keys we store as we create them
            var keys = new List<string>();

            // let's write some stuff to Riak, starting with a simple put
            Console.WriteLine("Simple Put ...");
            var simplePutData = CreateData(0);
            var simplePutResponse = client.Put(simplePutData);
            System.Diagnostics.Debug.Assert(simplePutResponse.IsSuccess);
            keys.Add(simplePutData.Key);

            // next write and pull out the resulting object at the same time,
            // and specifying a different write quorum
            var putWithBody = CreateData(1);
            Console.WriteLine("Simple Put with custom quorum ...");
            var putWithBodyResponse = client.Put(putWithBody, new RiakPutOptions { ReturnBody = true, W = 1 });
            System.Diagnostics.Debug.Assert(putWithBodyResponse.IsSuccess);
            System.Diagnostics.Debug.Assert(putWithBodyResponse.Value != null);
            System.Diagnostics.Debug.Assert(putWithBodyResponse.Value.VectorClock != null);
            keys.Add(putWithBody.Key);

            // let's bang out a few more objects to do a bulk load
            var objects = new List<RiakObject>();
            for (var i = 1; i < 11; ++i)
            {
                var obj = CreateData(i);
                objects.Add(obj);
                keys.Add(obj.Key);
            }
            Console.WriteLine("Bulk insert ...");
            var bulkInsertResults = client.Put(objects);
            // verify that they all went in
            foreach (var r in bulkInsertResults)
            {
                System.Diagnostics.Debug.Assert(r.IsSuccess);
            }

            // let's see if we can get out all the objects that we expect to retrieve
            // starting with a simple get:
            Console.WriteLine("Simple Get ...");
            var simpleGetResult = client.Get(Bucket, keys[0]);
            System.Diagnostics.Debug.Assert(simpleGetResult.IsSuccess);
            System.Diagnostics.Debug.Assert(simpleGetResult.Value != null);

            // let's do a bulk get of all the objects we've written so far, again
            // mucking with the quorum value
            var objectIds = keys.Select(k => new RiakObjectId(Bucket, k));
            Console.WriteLine("Bulk Get ...");
            var bulkGetResults = client.Get(objectIds, 1);

            // verify that we got everything
            foreach (var r in bulkGetResults)
            {
                System.Diagnostics.Debug.Assert(r.IsSuccess);
                System.Diagnostics.Debug.Assert(r.Value != null);
            }

            // let's try a map/reduce function, with javascript, to count the
            // number of objects in the bucket
            var sumMapRed = new RiakMapReduceQuery()
                .Inputs(Bucket)
                .MapJs(m => m.Source(@"function(o) {return [ 1 ];}"))
                .ReduceJs(r => r.Name(@"Riak.reduceSum").Keep(true));

            // execute this query with blocking IO, waiting for all the results to come
            // back before we process them
            Console.WriteLine("Blocking map/reduce query ...");
            var blockingMRResult = client.MapReduce(sumMapRed);
            System.Diagnostics.Debug.Assert(blockingMRResult.IsSuccess);
            // next, pull out the phase we're interested in to get the result we want
            var reducePhaseResult = blockingMRResult.Value.PhaseResults.Last().GetObjects<int[]>().SelectMany(p => p).ToArray();
            System.Diagnostics.Debug.Assert(reducePhaseResult[0] == 12);

            // now let's do the same thing, but with the blocking version that streams
            // the results back per phase, rather than waiting for all the reults to
            // be calculated first
            Console.WriteLine("Blocking streaming map/reduce query ...");
            var streamingMRResult = client.StreamMapReduce(sumMapRed);
            System.Diagnostics.Debug.Assert(streamingMRResult.IsSuccess);
            foreach (var result in streamingMRResult.Value.PhaseResults)
            {
                if (result.Phase == 1)
                {
                    var json = JArray.Parse(result.Values[0].FromRiakString());
                    System.Diagnostics.Debug.Assert(json[0].Value<int>() == 12);
                }
            }

            // each of the above methods have an async equivalent that has an extra
            // parameter to pass in which is an Action that takes the result. This
            // is executed on the worker thread that the work is done on. For the
            // sake of this example, we'll only demonstrate how to do this with
            // streaming map/reduce as applying the principle to the other functions
            // is a simple thing to do. All the async methods are exposed via the
            // 'Async' property.

            // create an event to wait on while the results are being processed
            // (usually you wouldn't worry about this in a Ui app, you'd just take
            // the result of the other thread and dispatch it to the UI when processed)
            var autoResetEvent = new AutoResetEvent(false);
            Console.WriteLine("Starting async streaming map/reduce query ...");
            client.Async.StreamMapReduce(sumMapRed, result => HandleStreamingMapReduce(result, autoResetEvent));
            Console.WriteLine("Waiting for async streaming map/reduce query result ...");
            autoResetEvent.WaitOne();

            // finally delete the bucket (this can also be done asynchronously)
            // this calls ListKeys behind the scenes, so it's a very slow process. Riak
            // doesn't currently have the ability to quickly delete a bucket.
            Console.WriteLine("Deleting the whole test bucket ...");
            client.DeleteBucket(Bucket);

            Console.WriteLine("Sample app complete!");
        }