public bool CheckOrSave(string endpoint, Int32 bucket, long position) { var id = new RiakObjectId($"{Settings.Bucket}.system", $"{endpoint}:{bucket}"); var options = new RiakGetOptions { }; options.SetRw(Quorum.WellKnown.All); var exists = _riak.Get(id, options); if (exists.IsSuccess) { return(false); } var competer = new Competer { Id = $"{endpoint}:{bucket}", Discriminator = Discriminator, Endpoint = endpoint, Bucket = bucket, Position = position, Heartbeat = DateTime.UtcNow }; var putOpt = new RiakPutOptions { IfNotModified = false, IfNoneMatch = true }; putOpt.SetW(Quorum.WellKnown.All); var o = new RiakObject(id, competer); var result = _riak.Put(o, putOpt); if (!result.IsSuccess) { Logger.Info("Endpoint {0} failed to claim bucket {1}. Error: {2}", endpoint, bucket, result.ErrorMessage); return(false); } Thread.Sleep(new Random().Next(100, 2000)); do { exists = _riak.Get(id, options); } while (!exists.IsSuccess); competer = exists.Value.GetObject <Competer>(); if (competer.Discriminator != Discriminator) { Logger.Info("Endpoint {0} failed to claim bucket {1}. Error: {2}", endpoint, bucket, "Discriminator mismatch"); return(false); } Logger.Info("Endpoint {0} successfully claimed bucket {1}", endpoint, bucket); return(true); }
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))); } }
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 virtual string Save(TModel model) { var riakObjectId = new RiakObjectId(BucketName, model.ID); RiakResult <RiakObject> result = client.Get(riakObjectId); CheckResult(result, true); RiakObject objToUpdate = null; if (result.Value != null) { objToUpdate = result.Value; if (objToUpdate.Siblings.Count > 0) { // Provide a better sibling resolution strategy here in production objToUpdate = objToUpdate.Siblings[0]; } objToUpdate.SetObject <TModel>(model); } else { objToUpdate = new RiakObject(riakObjectId, model); } result = client.Put(objToUpdate); CheckResult(result); RiakObject value = result.Value; return(value.Key); }
public virtual string Save(TModel model) { var riakObjectId = new RiakObjectId(BucketType, Bucket, model.ID); var riakObject = new RiakObject(riakObjectId, model); RiakResult <RiakObject> result = client.Put(riakObject); CheckResult(result); RiakObject value = result.Value; return(value.Key); }
private void button1_Click(object sender, EventArgs e) { //Cargar Datos Console.WriteLine("Loading Data FormaPago"); List <FormaPagoVM> formaPagoVMs = db.FormaPago.Select(b => new FormaPagoVM { Forma = b.Forma, comision = b.comision }).ToList(); Console.WriteLine("Loading Data Precio"); List <PrecioVM> precioVMs = db.Precio.Select(a => new PrecioVM { Tipo = a.Tipo, precio = a.precio1 }).ToList(); Console.WriteLine("Loading Data Cliente"); List <ClienteVM> clienteVMs = db.Cliente.Select(a => new ClienteVM { DNI = a.DNI, Nombre = a.Nombre, Apellidos = a.Apellidos, Domicilio = a.Domicilio, Telefono = a.Telefono }).ToList(); Console.WriteLine("Loading Data Habitacion"); List <HabitacionVM> habitacionVMs = db.Habitacion.Select(b => new HabitacionVM { Numero = b.Numero, bar = b.bar, puedesupletoria = b.puedesupletoria, superficie = b.superficie, terraza = b.terraza, Tipo = new PrecioVM { Tipo = b.Precio.Tipo, precio = b.Precio.precio1 } }).ToList(); Console.WriteLine("Loading Data Factura"); List <FacturaVM> facturaVMs = db.Factura.Select(a => new FacturaVM { CodigoF = a.CodigoF, Entrada = a.Entrada == null ? DateTime.MinValue : (DateTime)a.Entrada, Salida = a.Salida == null ? DateTime.MinValue : (DateTime)a.Salida, Cliente = new ClienteVM { DNI = a.Cliente.DNI, Nombre = a.Cliente.Nombre, Apellidos = a.Cliente.Apellidos, Domicilio = a.Cliente.Domicilio, Telefono = a.Cliente.Telefono }, Numero = new HabitacionVM { Numero = a.Habitacion.Numero, superficie = a.Habitacion.superficie, bar = a.Habitacion.bar, puedesupletoria = a.Habitacion.puedesupletoria, terraza = a.Habitacion.terraza, Tipo = new PrecioVM { Tipo = a.Habitacion.Precio.Tipo, precio = a.Habitacion.Precio.precio1 } }, Forma = new FormaPagoVM { Forma = a.FormaPago.Forma, comision = a.FormaPago.comision } }).ToList(); Console.WriteLine("Loading Data Empleado"); List <EmpleadoVM> empleadoVMs = new List <EmpleadoVM>(); foreach (Empleado a in db.Empleado) { EmpleadoVM empleadoVM = new EmpleadoVM(); empleadoVM.NumReg = a.NumReg; empleadoVM.Nombre = a.Nombre; empleadoVM.Incorporacion = a.Incorporacion == null ? DateTime.MinValue : (DateTime)a.Incorporacion; empleadoVM.Sueldo = a.Sueldo == null ? 0 : (int)a.Sueldo; if (a.Servicio != null) { ServicioVM servicioVM = new ServicioVM(); servicioVM.CodS = a.Servicio.CodS; servicioVM.Descripcion = a.Servicio.Descripcion.Trim(); servicioVM.costeinterno = a.Servicio.costeinterno == null ? 0 : (int)a.Servicio.costeinterno; if (a.Servicio.Empleado1 != null) { EmpleadoVM empleadoVM1 = new EmpleadoVM(); empleadoVM1.NumReg = a.Servicio.Empleado1.NumReg; empleadoVM1.Nombre = a.Servicio.Empleado1.Nombre; empleadoVM1.Incorporacion = a.Servicio.Empleado1.Incorporacion == null ? DateTime.MinValue : (DateTime)a.Servicio.Empleado1.Incorporacion; empleadoVM1.Sueldo = a.Servicio.Empleado1.Sueldo == null ? 0 : (int)a.Servicio.Empleado1.Sueldo; servicioVM.NumReg = empleadoVM1; } empleadoVM.Servicio = servicioVM; } empleadoVMs.Add(empleadoVM); } foreach (FormaPagoVM itemFormaPagoVM in formaPagoVMs) { client.Put(ToRiakObject(itemFormaPagoVM)); } foreach (PrecioVM itemPrecioVM in precioVMs) { client.Put(ToRiakObject(itemPrecioVM)); } foreach (ClienteVM itemClienteVM in clienteVMs) { client.Put(ToRiakObject(itemClienteVM)); } foreach (FacturaVM itemFacturaVM in facturaVMs) { client.Put(ToRiakObject(itemFacturaVM)); } foreach (HabitacionVM itemHabitacionVM in habitacionVMs) { client.Put(ToRiakObject(itemHabitacionVM)); } foreach (EmpleadoVM itemEmpleadoVM in empleadoVMs) { client.Put(ToRiakObject(itemEmpleadoVM)); } }
public Task <IEnumerable <RiakResult <RiakObject> > > Put(IEnumerable <RiakObject> values, RiakPutOptions options) { return(Task.Factory.StartNew(() => _client.Put(values, options))); }
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!"); }
public void Put(IEnumerable <RiakObject> values, Action <IEnumerable <RiakResult <RiakObject> > > callback, RiakPutOptions options) { ExecAsync(() => callback(_client.Put(values, options))); }
static void Main(string[] args) { const string bucket = "test"; try { using (IRiakEndPoint endpoint = RiakCluster.FromConfig("riakConfig")) { IRiakClient client = endpoint.CreateClient(); // Creating Objects In Riak Console.WriteLine("Creating Objects In Riak..."); int val1 = 1; var objectId1 = new RiakObjectId(bucket, "one"); var riakObject1 = new RiakObject(objectId1, val1); var result = client.Put(riakObject1); CheckResult(result); string val2 = "two"; var objectId2 = new RiakObjectId(bucket, "two"); var riakObject2 = new RiakObject(objectId2, val2); result = client.Put(riakObject2); CheckResult(result); var val3 = new Dictionary <string, int> { { "myValue1", 3 }, { "myValue2", 4 } }; var objectId3 = new RiakObjectId(bucket, "three"); var riakObject3 = new RiakObject(objectId3, val3); result = client.Put(riakObject3); CheckResult(result); // Fetching Objects From Riak Console.WriteLine("Reading Objects From Riak..."); var fetchResult1 = client.Get(objectId1); CheckResult(fetchResult1); RiakObject fetchObject1 = fetchResult1.Value; int fetchVal1 = fetchObject1.GetObject <int>(); Debug.Assert(val1 == fetchVal1, "Assert Failed", "val1 {0} != fetchVal1 {1}", val1, fetchVal1); var fetchResult2 = client.Get(objectId2); CheckResult(fetchResult2); RiakObject fetchObject2 = fetchResult2.Value; string fetchVal2 = fetchObject2.GetObject <string>(); Debug.Assert(val2 == fetchVal2, "Assert Failed", "val2 {0} != fetchVal2 {1}", val2, fetchVal2); var fetchResult3 = client.Get(objectId3); CheckResult(fetchResult3); RiakObject fetchObject3 = fetchResult3.Value; var fetchVal3 = fetchObject3.GetObject <Dictionary <string, int> >(); Debug.Assert(dictEqualityComparer.Equals(val3, fetchVal3), "Assert Failed", "val3 {0} != fetchVal3 {1}", val3, fetchVal3); // Updating Objects In Riak Console.WriteLine("Updating Objects In Riak"); fetchVal3["myValue1"] = 42; var updateObject1 = new RiakObject(bucket, "three", fetchVal3); var updateResult1 = client.Put(updateObject1); CheckResult(updateResult1); var fetchResult4 = client.Get(objectId3); CheckResult(fetchResult4); RiakObject fetchObject4 = fetchResult4.Value; var fetchVal4 = fetchObject4.GetObject <Dictionary <string, int> >(); Debug.Assert(false == dictEqualityComparer.Equals(val3, fetchVal4), "Assert Failed", "val3 {0} == fetchVal4 {1}", val3, fetchVal4); Debug.Assert(fetchVal4["myValue1"] == 42, "Assert Failed", "myValue1 should have been 42"); // Deleting Objects From Riak Console.WriteLine("Deleting Objects From Riak..."); RiakResult delResult1 = client.Delete(objectId1); CheckResult(delResult1); RiakResult delResult2 = client.Delete(objectId2); CheckResult(delResult2); RiakResult delResult3 = client.Delete(objectId3); CheckResult(delResult3); // Working With Complex Objects Console.WriteLine("Working With Complex Objects..."); var book = new Book(); book.ISBN = "1111979723"; book.Title = "Moby Dick"; book.Author = "Herman Melville"; book.Body = "Call me Ishmael. Some years ago..."; book.CopiesOwned = 3; var bookId = new RiakObjectId("books", book.ISBN); var bookObject = new RiakObject(bookId, book); var bookPutResult = client.Put(bookObject); CheckResult(bookPutResult); var fetchBookResult = client.Get(bookId); CheckResult(fetchBookResult); RiakObject fetchedBookObject = fetchBookResult.Value; string bookJson = Encoding.UTF8.GetString(fetchedBookObject.Value); Console.WriteLine("Serialized Object: {0}", bookJson); var bookDeleteResult = client.Delete(bookId); CheckResult(bookDeleteResult); } } catch (Exception e) { Console.Error.WriteLine("Exception: {0}", e.Message); } }