public TypedViewMetaDetailsResponse GetTypedViewMetaDetails(ServiceStack.ServiceInterface.Service service) { // The entity meta details don't change per type, so cache these for performance var cacheKey = string.Format("{0}-typedview-meta-details", TypedViewType.ToString().ToLower()); var metaDetails = CacheClient.Get <TypedViewMetaDetailsResponse>(cacheKey); if (metaDetails != null) { return(metaDetails); } var request = service.RequestContext.Get <IHttpRequest>(); var appUri = request.GetApplicationUrl().TrimEnd('/'); var baseServiceUri = appUri + request.PathInfo.Replace("/meta", ""); var queryString = request.QueryString["format"] != null ? "&format=" + request.QueryString["format"] : ""; var fields = new List <Link>(); foreach (var f in FieldMap) { var link = Link.Create( f.Key.ToCamelCase(), f.Value.DataType.Name, "field", string.Format("{0}?select={1}{2}", baseServiceUri, f.Key.ToLowerInvariant(), queryString), string.Format("The {0} field for the {1} resource.", f.Value.Name, typeof(TDto).Name), new Dictionary <string, string>() ); var props = new SortedDictionary <string, string>(); props.Add("index", f.Value.FieldIndex.ToString(CultureInfo.InvariantCulture)); if (f.Value.IsNullable) { props.Add("isNullable", "true"); } if (f.Value.IsOfEnumDataType) { props.Add("isEnumType", "true"); } if (f.Value.MaxLength > 0) { props.Add("maxLength", f.Value.MaxLength.ToString(CultureInfo.InvariantCulture)); } if (f.Value.Precision > 0) { props.Add("precision", f.Value.Precision.ToString(CultureInfo.InvariantCulture)); } if (f.Value.Scale > 0) { props.Add("scale", f.Value.Scale.ToString(CultureInfo.InvariantCulture)); } link.Properties = new Dictionary <string, string>(props); fields.Add(link); } metaDetails = new TypedViewMetaDetailsResponse() { Name = typeof(TDto).Name, FieldCount = fields.Count, Fields = fields.ToArray() }; CacheClient.Set(cacheKey, metaDetails); return(metaDetails); }
public static void Run() { var cacheClient = new CacheClient(); Console.WriteLine("***** BEGIN CACHE MISS TEST *****"); Console.WriteLine(); cacheClient.HostDisconnected += (sender, e) => { Console.WriteLine("*** Host disconnected"); }; cacheClient.HostReconnected += (sender, e) => { Console.WriteLine("*** Host reconnected"); }; // Try and get 10 items string value = null; for (int i = 0; i < 10; i++) { var cacheKey = "doesNotExist" + i; var result = cacheClient.TryGet(cacheKey, out value); if (!result) { Console.WriteLine("PASS: Did not receive value for cache key: {0}", cacheKey); } else { Console.WriteLine("FAIL: Received value for cache key: {0}", cacheKey); } } // Bulk 10 var bulkResult = cacheClient.Get <string>(new[] { "doesNotExist0", "doesNotExist1", "doesNotExist2", "doesNotExist3", "doesNotExist4", "doesNotExist5", "doesNotExist6", "doesNotExist7", "doesNotExist8", "doesNotExist9" }); if (bulkResult == null) { Console.WriteLine("PASS: Did not receive values for bulk cache keys"); } else { Console.WriteLine("FAIL: Received values for bulk cache keys"); } // Tag var tagResult = cacheClient.GetTagged <string>("tagDoesntExist"); if (tagResult == null) { Console.WriteLine("PASS: Did not receive values for tag cache keys"); } else { Console.WriteLine("FAIL: Received values for tag cache keys"); } var key = Console.ReadKey(); // Graceful shutdown option if (key.KeyChar == 'q') { cacheClient.Shutdown(); } }
public void Run(string[] args) { using (var client = new CacheClient(cacheServiceNode)) { client.Put("message", "hello"); Console.WriteLine(client.Get("message")); } }
public async static Task Run() { // ========================================================= // Iron.io Cache // ========================================================= IronCacheRestClient ironCacheClient = Client.New(); // Get a Cache object CacheClient cache = ironCacheClient.Cache("my_cache"); // Put value to cache by key await cache.Put("number_item", 42); CacheItem item = await cache.Get("number_item"); // Get value from cache by key Console.WriteLine(item.Value); // Get value from cache by key Console.WriteLine(await cache.Get <int>("number_item")); // Numbers can be incremented await cache.Increment("number_item", 10); // Immediately delete an item await cache.Delete("number_item"); await cache.Put("complex_item", new { greeting = "Hello", target = "world" }); CacheItem complexItem = await cache.Get("complex_item"); // Get value from cache by key Console.WriteLine(complexItem.Value); await cache.Delete("complex_item"); await cache.Put("sample_class", new SampleClass { Name = "Sample Class CacheItem" }); SampleClass sampleClassItem = await cache.Get <SampleClass>("sample_class"); Console.WriteLine(sampleClassItem.Inspect()); await cache.Delete("sample_class"); }
public static void Run() { var cacheClient = new CacheClient(); Console.WriteLine("***** BEGIN CACHE MISS TEST *****"); Console.WriteLine(); cacheClient.HostDisconnected += (sender, e) => { Console.WriteLine("*** Host disconnected"); }; cacheClient.HostReconnected += (sender, e) => { Console.WriteLine("*** Host reconnected"); }; // Try and get 10 items string value = null; for (int i = 0; i < 10; i++) { var cacheKey = "doesNotExist" + i; var result = cacheClient.TryGet(cacheKey, out value); if (!result) { Console.WriteLine("PASS: Did not receive value for cache key: {0}", cacheKey); } else { Console.WriteLine("FAIL: Received value for cache key: {0}", cacheKey); } } // Bulk 10 var bulkResult = cacheClient.Get<string>(new[] { "doesNotExist0", "doesNotExist1", "doesNotExist2", "doesNotExist3", "doesNotExist4", "doesNotExist5", "doesNotExist6", "doesNotExist7", "doesNotExist8", "doesNotExist9" }); if (bulkResult == null) { Console.WriteLine("PASS: Did not receive values for bulk cache keys"); } else { Console.WriteLine("FAIL: Received values for bulk cache keys"); } // Tag var tagResult = cacheClient.GetTagged<string>("tagDoesntExist"); if (tagResult == null) { Console.WriteLine("PASS: Did not receive values for tag cache keys"); } else { Console.WriteLine("FAIL: Received values for tag cache keys"); } var key = Console.ReadKey(); // Graceful shutdown option if (key.KeyChar == 'q') { cacheClient.Shutdown(); } }
static void Test1() { var client = new CacheClient(); client.SetServer("tcp://127.0.0.1:1234"); //client.Bench(); client.Set("aa", 1234); client.Set("bb", false); client.Set("cc", 3.14); client.Set("dd", "NewLife", 5); client.Set("ee", new { Name = "新生命", Year = 2002 }); Console.WriteLine(client.Get <Int32>("aa")); Console.WriteLine(client.Get <Boolean>("bb")); Console.WriteLine(client.Get <Double>("cc")); Console.WriteLine(client.Get <String>("dd")); Console.WriteLine(client.Get <Object>("ee").ToJson()); Console.WriteLine(); Console.WriteLine("Count={0}", client.Count); Console.WriteLine("Keys={0}", client.Keys.Join()); Thread.Sleep(2000); Console.WriteLine("Expire={0}", client.GetExpire("dd")); Console.WriteLine(); client.Decrement("aa", 30); client.Increment("cc", 0.3); Console.WriteLine(); var dic = client.GetAll <Object>(new[] { "aa", "cc", "ee" }); foreach (var item in dic) { var val = item.Value; if (val != null && item.Value.GetType().GetTypeCode() == TypeCode.Object) { val = val.ToJson(); } Console.WriteLine("{0}={1}", item.Key, val); } }
public bool ValidUpdater(UpdateFulfillment instance, string fulfiller) { var key = SessionFeature.GetSessionKey(); var currentUser = CacheClient.Get <AuthUserSession>(key); if (instance.Status == "Completed" && fulfiller != currentUser.UserName) { return(false); } return(true); }
public object Get(string key) { using (var client = new CacheClient(cacheServiceNode)) { var value = client.Get(key); if (value == null) { return(new Http404NotFound()); } return(new JSONResult(value, null)); } }
public void Get() { // Arrange var datakey = new DataKey <int>("Key1"); m_mockProtocol.Setup(protocol => protocol.Get(GetOperation.Get, datakey)).Returns(true); // Act m_client.Get(datakey); // Assert }
public Session this[Guid sessionId] { get { Console.WriteLine("UserSession get CacheClient: '{0}'", CacheClient); var authSession = CacheClient.Get <Session>(Session.ToCacheKey(sessionId)); if (authSession != default(Session)) { authSession.SetRedisClient((CacheClient as IRedisClientsManager).GetClient()); } return(authSession); } set { if (sessionId != value.Id) { throw new Exception(string.Format("sessionId {0}!={1} value.Id ", sessionId, value.Id)); } CacheClient.Replace <Session>(Session.ToCacheKey(sessionId), value, value.ExpiresAt); } }
/// <summary> /// 出队 /// </summary> public static void Dequeue <T>(Action <T> action) { //é»˜è®¤ä½¿ç”¨çº¿ç¨‹æ± Task.Run(() => { while (true) { if (cacheClient.GetListLength(key) > 0) { var exception = cacheClient.Get <T>(key); action(exception); } else { Thread.Sleep(2000); } } }); #region çº¿ç¨‹æ± ç‰ˆæœ¬ //ThreadPool.QueueUserWorkItem(o => //{ // while (true) // { // if (cacheClient.GetListLength(key) > 0) // { // var exception = cacheClient.Get<T>(key); // action(exception); // } // else // { // Thread.Sleep(2000); // } // } //}); #endregion }
public List <SubscriptionRelayConfig> GetAll(string eventName) { Guard.AgainstNullOrEmpty(() => eventName, eventName); var cached = CacheClient.Get <CachedSubscription>(FormatCacheKey(eventName)); if (cached != null) { return(cached.Subscribers); } var fetched = SubscriptionService.Search(eventName); if (fetched.Any()) { var expiry = TimeSpan.FromSeconds(ExpiryTimeSeconds); CacheClient.Set(FormatCacheKey(eventName), new CachedSubscription { Subscribers = fetched }, expiry); } return(fetched); }
public virtual T Get <T>(string key) { return(_cache.Get <T>(key)); }
public static void Run() { var cacheClient = new CacheClient(); var stopwatch = new Stopwatch(); var overallStopwatch = new Stopwatch(); overallStopwatch.Start(); // 502 chars = ~1 kb const string value = "asdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasas"; CustomObject myObject = new CustomObject(); Console.WriteLine("***** BEGIN ADD 10000 TESTS *****"); Console.WriteLine(); #region Regular Add 10000 strings stopwatch.Start(); for (int i = 1; i <= 10000; i++) { cacheClient.AddOrUpdate("test" + i, value); } stopwatch.Stop(); Console.WriteLine("Add time taken: " + stopwatch.ElapsedMilliseconds + " ms, " + stopwatch.ElapsedTicks + " ticks"); #endregion #region Bulk Add 10000 strings var list = new List <KeyValuePair <string, object> >(10000); for (int i = 1; i <= 10000; i++) { list.Add(new KeyValuePair <string, object>("bulktest" + i, value)); } stopwatch.Restart(); cacheClient.AddOrUpdate(list); stopwatch.Stop(); Console.WriteLine("Add Many time taken: " + stopwatch.ElapsedMilliseconds + " ms, " + stopwatch.ElapsedTicks + " ticks"); #endregion #region Tagged Add 10000 strings stopwatch.Restart(); for (int i = 1; i <= 10000; i++) { cacheClient.AddOrUpdate("tagtest" + i, value, tagName: "demotag"); } stopwatch.Stop(); Console.WriteLine("Add Tagged time taken: " + stopwatch.ElapsedMilliseconds + " ms, " + stopwatch.ElapsedTicks + " ticks"); #endregion Console.WriteLine(); Console.WriteLine("***** BEGIN SINGLE KEY GET TEST *****"); Console.WriteLine(); #region Regular Get 1 string proof string resultString = null; stopwatch.Restart(); var result = cacheClient.TryGet("test5", out resultString) && string.Equals(resultString, value); stopwatch.Stop(); Console.WriteLine("Get cache key \"test5\": time taken: " + stopwatch.ElapsedMilliseconds + " ms, " + stopwatch.ElapsedTicks + " ticks"); Console.WriteLine("Get cache key \"test5\": successful = " + result); Console.WriteLine("Get cache key \"test5\": result length: " + (resultString == null ? 0 : resultString.Length) + ", original length: " + value.Length); if (resultString != null) { var origHash = value.GetHashCode(); var resultHash = resultString.GetHashCode(); Console.WriteLine("Original String Hash Code: " + origHash + ", Result String Hash Code: " + resultHash); } #endregion Console.WriteLine(); Console.WriteLine("***** BEGIN GET 10000 TESTS *****"); Console.WriteLine(); string otherValue = null; #region Regular Get 10000 strings stopwatch.Restart(); var failedKeyCount = 0; for (int i = 1; i <= 10000; i++) { if (!cacheClient.TryGet("test" + i, out otherValue)) { failedKeyCount++; } } stopwatch.Stop(); Console.WriteLine("Failed Key Count: " + failedKeyCount + (failedKeyCount > 0 ? ", NOTE: network is probably slow" : "")); Console.WriteLine("Get time taken: " + stopwatch.ElapsedMilliseconds + " ms, " + stopwatch.ElapsedTicks + " ticks"); #endregion #region Bulk Get 10000 strings var list2 = new List <string>(10000); for (int i = 1; i <= 10000; i++) { list2.Add("bulktest" + i); } stopwatch.Restart(); var getManyResults = cacheClient.Get <string>(list2); stopwatch.Stop(); Console.WriteLine("Get Many time taken: " + stopwatch.ElapsedMilliseconds + " ms, " + stopwatch.ElapsedTicks + " ticks"); var getManyResultsCount = getManyResults != null ? getManyResults.Count : 0; Console.WriteLine("Get Many object count: " + getManyResultsCount + (getManyResultsCount < 10000 ? ", NOTE: network is probably slow" : "")); #endregion #region Tagged Get 10000 strings stopwatch.Restart(); var getTaggedResults = cacheClient.GetTagged <string>("demotag"); stopwatch.Stop(); Console.WriteLine("Get Tagged time taken: " + stopwatch.ElapsedMilliseconds + " ms, " + stopwatch.ElapsedTicks + " ticks"); getManyResultsCount = getManyResults != null ? getManyResults.Count : 0; Console.WriteLine("Get Tagged object count: " + getManyResultsCount + (getManyResultsCount < 10000 ? ", NOTE: network is probably slow" : "")); #endregion Console.WriteLine(); Console.WriteLine("***** BEGIN REMOVE 10000 TESTS *****"); Console.WriteLine(); #region Regular Remove 10000 strings stopwatch.Restart(); for (int i = 1; i <= 10000; i++) { cacheClient.Remove("test" + i); } stopwatch.Stop(); Console.WriteLine("Remove time taken: " + stopwatch.ElapsedMilliseconds + " ms, " + stopwatch.ElapsedTicks + " ticks"); #endregion #region Bulk Remove 10000 strings stopwatch.Restart(); cacheClient.Remove(list2); stopwatch.Stop(); Console.WriteLine("Remove Many time taken: " + stopwatch.ElapsedMilliseconds + " ms, " + stopwatch.ElapsedTicks + " ticks"); #endregion #region Tagged Remove 10000 strings stopwatch.Restart(); cacheClient.RemoveTagged("demotag"); stopwatch.Stop(); Console.WriteLine("Remove Tagged time taken: " + stopwatch.ElapsedMilliseconds + " ms, " + stopwatch.ElapsedTicks + " ticks"); #endregion Console.WriteLine(); Console.WriteLine("***** BEGIN ABSOLUTE EXPIRATION TEST *****"); Console.WriteLine(); #region Regular Add 10000 strings with absolute expiration var absoluteExpiration = DateTime.Now.AddMinutes(1); stopwatch.Restart(); for (int i = 1; i <= 10000; i++) { cacheClient.AddOrUpdate("testabsolute" + i, value, absoluteExpiration: absoluteExpiration); } stopwatch.Stop(); Console.WriteLine("Add absolute expiration time taken: " + stopwatch.ElapsedMilliseconds + " ms, " + stopwatch.ElapsedTicks + " ticks"); #endregion Console.WriteLine(); Console.WriteLine("***** BEGIN 10000 COMPLEX OBJECT ADD TEST *****"); Console.WriteLine(); #region Regular Add 10000 complex objects with sliding expiration var slidingExpiration = new TimeSpan(0, 2, 0); stopwatch.Restart(); for (int i = 1; i <= 10000; i++) { cacheClient.AddOrUpdate("testabsolutecomplex" + i, myObject, slidingExpiration: slidingExpiration); } stopwatch.Stop(); Console.WriteLine("Add complex object time taken: " + stopwatch.ElapsedMilliseconds + " ms, " + stopwatch.ElapsedTicks + " ticks"); #endregion Console.WriteLine(); Console.WriteLine("***** BEGIN 10000 COMPLEX OBJECT GET TEST *****"); Console.WriteLine(); #region Regular Get 10000 complex objects with sliding expiration stopwatch.Restart(); failedKeyCount = 0; for (int i = 1; i <= 10000; i++) { if (!cacheClient.TryGet("testabsolutecomplex" + i, out myObject)) { failedKeyCount++; } } stopwatch.Stop(); Console.WriteLine("Failed Key Count: " + failedKeyCount + (failedKeyCount > 0 ? ", NOTE: network is probably slow" : "")); Console.WriteLine("Get complex object time taken: " + stopwatch.ElapsedMilliseconds + " ms, " + stopwatch.ElapsedTicks + " ticks"); #endregion overallStopwatch.Stop(); Console.WriteLine(); Console.WriteLine("***** END TESTS *****"); Console.WriteLine(); Console.WriteLine("Total time taken: " + overallStopwatch.ElapsedMilliseconds + " ms, " + overallStopwatch.ElapsedTicks + " ticks"); var key = Console.ReadKey(); // Graceful shutdown option if (key.KeyChar == 'q') { cacheClient.Shutdown(); } }
private static void Main(string[] args) { LogManager.Adapter = new ConsoleOutLoggerFactoryAdapter(); // ========================================================= // Iron.io MQ // ========================================================= //IronMqRestClient ironMq = IronSharp.IronMQ.Client.New(); // For beta testing IronMqRestClient ironMq = IronSharp.IronMQ.Client.New(new IronClientConfig { ProjectId = "53a3b3bd5e8edd1245000005", Token = "O7KrMTwmw997iq0KzL7v", Host = "192.168.1.155", ApiVersion = 3, Port = 8080, Scheme = Uri.UriSchemeHttp }); // Simple actions // Post message to a queue TestPosting(ironMq); // Post message to a queue and reserve it TestReservation(ironMq); // Post message, reserve it and delete TestDeletingReservedMessage(ironMq); // Actions on queue // Update queue info TestUpdatingTheQueue(ironMq); // Clear all messages of queue TestClearingQueue(ironMq); // Delete queue and its messages TestDeletingQueue(ironMq); // Get list of all queus inside project TestGettingListQueue(ironMq); // Actions on messages //TestPosting(ironMq); //TestReservation(ironMq); //TestDeletingReservedMessage(ironMq); // Get message by id without reservation TestGettingMessageById(ironMq); // Get message without reserving it TestPeekingMessage(ironMq); // Delete unreserved message TestDeletingMessage(ironMq); // Touch message to prolongate reservation TestTouching(ironMq); // Touch message to prolongate reservation TestTouchingTwice(ironMq); // Release reserved message TestReleasing(ironMq); // Delete a bunch of messages TestDeletingMessages(ironMq); // Get subscriber's URL TestGettingSubscribersInfo(ironMq); // ========================================================= // Iron.io Worker // ========================================================= Console.WriteLine("Be sure to create a 'Test' worker before running this sample"); Console.WriteLine("Press ANY key to continue"); Console.Read(); IronWorkerRestClient workerClient = IronSharp.IronWorker.Client.New(); string taskId = workerClient.Tasks.Create("Test", new { Key = "Value" }); Console.WriteLine("TaskID: {0}", taskId); TaskInfoCollection taskInfoCollection = workerClient.Tasks.List("Test"); foreach (TaskInfo task in taskInfoCollection.Tasks) { Console.WriteLine(task.Inspect()); } ScheduleOptions options = ScheduleBuilder.Build(). Delay(TimeSpan.FromMinutes(1)). WithFrequency(TimeSpan.FromHours(1)). RunFor(TimeSpan.FromHours(3)). WithPriority(TaskPriority.Default); var payload = new { a = "b", c = new[] { 1, 2, 3 } }; ScheduleIdCollection schedule = workerClient.Schedules.Create("Test", payload, options); Console.WriteLine(schedule.Inspect()); workerClient.Schedules.Cancel(schedule.Schedules.First().Id); // ========================================================= // Iron.io Cache // ========================================================= IronCacheRestClient ironCacheClient = IronSharp.IronCache.Client.New(); // Get a Cache object CacheClient cache = ironCacheClient.Cache("my_cache"); // Put value to cache by key cache.Put("number_item", 42); // Get value from cache by key Console.WriteLine(cache.Get("number_item").Value); // Get value from cache by key Console.WriteLine(cache.Get <int>("number_item")); // Numbers can be incremented cache.Increment("number_item", 10); // Immediately delete an item cache.Delete("number_item"); cache.Put("complex_item", new { greeting = "Hello", target = "world" }); // Get value from cache by key Console.WriteLine(cache.Get("complex_item").Value); cache.Delete("complex_item"); Console.WriteLine("============= Done =============="); Console.Read(); }
private static void Main(string[] args) { LogManager.Adapter = new ConsoleOutLoggerFactoryAdapter(); IronMqRestClient ironMq = IronSharp.IronMQ.Client.New(new IronClientConfig { ProjectId = "5bf768af967e0f000910fed3", Token = "y7TU7c3D3IUXtwrcJJFH", Host = "mq-aws-eu-west-1-1.iron.io", ApiVersion = 3, Scheme = Uri.UriSchemeHttp }); QueueClient queueHabitacion = ironMq.Queue("Habitacion"); var codigoHabitacion = "HBT0000007"; string messageId1 = queueHabitacion.Post(codigoHabitacion); Console.WriteLine("Mensaje enviado: {0}", codigoHabitacion); QueueClient queueHotel = ironMq.Queue("Hotel"); var codigoHotel = "HT00000002"; string messageId2 = queueHotel.Post(codigoHotel); Console.WriteLine("Mensaje enviado: {0}", codigoHabitacion); //QueueMessage messageHabitacion = queueHabitacion.Reserve(); //Console.WriteLine("Respuesta: " + messageHabitacion.Body); //QueueMessage messageHotel = queueHotel.Reserve(); //Console.WriteLine("Respuesta: " + messageHotel.Body); //Console.WriteLine(message.ReservationId); //bool finished = false; //var hotelIds = new List<string>(); //while (!finished) //{ // messageHotel = queueHotel.Reserve(); // if (messageHotel != null) // hotelIds.Add(messageHotel.Body); // else // finished = true; //} LogManager.Adapter = new ConsoleOutLoggerFactoryAdapter(); // ========================================================= // Iron.io MQ // ========================================================= //IronMqRestClient ironMq = IronSharp.IronMQ.Client.New(); // For beta testing //IronMqRestClient ironMq = IronSharp.IronMQ.Client.New(new IronClientConfig { ProjectId = "53a3b3bd5e8edd1245000005", Token = "O7KrMTwmw997iq0KzL7v", Host = "192.168.1.155", ApiVersion = 3, Port = 8080, Scheme = Uri.UriSchemeHttp }); // Simple actions // Post message to a queue TestPosting(ironMq); // Post message to a queue and reserve it TestReservation(ironMq); // Post message, reserve it and delete TestDeletingReservedMessage(ironMq); // Actions on queue // Update queue info TestUpdatingTheQueue(ironMq); // Clear all messages of queue TestClearingQueue(ironMq); // Delete queue and its messages TestDeletingQueue(ironMq); // Get list of all queus inside project TestGettingListQueue(ironMq); // Actions on messages //TestPosting(ironMq); //TestReservation(ironMq); //TestDeletingReservedMessage(ironMq); // Get message by id without reservation TestGettingMessageById(ironMq); // Get message without reserving it TestPeekingMessage(ironMq); // Delete unreserved message TestDeletingMessage(ironMq); // Touch message to prolongate reservation TestTouching(ironMq); // Touch message to prolongate reservation TestTouchingTwice(ironMq); // Release reserved message TestReleasing(ironMq); // Delete a bunch of messages TestDeletingMessages(ironMq); // Get subscriber's URL TestGettingSubscribersInfo(ironMq); // ========================================================= // Iron.io Worker // ========================================================= Console.WriteLine("Be sure to create a 'Test' worker before running this sample"); Console.WriteLine("Press ANY key to continue"); Console.Read(); IronWorkerRestClient workerClient = IronSharp.IronWorker.Client.New(); string taskId = workerClient.Tasks.Create("Test", new { Key = "Value" }); Console.WriteLine("TaskID: {0}", taskId); TaskInfoCollection taskInfoCollection = workerClient.Tasks.List("Test"); foreach (TaskInfo task in taskInfoCollection.Tasks) { Console.WriteLine(task.Inspect()); } ScheduleOptions options = ScheduleBuilder.Build(). Delay(TimeSpan.FromMinutes(1)). WithFrequency(TimeSpan.FromHours(1)). RunFor(TimeSpan.FromHours(3)). WithPriority(TaskPriority.Default); var payload = new { a = "b", c = new[] { 1, 2, 3 } }; ScheduleIdCollection schedule = workerClient.Schedules.Create("Test", payload, options); Console.WriteLine(schedule.Inspect()); workerClient.Schedules.Cancel(schedule.Schedules.First().Id); // ========================================================= // Iron.io Cache // ========================================================= IronCacheRestClient ironCacheClient = IronSharp.IronCache.Client.New(); // Get a Cache object CacheClient cache = ironCacheClient.Cache("my_cache"); // Put value to cache by key cache.Put("number_item", 42); // Get value from cache by key Console.WriteLine(cache.Get("number_item").Value); // Get value from cache by key Console.WriteLine(cache.Get <int>("number_item")); // Numbers can be incremented cache.Increment("number_item", 10); // Immediately delete an item cache.Delete("number_item"); cache.Put("complex_item", new { greeting = "Hello", target = "world" }); // Get value from cache by key Console.WriteLine(cache.Get("complex_item").Value); cache.Delete("complex_item"); Console.WriteLine("============= Done =============="); Console.Read(); }
public static void Run() { var cacheClient = new CacheClient(); var stopwatch = new Stopwatch(); var overallStopwatch = new Stopwatch(); overallStopwatch.Start(); // 502 chars = ~1 kb const string value = "asdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasas"; CustomObject myObject = new CustomObject(); Console.WriteLine("***** BEGIN ADD 10000 TESTS *****"); Console.WriteLine(); #region Regular Add 10000 strings stopwatch.Start(); for (int i = 1; i <= 10000; i++) { cacheClient.AddOrUpdate("test" + i, value); } stopwatch.Stop(); Console.WriteLine("Add time taken: " + stopwatch.ElapsedMilliseconds + " ms, " + stopwatch.ElapsedTicks + " ticks"); #endregion #region Bulk Add 10000 strings var list = new List<KeyValuePair<string, object>>(10000); for (int i = 1; i <= 10000; i++) { list.Add(new KeyValuePair<string, object>("bulktest" + i, value)); } stopwatch.Restart(); cacheClient.AddOrUpdate(list); stopwatch.Stop(); Console.WriteLine("Add Many time taken: " + stopwatch.ElapsedMilliseconds + " ms, " + stopwatch.ElapsedTicks + " ticks"); #endregion #region Tagged Add 10000 strings stopwatch.Restart(); for (int i = 1; i <= 10000; i++) { cacheClient.AddOrUpdate("tagtest" + i, value, tagName: "demotag"); } stopwatch.Stop(); Console.WriteLine("Add Tagged time taken: " + stopwatch.ElapsedMilliseconds + " ms, " + stopwatch.ElapsedTicks + " ticks"); #endregion Console.WriteLine(); Console.WriteLine("***** BEGIN SINGLE KEY GET TEST *****"); Console.WriteLine(); #region Regular Get 1 string proof string resultString = null; stopwatch.Restart(); var result = cacheClient.TryGet("test5", out resultString) && string.Equals(resultString, value); stopwatch.Stop(); Console.WriteLine("Get cache key \"test5\": time taken: " + stopwatch.ElapsedMilliseconds + " ms, " + stopwatch.ElapsedTicks + " ticks"); Console.WriteLine("Get cache key \"test5\": successful = " + result); Console.WriteLine("Get cache key \"test5\": result length: " + (resultString == null ? 0 : resultString.Length) + ", original length: " + value.Length); if (resultString != null) { var origHash = value.GetHashCode(); var resultHash = resultString.GetHashCode(); Console.WriteLine("Original String Hash Code: " + origHash + ", Result String Hash Code: " + resultHash); } #endregion Console.WriteLine(); Console.WriteLine("***** BEGIN GET 10000 TESTS *****"); Console.WriteLine(); string otherValue = null; #region Regular Get 10000 strings stopwatch.Restart(); for (int i = 1; i <= 10000; i++) { if (!cacheClient.TryGet("test" + i, out otherValue)) { Console.WriteLine("Get failed for cache key: " + "test" + i); } } stopwatch.Stop(); Console.WriteLine("Get time taken: " + stopwatch.ElapsedMilliseconds + " ms, " + stopwatch.ElapsedTicks + " ticks"); #endregion #region Bulk Get 10000 strings var list2 = new List<string>(10000); for (int i = 1; i <= 10000; i++) { list2.Add("bulktest" + i); } stopwatch.Restart(); var getManyResults = cacheClient.Get<string>(list2); stopwatch.Stop(); Console.WriteLine("Get Many time taken: " + stopwatch.ElapsedMilliseconds + " ms, " + stopwatch.ElapsedTicks + " ticks"); Console.WriteLine("Get Many object count: " + getManyResults.Count); #endregion #region Tagged Get 10000 strings stopwatch.Restart(); var getTaggedResults = cacheClient.GetTagged<string>("demotag"); stopwatch.Stop(); Console.WriteLine("Get Tagged time taken: " + stopwatch.ElapsedMilliseconds + " ms, " + stopwatch.ElapsedTicks + " ticks"); Console.WriteLine("Get Tagged object count: " + getManyResults.Count); #endregion Console.WriteLine(); Console.WriteLine("***** BEGIN REMOVE 10000 TESTS *****"); Console.WriteLine(); #region Regular Remove 10000 strings stopwatch.Restart(); for (int i = 1; i <= 10000; i++) { cacheClient.Remove("test" + i); } stopwatch.Stop(); Console.WriteLine("Remove time taken: " + stopwatch.ElapsedMilliseconds + " ms, " + stopwatch.ElapsedTicks + " ticks"); #endregion #region Bulk Remove 10000 strings stopwatch.Restart(); cacheClient.Remove(list2); stopwatch.Stop(); Console.WriteLine("Remove Many time taken: " + stopwatch.ElapsedMilliseconds + " ms, " + stopwatch.ElapsedTicks + " ticks"); #endregion #region Tagged Remove 10000 strings stopwatch.Restart(); cacheClient.RemoveTagged("demotag"); stopwatch.Stop(); Console.WriteLine("Remove Tagged time taken: " + stopwatch.ElapsedMilliseconds + " ms, " + stopwatch.ElapsedTicks + " ticks"); #endregion Console.WriteLine(); Console.WriteLine("***** BEGIN ABSOLUTE EXPIRATION TEST *****"); Console.WriteLine(); #region Regular Add 10000 strings with absolute expiration var absoluteExpiration = DateTime.Now.AddMinutes(1); stopwatch.Restart(); for (int i = 1; i <= 10000; i++) { cacheClient.AddOrUpdate("testabsolute" + i, value, absoluteExpiration: absoluteExpiration); } stopwatch.Stop(); Console.WriteLine("Add absolute expiration time taken: " + stopwatch.ElapsedMilliseconds + " ms, " + stopwatch.ElapsedTicks + " ticks"); #endregion Console.WriteLine(); Console.WriteLine("***** BEGIN 10000 COMPLEX OBJECT ADD TEST *****"); Console.WriteLine(); #region Regular Add 10000 complex objects with sliding expiration var slidingExpiration = new TimeSpan(0, 2, 0); stopwatch.Restart(); for (int i = 1; i <= 10000; i++) { cacheClient.AddOrUpdate("testabsolutecomplex" + i, myObject, slidingExpiration: slidingExpiration); } stopwatch.Stop(); Console.WriteLine("Add complex object time taken: " + stopwatch.ElapsedMilliseconds + " ms, " + stopwatch.ElapsedTicks + " ticks"); #endregion Console.WriteLine(); Console.WriteLine("***** BEGIN 10000 COMPLEX OBJECT GET TEST *****"); Console.WriteLine(); #region Regular Get 10000 complex objects with sliding expiration stopwatch.Restart(); for (int i = 1; i <= 10000; i++) { cacheClient.TryGet("testabsolutecomplex" + i, out myObject); } stopwatch.Stop(); Console.WriteLine("Get complex object time taken: " + stopwatch.ElapsedMilliseconds + " ms, " + stopwatch.ElapsedTicks + " ticks"); #endregion overallStopwatch.Stop(); Console.WriteLine(); Console.WriteLine("***** END TESTS *****"); Console.WriteLine(); Console.WriteLine("Total time taken: " + overallStopwatch.ElapsedMilliseconds + " ms, " + overallStopwatch.ElapsedTicks + " ticks"); var key = Console.ReadKey(); // Graceful shutdown option if (key.KeyChar == 'q') { cacheClient.Shutdown(); } }
public EntityMetaDetailsResponse GetEntityMetaDetails(ServiceStack.ServiceInterface.Service service) { // The entity meta details don't change per entity type, so cache these for performance var cacheKey = string.Format("{0}-meta-details", EntityType.ToString().ToLower()); var metaDetails = CacheClient.Get <EntityMetaDetailsResponse>(cacheKey); if (metaDetails != null) { return(metaDetails); } var request = service.RequestContext.Get <IHttpRequest>(); var appUri = request.GetApplicationUrl().TrimEnd('/'); var baseServiceUri = appUri + request.PathInfo.Replace("/meta", ""); var queryString = request.QueryString["format"] != null ? "&format=" + request.QueryString["format"] : ""; var pkCount = FieldMap.Count(pk => pk.Value.IsPrimaryKey); var fields = new List <Link>(); foreach (var f in FieldMap) { var isUnique = false; var ucs = UniqueConstraintMap.Where(uc => uc.Value.Any(x => x.Name.Equals(f.Key, StringComparison.InvariantCultureIgnoreCase))).ToArray(); var link = Link.Create( f.Key.ToCamelCase(), f.Value.DataType.Name, "field", string.Format("{0}?select={1}{2}", baseServiceUri, f.Key.ToLowerInvariant(), queryString), string.Format("The {0} field for the {1} resource.", f.Value.Name, typeof(TDto).Name), new Dictionary <string, string>() ); var props = new SortedDictionary <string, string>(); props.Add("index", f.Value.FieldIndex.ToString(CultureInfo.InvariantCulture)); if (f.Value.IsPrimaryKey) { props.Add("isPrimaryKey", f.Value.IsPrimaryKey.ToString().ToLower()); if (pkCount == 1) { isUnique = true; } } if (f.Value.IsForeignKey) { props.Add("isForeignKey", "true"); } var ucNames = new List <string>(); foreach (var uc in ucs) { if (uc.Value.Count() == 1) { isUnique = true; } ucNames.Add(uc.Key.ToLower()); } if (ucNames.Any()) { props.Add("partOfUniqueConstraints", string.Join(",", ucNames.ToArray())); } if (isUnique) { props.Add("isUnique", "true"); } if (f.Value.IsOfEnumDataType) { props.Add("isOfEnumDataType", "true"); } if (f.Value.IsReadOnly) { props.Add("isReadOnly", "true"); } if (f.Value.IsNullable) { props.Add("isNullable", "true"); } if (f.Value.IsOfEnumDataType) { props.Add("isEnumType", "true"); } if (f.Value.MaxLength > 0) { props.Add("maxLength", f.Value.MaxLength.ToString(CultureInfo.InvariantCulture)); } if (f.Value.Precision > 0) { props.Add("precision", f.Value.Precision.ToString(CultureInfo.InvariantCulture)); } if (f.Value.Scale > 0) { props.Add("scale", f.Value.Scale.ToString(CultureInfo.InvariantCulture)); } link.Properties = new Dictionary <string, string>(props); fields.Add(link); } var includes = new List <Link>(); foreach (var f in IncludeMap) { var relationType = ""; switch (f.Value.TypeOfRelation) { case RelationType.ManyToMany: relationType = "n:n"; break; case RelationType.ManyToOne: relationType = "n:1"; break; case RelationType.OneToMany: relationType = "1:n"; break; case RelationType.OneToOne: relationType = "1:1"; break; } var relatedDtoContainerName = (Enum.GetName(typeof(EntityType), f.Value.ToFetchEntityType) ?? "").Replace("Entity", ""); var link = Link.Create( f.Key.ToCamelCase(), (relationType.EndsWith("n") ? relatedDtoContainerName + "Collection" : relatedDtoContainerName), "include", string.Format("{0}?include={1}{2}", baseServiceUri, f.Key.ToLowerInvariant(), queryString), string.Format( "The {0} field for the {1} resource to include in the results returned by a query.", f.Value.PropertyName, typeof(TDto).Name), new Dictionary <string, string> { { "field", f.Value.PropertyName.ToCamelCase() }, { "relatedType", (Enum.GetName(typeof(EntityType), f.Value.ToFetchEntityType) ?? "").Replace("Entity", "") }, { "relationType", relationType } }); includes.Add(link); } var relations = new List <Link>(); foreach (var f in RelationMap) { var isPkSide = f.Value.StartEntityIsPkSide; var isFkSide = !f.Value.StartEntityIsPkSide; var pkFieldCore = f.Value.GetAllPKEntityFieldCoreObjects().FirstOrDefault(); var fkFieldCore = f.Value.GetAllFKEntityFieldCoreObjects().FirstOrDefault(); var thisField = isPkSide ? (pkFieldCore == null ? "" : pkFieldCore.Name) : (fkFieldCore == null ? "" : fkFieldCore.Name); var relatedField = isFkSide ? (pkFieldCore == null ? "" : pkFieldCore.Name) : (fkFieldCore == null ? "" : fkFieldCore.Name); var thisEntityAlias = isPkSide ? (pkFieldCore == null ? "": pkFieldCore.ActualContainingObjectName.Replace("Entity", "")) : (fkFieldCore == null ? "": fkFieldCore.ActualContainingObjectName.Replace("Entity", "")); var relatedEntityAlias = isFkSide ? (pkFieldCore == null ? "": pkFieldCore.ActualContainingObjectName.Replace("Entity", "")) : (fkFieldCore == null ? "": fkFieldCore.ActualContainingObjectName.Replace("Entity", "")); var relationType = ""; switch (f.Value.TypeOfRelation) { case RelationType.ManyToMany: relationType = "n:n"; break; case RelationType.ManyToOne: relationType = "n:1"; break; case RelationType.OneToMany: relationType = "1:n"; break; case RelationType.OneToOne: relationType = "1:1"; break; } var link = Link.Create( f.Key.ToCamelCase(), relationType.EndsWith("n") ? relatedEntityAlias + "Collection" : relatedEntityAlias, "relation", string.Format("{0}?relations={1}{2}", baseServiceUri, f.Key.ToLowerInvariant(), queryString), string.Format( "The relation '{0}' for the {1} resource between a {2} (PK) and a {3} (FK) resource.", f.Value.MappedFieldName, typeof(TDto).Name, f.Value.AliasStartEntity.Replace("Entity", ""), f.Value.AliasEndEntity.Replace("Entity", "")), new Dictionary <string, string> { { "field", f.Value.MappedFieldName.ToCamelCase() }, { "joinHint", f.Value.JoinType.ToString().ToLower() }, { "relationType", relationType }, { "isPkSide", isPkSide.ToString().ToLower() }, { "isFkSide", isFkSide.ToString().ToLower() }, { "isWeakRelation", f.Value.IsWeak.ToString().ToLower() }, { "pkTypeName", isPkSide ? thisEntityAlias : relatedEntityAlias }, { "pkTypeField", isPkSide ? thisField.ToCamelCase() : relatedField.ToCamelCase() }, { "fkTypeName", isFkSide ? thisEntityAlias : relatedEntityAlias }, { "fkTypeField", isFkSide ? thisField.ToCamelCase() : relatedField.ToCamelCase() }, }); relations.Add(link); // add relation to fields list as well fields.Add(Link.Create( f.Value.MappedFieldName.ToCamelCase(), relationType.EndsWith("n") ? relatedEntityAlias + "Collection": relatedEntityAlias, "field", null, string.Format("The {0} field for the {1} resource.", f.Value.MappedFieldName, typeof(TDto).Name), new Dictionary <string, string> { { "relation", f.Value.MappedFieldName.ToCamelCase() }, { "relationType", relationType }, { "isPkSide", isPkSide.ToString().ToLower() }, { "isFkSide", isFkSide.ToString().ToLower() }, })); } metaDetails = new EntityMetaDetailsResponse() { Fields = fields.ToArray(), Includes = includes.ToArray(), Relations = relations.ToArray() }; CacheClient.Set(cacheKey, metaDetails); return(metaDetails); }