public async Task AddAsync(ITransaction tx, TKey key, TValue value)
        {
            if (reliableDictionary == null)
            {
                await InitializeReliableDictionary();
            }

            await reliableDictionary.AddAsync(tx, key, value);
        }
        public async Task <IActionResult> Post(string id)
        {
            IReliableDictionary <string, Game> gamesDictionary = await _stateManager.GetOrAddAsync <IReliableDictionary <string, Game> >("games");

            using (ITransaction tx = _stateManager.CreateTransaction())
            {
                bool gameExists = await gamesDictionary.ContainsKeyAsync(tx, id);

                if (gameExists)
                {
                    return(BadRequest("Game already exists"));
                }

                var game = new Game
                {
                    State = new TicTacToeState()
                    {
                        Board = new string[9], IsXTurn = true,
                    },
                    UserRoles = new Dictionary <string, string>()
                };

                await gamesDictionary.AddAsync(tx, id, game);

                await tx.CommitAsync();

                return(Ok());
            }
        }
        /// <summary>
        /// Inner GetOrAdd for a collection.
        /// This method adds new metric collection type information for new collections as part of the same transaction.
        /// </summary>
        /// <param name="tx"></param>
        /// <param name="type"></param>
        /// <param name="name"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        private async Task <ConditionalValue <IReliableState> > TryCreateOrGetMetricReliableCollectionAsync(ITransaction tx, Type type, Uri name, TimeSpan timeout)
        {
            if (type.GetGenericTypeDefinition() == typeof(IReliableDictionary <,>))
            {
                // Store the given type information for the collection with the given name.
                // The type information is used to recreate the collection during enumeration.
                IReliableDictionary <string, string> metricDictionaryTypes = await this.GetTypeNameDictionaryAsync();

                if (!(await metricDictionaryTypes.ContainsKeyAsync(tx, name.ToString(), LockMode.Update)))
                {
                    await metricDictionaryTypes.AddAsync(tx, name.ToString(), type.AssemblyQualifiedName);
                }

                IReliableDictionary <BinaryValue, BinaryValue> innerStore =
                    await this.stateManagerReplica.GetOrAddAsync <IReliableDictionary <BinaryValue, BinaryValue> >(tx, name, timeout);

                return(new ConditionalValue <IReliableState>(
                           true,
                           MetricReliableDictionaryActivator.CreateFromReliableDictionaryType(
                               type,
                               innerStore,
                               new BinaryValueConverter(name, this.serializerResolver),
                               this.config)));
            }

            return(new ConditionalValue <IReliableState>(false, null));
        }
Beispiel #4
0
        /// <summary>
        /// This method executes on the bidder's partition.
        /// Called by web: priority 0
        /// </summary>
        public async Task <ItemInfo> CreateItemAsync(String sellerEmail, String itemName, String imageUrl, DateTime expiration, Decimal startAmount, CancellationToken cancellationToken)
        {
            // NOTE: If items gets large, old item value (but not key) can move to warm storage

            // If user exists, create item & transactionally and it to user's items dictionary & unexpired items dictionary
            Email _sellerEmail = Email.Parse(sellerEmail);

            using (var tx = CreateTransaction()) {
                var cr = await m_users.TryGetValueAsync(tx, _sellerEmail);

                if (!cr.HasValue)
                {
                    throw new InvalidOperationException($"Seller '{_sellerEmail}' doesn't exist.");
                }

                // Look up user's (seller's) auction item dictionary & add the new item to it:
                IReliableDictionary <ItemId, ItemInfo> userItems = await GetSellerItemsAsync(_sellerEmail);

                ItemId   itemId = ItemId.Parse(_sellerEmail, itemName);
                ItemInfo item   = new ItemInfo(itemId, imageUrl, expiration, new[] { new Bid(_sellerEmail, startAmount) }); // Seller places first bid
                try {
                    await userItems.AddAsync(tx, itemId, item);                                                             // TODO: If already exists
                }
                catch (Exception ex) {
                    throw new InvalidOperationException($"Seller '{itemId.Seller}' is already selling '{itemId.ItemName}'.", ex);
                }
                await m_unexpiredItems.AddAsync(tx, itemId);

                await tx.CommitAsync();

                return(item);
            }
        }
        public async Task <IActionResult> Put(string name, [FromBody] ValueViewModel value)
        {
            try
            {
                IReliableDictionary <string, string> dictionary =
                    await this.stateManager.GetOrAddAsync <IReliableDictionary <string, string> >(ValuesDictionaryName);

                using (ITransaction tx = this.stateManager.CreateTransaction())
                {
                    await dictionary.AddAsync(tx, name, value.Value);

                    await tx.CommitAsync();
                }
            }
            catch (ArgumentException)
            {
                return(new ContentResult {
                    StatusCode = 400, Content = $"A value with name {name} already exists."
                });
            }
            catch (FabricNotPrimaryException)
            {
                return(new ContentResult {
                    StatusCode = 503, Content = "The primary replica has moved. Please re-resolve the service."
                });
            }
            catch (FabricException)
            {
                return(new ContentResult {
                    StatusCode = 503, Content = "The service was unable to process the request. Please try again."
                });
            }

            return(this.Ok());
        }
Beispiel #6
0
        /// <summary>
        /// Adds elements to the queuestorage
        /// </summary>
        /// <param name="newMessage"></param>
        /// <returns></returns>
        public async Task <bool> SetQueueInformation(string newMessage)
        {
            try
            {
                CancellationToken token = this.serviceCancellationToken;

                IReliableDictionary <long, string> queueinfo = await this.StateManager.GetOrAddAsync <IReliableDictionary <long, string> >("QueueData");

                using (ITransaction tx = this.StateManager.CreateTransaction())
                {
                    long newid = Environment.TickCount;
                    if (!await queueinfo.ContainsKeyAsync(tx, newid))
                    {
                        await queueinfo.AddAsync(tx, newid, newMessage);
                    }
                    await tx.CommitAsync();
                }

                return(true);
            }
            catch
            {
                return(false);
            }
        }
 private async Task AddClusters(ITransaction tx, IReliableDictionary <int, Cluster> dictionary, int count, Func <Cluster> newCluster)
 {
     for (int i = 0; i < count; ++i)
     {
         await dictionary.AddAsync(tx, GetRandom(), newCluster());
     }
 }
Beispiel #8
0
        private async Task ExecuteAddOrderAsync(Order order, IReliableDictionary <string, Order> orders)
        {
            using (ITransaction tx = this.stateManager.CreateTransaction())
            {
                await orders.AddAsync(tx, order.Id, order);

                await tx.CommitAsync();
            }
        }
Beispiel #9
0
        public async Task <IActionResult> NewGame(string roomid, string playerid, string playerdata, string roomtype)
        {
            try
            {
                if (!RoomManager.IsActive)
                {
                    return new ContentResult {
                               StatusCode = 503, Content = "Service is still starting up. Please retry."
                    }
                }
                ;

                Player player = JsonConvert.DeserializeObject <Player>(playerdata);

                //get the general room dictionary
                IReliableDictionary <string, Room> roomdict =
                    await this.stateManager.GetOrAddAsync <IReliableDictionary <string, Room> >(RoomDictionaryName);

                //get or add the active room we will put this player in
                IReliableDictionary <string, ActivePlayer> activeroom =
                    await this.stateManager.GetOrAddAsync <IReliableDictionary <string, ActivePlayer> >(roomid);

                using (ITransaction tx = this.stateManager.CreateTransaction())
                {
                    //Find the room in the room dictionary
                    ConditionalValue <Room> roomOption = await roomdict.TryGetValueAsync(tx, roomid, LockMode.Update);

                    if (!roomOption.HasValue)
                    {
                        //Scenario: Room does not exist yet
                        await roomdict.AddAsync(tx, roomid, new Room(1, roomtype));
                    }
                    else
                    {
                        //Scenario: Room does exist
                        Room newRoom = roomOption.Value;
                        newRoom.NumPlayers++;
                        await roomdict.SetAsync(tx, roomid, newRoom);
                    }

                    //Add the data to that room
                    await activeroom.SetAsync(tx, playerid, new ActivePlayer(player, DateTime.UtcNow));

                    await tx.CommitAsync();
                }

                return(new ContentResult {
                    StatusCode = 200, Content = "Successfully Logged In"
                });
            }
            catch (Exception e)
            {
                return(exceptionHandler(e));
            }
        }
        /// <summary>
        /// This method saves the description (eventString) and timestamp of the recentmost induced fault as
        /// a ChaosEntry in a Reliable Dictionary
        /// </summary>
        /// <param name="eventString"></param>
        /// <returns>A task to await on</returns>
        private async Task StoreEventAsync(string eventString)
        {
            ServiceEventSource.Current.ServiceMessage(this, "ChaosTest: {0}", eventString);

            IReliableDictionary <string, long> eventCount =
                await this.StateManager.GetOrAddAsync <IReliableDictionary <string, long> >(StringResource.EventCountKey);

            IReliableDictionary <string, DateTime> startTime =
                await this.StateManager.GetOrAddAsync <IReliableDictionary <string, DateTime> >(StringResource.StartTimeKey);

            IReliableDictionary <long, ChaosEntry> savedEvents =
                await this.StateManager.GetOrAddAsync <IReliableDictionary <long, ChaosEntry> >(StringResource.SavedEventsKey);


            using (ITransaction tx = this.StateManager.CreateTransaction())
            {
                if (!await startTime.ContainsKeyAsync(tx, StringResource.StartTimeKey))
                {
                    await startTime.AddAsync(tx, StringResource.StartTimeKey, DateTime.UtcNow);
                }

                if (!await eventCount.ContainsKeyAsync(tx, StringResource.EventCountKey))
                {
                    await eventCount.AddAsync(tx, StringResource.EventCountKey, 0);
                }

                ConditionalValue <long> result =
                    await eventCount.TryGetValueAsync(tx, StringResource.EventCountKey, LockMode.Update);

                if (result.HasValue)
                {
                    long currentCount = result.Value;

                    // If we have HistoryLength number of events, we make room for new events by removing oldest ones,
                    // always keeping HistoryLength number of recentmost events on the show on the webpage.
                    if (currentCount > Constants.HistoryLength - 1)
                    {
                        await savedEvents.TryRemoveAsync(tx, currentCount - Constants.HistoryLength + 1);
                    }

                    ChaosEntry chaosEntry = new ChaosEntry
                    {
                        Record    = eventString,
                        TimeStamp = DateTime.UtcNow.ToString(CultureInfo.InvariantCulture)
                    };

                    await savedEvents.AddAsync(tx, ++currentCount, chaosEntry);

                    await eventCount.SetAsync(tx, StringResource.EventCountKey, currentCount);

                    await tx.CommitAsync();
                }
            }
        }
        private async Task Populate(CancellationToken cancellationToken)
        {
            IReliableDictionary <string, string> list = await this.GetListAsync();

            using (ITransaction tx = this.stateManager.CreateTransaction())
            {
                await list.AddAsync(tx, Guid.NewGuid().ToString(), DateTime.Now.ToString());

                await tx.CommitAsync();
            }
        }
Beispiel #12
0
        private async Task AddToHistoryAsync(CheckoutSummary checkout)
        {
            IReliableDictionary <DateTime, CheckoutSummary> history = await StateManager.GetOrAddAsync <IReliableDictionary <DateTime, CheckoutSummary> >("history");

            using (ITransaction transaction = StateManager.CreateTransaction())
            {
                await history.AddAsync(transaction, checkout.Date, checkout);

                await transaction.CommitAsync();
            }
        }
Beispiel #13
0
        private async Task AddToHistoryAsync(CheckoutSummary summary)
        {
            IReliableDictionary <DateTime, CheckoutSummary> history =
                await StateManager.GetOrAddAsync <IReliableDictionary <DateTime, CheckoutSummary> >(HISTORY_COLLECTION);

            using (ITransaction tx = StateManager.CreateTransaction())
            {
                await history.AddAsync(tx, summary.Date, summary);

                await tx.CommitAsync();
            }
        }
 private static async Task SaveToCache(
     string query,
     IReliableDictionary <string, CachedItem <SearchOutput> > cache,
     SearchOutput output,
     ITransaction tx)
 {
     await cache.AddAsync(tx, query, new CachedItem <SearchOutput>
     {
         CachedAt = DateTime.UtcNow,
         Data     = output
     });
 }
Beispiel #15
0
        /// <summary>
        /// Adds clusters by the given amount without going over the max threshold and without resulting in below the min threshold.
        /// </summary>
        /// <param name="targetCount"></param>
        /// <returns></returns>
        internal async Task BalanceClustersAsync(int target)
        {
            Random random = new Random();

            IReliableDictionary <int, Cluster> clusterDictionary =
                await this.reliableStateManager.GetOrAddAsync <IReliableDictionary <int, Cluster> >(ClusterDictionaryName);

            using (ITransaction tx = this.reliableStateManager.CreateTransaction())
            {
                var activeClusters     = this.GetActiveClusters(clusterDictionary);
                int activeClusterCount = activeClusters.Count();

                if (target < this.Config.MinimumClusterCount)
                {
                    target = this.Config.MinimumClusterCount;
                }

                if (target > this.Config.MaximumClusterCount)
                {
                    target = this.Config.MaximumClusterCount;
                }

                if (activeClusterCount < target)
                {
                    int limit = Math.Min(target, this.Config.MaximumClusterCount);

                    for (int i = 0; i < limit - activeClusterCount; ++i)
                    {
                        await clusterDictionary.AddAsync(tx, random.Next(), new Cluster());
                    }

                    await tx.CommitAsync();
                }

                if (activeClusterCount > target)
                {
                    var removeList = activeClusters
                                     .Where(x => x.Value.Users.Count == 0)
                                     .Take(Math.Min(activeClusterCount - this.Config.MinimumClusterCount, activeClusterCount - target));

                    foreach (var item in removeList)
                    {
                        Cluster value = item.Value;
                        value.Status = ClusterStatus.Remove;

                        await clusterDictionary.SetAsync(tx, item.Key, value);
                    }

                    await tx.CommitAsync();
                }
            }
        }
        public async Task <IActionResult> Post([FromRoute] string name)
        {
            ServiceEventSource.Current.ServiceMessage(this._serviceContext, $"Spinning up ingestion worker {name}");


            // establish the information for the event hub, to which we're connecting
            // load the connection string from event hub
            var ehConfiguration = this._serviceContext.CodePackageActivationContext
                                  .GetConfigurationPackageObject("Config")
                                  .Settings
                                  .Sections["EventHubConfiguration"];

            var eventHubConnectionString = ehConfiguration.Get("ConnectionString");
            var eventHubConsumerGroup    = ehConfiguration.Get("ConsumerGroup");
            var eventHubMaxBatchSize     = ehConfiguration.TryGetAsInt("MaxBatchSize", 100);

            // start connecting to the event hub
            var client = EventHubClient.CreateFromConnectionString(eventHubConnectionString);

            // verify the partition exists
            var eventHubInfo = await client.GetRuntimeInformationAsync();

            ServiceEventSource.Current.ServiceMessage(this._serviceContext, $"Ingestion worker {name} will connect to EH {client.EventHubName}");

            var lowKey  = 0;
            var highKey = eventHubInfo.PartitionCount - 1;

            var appName = _serviceContext.CodePackageActivationContext.ApplicationName;
            var svcName = $"{appName}/{Names.IngestorSuffix}/{name}";

            await _fabricClient.ServiceManager.CreateServiceAsync(new StatefulServiceDescription()
            {
                HasPersistedState          = true,
                PartitionSchemeDescription = new UniformInt64RangePartitionSchemeDescription(eventHubInfo.PartitionCount, lowKey, highKey),
                ServiceTypeName            = Names.IngestorTypeName,
                ApplicationName            = new System.Uri(appName),
                ServiceName = new System.Uri(svcName)
            });

            ServiceEventSource.Current.ServiceMessage(this._serviceContext, $"Ingestion worker {name} spun up on {svcName}");

            // store the name of the ingestor for the service in the dictionary, so that we can monitor this
            // outside the SF portal
            using (var tx = this._stateManager.CreateTransaction())
            {
                await _ingestorDictionary.AddAsync(tx, svcName, eventHubInfo.PartitionCount.ToString());

                await tx.CommitAsync();
            }

            return(Ok($"Ingestor created: {svcName}"));
        }
Beispiel #17
0
        public async Task AddKeyAsync(string key, string value)
        {
            if (_dict == null)
            {
                throw new NullReferenceException(nameof(_dict));
            }
            using (var tx = this.StateManager.CreateTransaction())
            {
                await _dict.AddAsync(tx, key, value);

                await tx.CommitAsync();
            }
        }
Beispiel #18
0
        public async Task <IActionResult> Post(string value)
        {
            IReliableDictionary <string, string> valuesList = await _stateManager.GetOrAddAsync <IReliableDictionary <string, string> >("values");

            using (ITransaction tx = _stateManager.CreateTransaction())
            {
                await valuesList.AddAsync(tx, value, value);

                await tx.CommitAsync();
            }

            return(new OkResult());
        }
Beispiel #19
0
        public async Task AddToHistoryAsync(CheckoutSummary checkout)
        {
            // Get or Create history list
            IReliableDictionary <DateTime, CheckoutSummary> history =
                await StateManager.GetOrAddAsync <IReliableDictionary <DateTime, CheckoutSummary> >("history");

            using (ITransaction tx = StateManager.CreateTransaction())
            {
                // Add the new checkout to history.
                await history.AddAsync(tx, checkout.Date, checkout);

                await tx.CommitAsync();
            }
        }
        /// <summary>
        /// Used internally to generate inventory items and adds them to the ReliableDict we have.
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public async Task <bool> CreateInventoryItemAsync(Domain.CustomerInformation item)
        {
            IReliableDictionary <string, Domain.CustomerInformation> inventoryItems =
                await this.StateManager.GetOrAddAsync <IReliableDictionary <string, Domain.CustomerInformation> >(CustomerInformationDictionary);

            using (ITransaction tx = this.StateManager.CreateTransaction())
            {
                await inventoryItems.AddAsync(tx, item.Id, item);

                await tx.CommitAsync();
            }

            return(true);
        }
        public async Task AddMessageAsync(Message message)
        {
            DateTime time = DateTime.Now.ToLocalTime();

            IReliableDictionary <DateTime, Message> messagesDictionary =
                await this.StateManager.GetOrAddAsync <IReliableDictionary <DateTime, Message> >("messages");

            using (ITransaction tx = this.StateManager.CreateTransaction())
            {
                await messagesDictionary.AddAsync(tx, time, message);

                await tx.CommitAsync();
            }
        }
Beispiel #22
0
        public async Task <bool> AddOrUpdateAsync(Person person)
        {
            using (var ctx = this.StateManager.CreateTransaction())
            {
                var personId      = person.Id;
                var currentPerson = (Person)null;

                if (await _personDictionary.ContainsKeyAsync(ctx, personId))
                {
                    var personValue = await _personDictionary.TryGetValueAsync(ctx, personId);

                    if (personValue.HasValue)
                    {
                        currentPerson = personValue.Value;
                    }
                }

                if (currentPerson == null)
                {
                    await _personDictionary.AddAsync(ctx, person.Id, person);

                    if (!String.IsNullOrWhiteSpace(person.EmailAddress))
                    {
                        await _emailLookupDictionary.AddAsync(ctx, person.EmailAddress, person.Id);
                    }

                    if (!String.IsNullOrWhiteSpace(person.TwitterHandle))
                    {
                        await _twitterLookupDictionary.AddAsync(ctx, person.TwitterHandle, person.Id);
                    }

                    await ctx.CommitAsync();

                    return(true);
                }
                else
                {
                    if (await _personDictionary.TryUpdateAsync(ctx, person.Id, person, currentPerson))
                    {
                        await ctx.CommitAsync();

                        return(true);
                    }
                }
            }

            return(false);
        }
Beispiel #23
0
        public async Task StartAnalysis(int partitionKey, byte[] imagebyte)
        {
            //this.analysisCollection =
            //    await this.StateManager.GetOrAddAsync<IReliableDictionary<string, AnalysisState>>("statuscollection");

            using (ITransaction tx = this.StateManager.CreateTransaction())
            {
                var state = new AnalysisState();
                //var state = new AnalysisState(imagebyte);
                await analysisCollection.AddAsync(tx, partitionKey, state);

                await byteCollection.AddAsync(tx, partitionKey, imagebyte);

                await tx.CommitAsync();
            }
        }
Beispiel #24
0
        /// <summary>
        /// Used internally to generate inventory items and adds them to the ReliableDict we have.
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public async Task <bool> CreateInventoryItemAsync(InventoryItem item)
        {
            IReliableDictionary <InventoryItemId, InventoryItem> inventoryItems =
                await this.stateManager.GetOrAddAsync <IReliableDictionary <InventoryItemId, InventoryItem> >(InventoryItemDictionaryName);

            using (ITransaction tx = this.stateManager.CreateTransaction())
            {
                await inventoryItems.AddAsync(tx, item.Id, item);

                await tx.CommitAsync();

                ServiceEventSource.Current.ServiceMessage(this, "Created inventory item: {0}", item);
            }

            return(true);
        }
        /// <summary>
        /// This method activates an actor to fulfill the RestockRequest.
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task AddRestockRequestAsync(RestockRequest request)
        {
            try
            {
                //Get dictionary of Restock Requests
                IReliableDictionary <InventoryItemId, ActorId> requestDictionary =
                    await this.StateManager.GetOrAddAsync <IReliableDictionary <InventoryItemId, ActorId> >(ItemIdToActorIdMapName);

                ActorId actorId = ActorId.CreateRandom();

                try
                {
                    using (ITransaction tx = this.StateManager.CreateTransaction())
                    {
                        await requestDictionary.AddAsync(tx, request.ItemId, actorId);

                        await tx.CommitAsync();
                    }
                }
                catch (ArgumentException)
                {
                    // restock request already exists
                    return;
                }

                // Create actor proxy and send the request
                IRestockRequestActor restockRequestActor = ActorProxy.Create <IRestockRequestActor>(actorId, this.ApplicationName);

                await restockRequestActor.AddRestockRequestAsync(request);

                // Successfully added, register for event notifications for completion
                await restockRequestActor.SubscribeAsync <IRestockRequestEvents>(this);

                ServiceEventSource.Current.ServiceMessage(this, "Created restock request. Item ID: {0}. Actor ID: {1}", request.ItemId, actorId);
            }
            catch (InvalidOperationException ex)
            {
                ServiceEventSource.Current.Message(string.Format("RestockRequestManagerService: Actor rejected {0}: {1}", request, ex));
                throw;
            }
            catch (Exception ex)
            {
                ServiceEventSource.Current.Message(string.Format("RestockRequestManagerService: Exception {0}: {1}", request, ex));
                throw;
            }
        }
Beispiel #26
0
        public async Task <IActionResult> Create([FromBody] PostsRequest request)
        {
            Post post = new Post();

            post.message  = request.message;
            post.userName = request.userName;
            IReliableDictionary <string, Post> votesDictionary = await this.stateManager.GetOrAddAsync <IReliableDictionary <string, Post> >("posts");

            using (ITransaction tx = this.stateManager.CreateTransaction())
            {
                await votesDictionary.AddAsync(tx, post.id.ToString(), post);

                await tx.CommitAsync();
            }

            return(new OkResult());
        }
Beispiel #27
0
        private async Task FillWithData(CancellationToken cancellationToken)
        {
            bool Done = false;
            IReliableDictionary <int, List <TechSkill> > dictionary = await StateManager.GetOrAddAsync <IReliableDictionary <int, List <TechSkill> > >(SkillDictionaryName);



            //fill with sample data
            while (!Done)
            {
                try
                {
                    // Create a new Transaction object for this partition
                    using (ITransaction tx = base.StateManager.CreateTransaction())
                    {
                        IAsyncEnumerable <KeyValuePair <int, List <TechSkill> > > SkillEnum = (await dictionary.CreateEnumerableAsync(tx));

                        TechSkill tsk = new TechSkill
                        {
                            ResourceId = 1,
                            Name       = "C#",
                            Level      = Models.Domain.Level.Expert,
                            Notes      = string.Empty
                        };

                        List <TechSkill> skills = new List <TechSkill>();
                        skills.Add(tsk);

                        await dictionary.AddAsync(tx, tsk.ResourceId, skills);

                        // CommitAsync sends Commit record to log & secondary replicas
                        // After quorum responds, all locks released
                        await tx.CommitAsync();
                    }
                    // If CommitAsync not called, Dispose sends Abort
                    // record to log & all locks released
                    Done = true;
                }
                catch (TimeoutException)
                {
                    Done = false;
                    await Task.Delay(100, cancellationToken);
                }
            }
        }
Beispiel #28
0
        private async Task <string> ExecuteAddUserAsync(User user, IReliableDictionary <string, User> users, CancellationToken cancellationToken)
        {
            using (var tx = this.StateManager.CreateTransaction())
            {
                var current = await users.TryGetValueAsync(tx, user.Id);

                if (current.HasValue)
                {
                    return(user.Id); // Return existing user
                }
                await users.AddAsync(tx, user.Id, user, TimeSpan.FromSeconds(15), cancellationToken);

                await tx.CommitAsync();

                MetricsLog?.UserCreated(user);
            }
            return(user.Id);
        }
        public async Task Post([FromBody] List <DoctorStatsViewModel> stats)
        {
            try
            {
                IReliableDictionary <int, string> countyNameDictionary =
                    await this.stateManager.GetOrAddAsync <IReliableDictionary <int, string> >(CountyService.CountyNameDictionaryName);

                foreach (var stat in stats)
                {
                    ServiceEventSource.Current.Message("Saving for county {0}", stat.countyId);

                    IReliableDictionary <Guid, CountyDoctorStats> countyHealth =
                        await
                        this.stateManager.GetOrAddAsync <IReliableDictionary <Guid, CountyDoctorStats> >(
                            string.Format(CountyService.CountyHealthDictionaryName, stat.countyId));

                    using (ITransaction tx = this.stateManager.CreateTransaction())
                    {
                        await
                        countyHealth.SetAsync(
                            tx,
                            stat.DoctorId,
                            new CountyDoctorStats(stat.PatientCount, stat.HealthReportCount, stat.DoctorName, stat.AverageHealthIndex));

                        // Add the county only if it does not already exist.
                        ConditionalValue <string> getResult = await countyNameDictionary.TryGetValueAsync(tx, stat.countyId);

                        if (!getResult.HasValue)
                        {
                            await countyNameDictionary.AddAsync(tx, stat.countyId, String.Empty);
                        }

                        // finally, commit the transaction and return a result
                        await tx.CommitAsync();
                    }
                }
                return;
            }
            catch (Exception e)
            {
                ServiceEventSource.Current.Message("Exception in CountyHealthController {0}", e);
                throw;
            }
        }
Beispiel #30
0
        /// <summary>
        /// This method executes on the bidder's partition.
        /// Called by web: priority 0
        /// </summary>
        public async Task <UserInfo> CreateUserAsync(String userEmail, CancellationToken cancellationToken)
        {
            // Create user and add to dictionary; fail if user already exists
            Email _userEmail = Email.Parse(userEmail);

            using (var tx = CreateTransaction()) {
                var userInfo = new UserInfo(_userEmail);
                try {
                    await m_users.AddAsync(tx, _userEmail, userInfo);

                    await tx.CommitAsync();

                    return(userInfo);
                }
                catch (Exception ex) { // Change to what if already exists
                    throw new InvalidOperationException($"User '{_userEmail}' already exists.", ex);
                }
            }
        }
 private async Task AddClusters(ITransaction tx, IReliableDictionary<int, Cluster> dictionary, int count, Func<Cluster> newCluster)
 {
     for (int i = 0; i < count; ++i)
     {
         await dictionary.AddAsync(tx, this.GetRandom(), newCluster());
     }
 }