public async Task <bool> ContainsKeyAsync(ITransaction tx, TKey key)
        {
            if (reliableDictionary == null)
            {
                await InitializeReliableDictionary();
            }

            return(await reliableDictionary.ContainsKeyAsync(tx, key));
        }
        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());
            }
        }
Exemple #3
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);
            }
        }
        /// <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));
        }
Exemple #5
0
        public async Task <Person> GetByEmailOrTwitterAsync(string email, string twitter)
        {
            using (var ctx = this.StateManager.CreateTransaction())
            {
                var personId = Guid.Empty;
                if (!String.IsNullOrWhiteSpace(email) && await _emailLookupDictionary.ContainsKeyAsync(ctx, email.ToLower()))
                {
                    var personValue = await _emailLookupDictionary.TryGetValueAsync(ctx, email.ToLower());

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

                if (personId == Guid.Empty && !String.IsNullOrWhiteSpace(twitter) && await _twitterLookupDictionary.ContainsKeyAsync(ctx, twitter.ToLower()))
                {
                    var personValue = await _twitterLookupDictionary.TryGetValueAsync(ctx, twitter.ToLower());

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

                if (personId == Guid.Empty)
                {
                    return(null);
                }

                var person = await _personDictionary.TryGetValueAsync(ctx, personId);

                return(person.HasValue ? person.Value : null);
            }
        }
Exemple #6
0
 public async Task <bool> ExistsAsync(string key)
 {
     using (var tx = _stateManager.CreateTransaction())
     {
         return(await _dictionary.ContainsKeyAsync(tx, key));
     }
 }
Exemple #7
0
 private async Task <bool> ExecuteContainsAsync(string orderId, IReliableDictionary <string, Order> orders)
 {
     using (var tx = this.stateManager.CreateTransaction())
     {
         return(await orders.ContainsKeyAsync(tx, orderId));
     }
 }
        public async Task <IActionResult> Delete(string name)
        {
            ServiceEventSource.Current.Message($"VotingData.Delete start. name='{name}'");
            ConditionalValue <int> result = new ConditionalValue <int>(false, -1);

            IReliableDictionary <string, int> votesDictionary = await this.stateManager.GetOrAddAsync <IReliableDictionary <string, int> >("votes");

            IReliableDictionary <string, long> ballotDictionary = await this.stateManager.GetOrAddAsync <IReliableDictionary <string, long> >("ballots");

            using (ITransaction tx = this.stateManager.CreateTransaction())
            {
                if (await votesDictionary.ContainsKeyAsync(tx, name))
                {
                    ConditionalValue <int> deleteVotes = await votesDictionary.TryGetValueAsync(tx, name);

                    result = await votesDictionary.TryRemoveAsync(tx, name);

                    long ballots = await GetTotalBallotsCast();
                    await AuditBallot(-1 *(ballots >= deleteVotes.Value ? deleteVotes.Value : ballots));

                    await tx.CommitAsync();

                    ServiceEventSource.Current.Message($"VotingData.Delete end. '{name}' deleted.");
                    return(new OkResult());
                }
                else
                {
                    ServiceEventSource.Current.Message($"VotingData.Delete end. '{name}' not found.");
                    return(new NotFoundResult());
                }
            }
        }
        /// <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();
                }
            }
        }
Exemple #10
0
        public async Task <IActionResult> GetGame(string roomid)
        {
            try
            {
                if (!RoomManager.IsActive)
                {
                    return new ContentResult {
                               StatusCode = 500, Content = "Service is still starting up. Please retry."
                    }
                }
                ;

                IReliableDictionary <string, Room> roomdict =
                    await this.stateManager.GetOrAddAsync <IReliableDictionary <string, Room> >(RoomDictionaryName);

                List <KeyValuePair <string, Player> > result = new List <KeyValuePair <string, Player> >();

                using (ITransaction tx = this.stateManager.CreateTransaction())
                {
                    //Make sure the requested room exists
                    if (!await roomdict.ContainsKeyAsync(tx, roomid))
                    {
                        await tx.CommitAsync();

                        return(new ContentResult {
                            StatusCode = 400, Content = "This room does not exist"
                        });
                    }

                    IReliableDictionary <string, ActivePlayer> activeroom =
                        await this.stateManager.GetOrAddAsync <IReliableDictionary <string, ActivePlayer> >(roomid);

                    //Return an eumerator of the rooms in this dictionary to be parsed together with others
                    IAsyncEnumerable <KeyValuePair <string, ActivePlayer> > enumerable = await activeroom.CreateEnumerableAsync(tx);

                    IAsyncEnumerator <KeyValuePair <string, ActivePlayer> > enumerator = enumerable.GetAsyncEnumerator();

                    while (await enumerator.MoveNextAsync(CancellationToken.None))
                    {
                        result.Add(new KeyValuePair <string, Player>(enumerator.Current.Key, enumerator.Current.Value.Player));
                    }
                    await tx.CommitAsync();
                }

                return(new ContentResult {
                    StatusCode = 200, Content = JsonConvert.SerializeObject(result)
                });
            }
            catch (Exception e)
            {
                return(exceptionHandler(e));
            }
        }
Exemple #11
0
        public async Task <IActionResult> Exists(string roomid, string playerid)
        {
            try
            {
                if (!RoomManager.IsActive)
                {
                    return new ContentResult {
                               StatusCode = 500, Content = "Service is still starting up. Please retry."
                    }
                }
                ;

                IReliableDictionary <string, Room> roomdict =
                    await this.stateManager.GetOrAddAsync <IReliableDictionary <string, Room> >(RoomDictionaryName);

                using (ITransaction tx = this.stateManager.CreateTransaction())
                {
                    //Check that the room exists
                    if (!await roomdict.ContainsKeyAsync(tx, roomid))
                    {
                        await tx.CommitAsync();

                        return(new ContentResult {
                            StatusCode = 200, Content = "false"
                        });
                    }

                    IReliableDictionary <string, ActivePlayer> activeroom =
                        await this.stateManager.GetOrAddAsync <IReliableDictionary <string, ActivePlayer> >(roomid);

                    //check int hat room for the player
                    if (!await activeroom.ContainsKeyAsync(tx, playerid))
                    {
                        await tx.CommitAsync();

                        return(new ContentResult {
                            StatusCode = 200, Content = "false"
                        });
                    }

                    await tx.CommitAsync();
                }

                return(new ContentResult {
                    StatusCode = 200, Content = "true"
                });
            }
            catch (Exception e)
            {
                return(exceptionHandler(e));
            }
        }
Exemple #12
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);
        }
        public async Task <IActionResult> Get(string id)
        {
            IReliableDictionary <string, UserData> usersDict = await this.stateManager.GetOrAddAsync <IReliableDictionary <string, UserData> >(USERS);

            using (ITransaction tx = this.stateManager.CreateTransaction())
            {
                if (!await usersDict.ContainsKeyAsync(tx, id))
                {
                    return(new NoContentResult());
                }

                var result = await usersDict.TryGetValueAsync(tx, id);

                return(this.Json(result.Value));
            }
        }
Exemple #14
0
        /// <summary>
        /// Delete the given key from the category dictionary.
        /// </summary>
        /// <param name="stateName">State name</param>
        /// <param name="key">Key</param>
        /// <returns>Task</returns>
        internal async Task <bool> DeleteFromState(string stateName, string key)
        {
            IReliableDictionary <string, string> votesDictionary = await this.stateManager.GetOrAddAsync <IReliableDictionary <string, string> >(stateName);

            using (ITransaction tx = this.stateManager.CreateTransaction())
            {
                if (await votesDictionary.ContainsKeyAsync(tx, key))
                {
                    await votesDictionary.TryRemoveAsync(tx, key);

                    await tx.CommitAsync();

                    return(true);
                }
                return(false);
            }
        }
        public async Task <IReadOnlyCollection <bool> > ExistsAsync(IEnumerable <string> fullPaths, CancellationToken cancellationToken)
        {
            GenericValidation.CheckBlobFullPaths(fullPaths);

            var result = new List <bool>();

            using (ServiceFabricTransaction tx = GetTransaction())
            {
                IReliableDictionary <string, byte[]> coll = await OpenCollectionAsync().ConfigureAwait(false);

                foreach (string fullPath in fullPaths)
                {
                    bool exists = await coll.ContainsKeyAsync(tx.Tx, ToFullPath(fullPath)).ConfigureAwait(false);

                    result.Add(exists);
                }
            }
            return(result);
        }
        public async Task <IEnumerable <bool> > ExistsAsync(IEnumerable <string> ids, CancellationToken cancellationToken)
        {
            GenericValidation.CheckBlobId(ids);

            var result = new List <bool>();

            using (ServiceFabricTransaction tx = GetTransaction())
            {
                IReliableDictionary <string, byte[]> coll = await OpenCollectionAsync();

                foreach (string id in ids)
                {
                    bool exists = await coll.ContainsKeyAsync(tx.Tx, ToId(id));

                    result.Add(exists);
                }
            }
            return(result);
        }
Exemple #17
0
        public async Task <ActionResult> Delete(string id)
        {
            IReliableDictionary <string, Employee> employees = await this.stateManager.GetOrAddAsync <IReliableDictionary <string, Employee> >("employees");

            using (ITransaction tx = this.stateManager.CreateTransaction())
            {
                if (await employees.ContainsKeyAsync(tx, id))
                {
                    await employees.TryRemoveAsync(tx, id);

                    await tx.CommitAsync();

                    return(new OkResult());
                }
                else
                {
                    return(new NotFoundResult());
                }
            }
        }
        public async Task <IActionResult> Delete(string name)
        {
            IReliableDictionary <string, string> buildsDictionary = await this.stateManager.GetOrAddAsync <IReliableDictionary <string, string> >("builds");

            using (ITransaction tx = this.stateManager.CreateTransaction())
            {
                if (await buildsDictionary.ContainsKeyAsync(tx, name))
                {
                    await buildsDictionary.TryRemoveAsync(tx, name);

                    await tx.CommitAsync();

                    return(new OkResult());
                }
                else
                {
                    return(new NotFoundResult());
                }
            }
        }
Exemple #19
0
        public async Task <IActionResult> Delete(string name)
        {
            logger.Information("Delete vote option {VotingOption}", name);
            IReliableDictionary <string, int> votesDictionary = await this.stateManager.GetOrAddAsync <IReliableDictionary <string, int> >("counts");

            using (ITransaction tx = this.stateManager.CreateTransaction())
            {
                if (await votesDictionary.ContainsKeyAsync(tx, name))
                {
                    await votesDictionary.TryRemoveAsync(tx, name);

                    await tx.CommitAsync();

                    return(new OkResult());
                }
                else
                {
                    return(new NotFoundResult());
                }
            }
        }
        public async Task <IActionResult> Get(string id)
        {
            IReliableDictionary <string, List <MessageData> > msgsDict = await this.stateManager.GetOrAddAsync <IReliableDictionary <string, List <MessageData> > >(MESSAGES);

            using (ITransaction tx = this.stateManager.CreateTransaction())
            {
                if (!await msgsDict.ContainsKeyAsync(tx, id))
                {
                    return(new NoContentResult());
                }

                var result = await msgsDict.TryGetValueAsync(tx, id);

                if (result.Value.Count <= 0)
                {
                    return(new NoContentResult());
                }

                return(this.Json(result.Value));
            }
        }
        public async Task Post(string name, string parameters)
        {
            IReliableQueue <string> queue = await this.stateManager.GetOrAddAsync <IReliableQueue <string> >("jobQueue");

            IReliableDictionary <string, Job> dictionary = await this.stateManager.GetOrAddAsync <IReliableDictionary <string, Job> >("jobs");

            using (ITransaction tx = this.stateManager.CreateTransaction())
            {
                if (await dictionary.ContainsKeyAsync(tx, name, LockMode.Update))
                {
                    throw new ArgumentException($"Job {name} already exists.");
                }

                Job job = new Job(name, parameters, false);

                await queue.EnqueueAsync(tx, name);

                await dictionary.SetAsync(tx, name, job);

                await tx.CommitAsync();
            }
        }
Exemple #22
0
        public async Task AddBookAsync(Book book)
        {
            IReliableDictionary <Guid, Book> books =
                await this.StateManager.GetOrAddAsync <IReliableDictionary <Guid, Book> >(BooksDictionaryName);

            ServiceEventSource.Current.ServiceMessage(this, message: "Received add book request. ID: {0}. Name: {1}.", args: new object[] { book.ID, book.BookName });

            using (ITransaction tx = this.StateManager.CreateTransaction())
            {
                bool exists = await books.ContainsKeyAsync(tx, book.ID);

                if (!exists)
                {
                    await books.AddAsync(tx, book.ID, book);
                }

                await tx.CommitAsync();

                ServiceEventSource.Current.ServiceMessage(
                    this, message: "Received add book request. Item: {0}. Name: {1}.", args: new object[] { book.ID, book.BookName });
            }
        }
Exemple #23
0
        private static async Task <ChaosStatus> GetCurrentStatusPrivateAsync(
            IReliableDictionary <string, byte[]> statusDictionary,
            ITransaction tx,
            CancellationToken cancellationToken)
        {
            ChaosStatus status = ChaosStatus.Stopped;

            if (await statusDictionary.ContainsKeyAsync(tx, FASConstants.ChaosStatusKeyName, FASConstants.ReliableDictionaryTimeout, cancellationToken).ConfigureAwait(false))
            {
                var conditionalStatus = await statusDictionary.TryGetValueAsync(tx, FASConstants.ChaosStatusKeyName, FASConstants.ReliableDictionaryTimeout, cancellationToken).ConfigureAwait(false);

                if (conditionalStatus.HasValue)
                {
                    status = (ChaosStatus)BitConverter.ToInt32(conditionalStatus.Value, 0);
                }
            }
            else
            {
                TestabilityTrace.TraceSource.WriteError(TraceType, "GetCurrentStatus was called, but there was no entry with key == {0}.", FASConstants.ChaosStatusKeyName);
            }

            return(status);
        }
 public async Task <bool> Contains(string key, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(await state.ContainsKeyAsync(transactionProvider.Current, key).ConfigureAwait(false));
 }
        protected override async Task RunAsync(CancellationToken runAsyncCancellationToken)
        {
            // This is to keep track of exceptions in the validation step at the end of
            // each iteration of the ChaosTestScenario that is being used under the cover
            //
            bool validationExceptionCaught = false;

            IReliableDictionary <string, CurrentState> chaosServiceState =
                await this.StateManager.GetOrAddAsync <IReliableDictionary <string, CurrentState> >(StringResource.ChaosServiceStateKey);

            using (ITransaction tx = this.StateManager.CreateTransaction())
            {
                if (!await chaosServiceState.ContainsKeyAsync(tx, StringResource.ChaosServiceStateKey, LockMode.Update))
                {
                    await chaosServiceState.AddAsync(tx, StringResource.ChaosServiceStateKey, CurrentState.Stopped);
                }
                await tx.CommitAsync();
            }


            while (!runAsyncCancellationToken.IsCancellationRequested)
            {
                try
                {
                    // check to see if we're in a "stop" or "start" state.
                    // this continues to poll until we're in a "start" state.
                    // a ReliableDictionary is used to store this information so that if the service
                    //   fails over to another node, the state is preserved and the chaos test will continue to execute.
                    using (ITransaction tx = this.StateManager.CreateTransaction())
                    {
                        ConditionalValue <CurrentState> currentStateResult =
                            await chaosServiceState.TryGetValueAsync(tx, StringResource.ChaosServiceStateKey);

                        if (currentStateResult.HasValue &&
                            (currentStateResult.Value == CurrentState.Stopped ||
                             currentStateResult.Value == CurrentState.None))
                        {
                            await Task.Delay(Constants.IntervalBetweenLoopIteration, runAsyncCancellationToken);

                            continue;
                        }
                    }

                    // this section runs the actual chaos test.
                    // the cancellation token source is linked to the token provided to RunAsync so that we
                    //   can stop the test if the service needs to shut down.
                    using (FabricClient fabricClient = new FabricClient())
                    {
                        using (this.stopEventTokenSource = CancellationTokenSource.CreateLinkedTokenSource(runAsyncCancellationToken))
                        {
                            // when a validation exception is caught, this waits for a while to let the cluster stabilize before continuing.
                            if (validationExceptionCaught)
                            {
                                await Task.Delay(ChaosTestConfigSettings.MaxClusterStabilizationTimeout, this.stopEventTokenSource.Token);

                                validationExceptionCaught = false;
                            }

                            ChaosTestScenarioParameters chaosScenarioParameters =
                                new ChaosTestScenarioParameters(
                                    ChaosTestConfigSettings.MaxClusterStabilizationTimeout,
                                    ChaosTestConfigSettings.MaxConcurrentFaults,
                                    ChaosTestConfigSettings.EnableMoveReplicaFaults,
                                    TimeSpan.MaxValue)
                            {
                                WaitTimeBetweenFaults =
                                    ChaosTestConfigSettings.WaitTimeBetweenFaults,
                                WaitTimeBetweenIterations =
                                    ChaosTestConfigSettings.WaitTimeBetweenIterations
                            };

                            ChaosTestScenario chaosTestScenario = new ChaosTestScenario(fabricClient, chaosScenarioParameters);

                            // capture progress events so we can report them back
                            chaosTestScenario.ProgressChanged += this.TestScenarioProgressChanged;

                            // this continuously runs the chaos test until the CancellationToken is signaled.
                            await chaosTestScenario.ExecuteAsync(this.stopEventTokenSource.Token);
                        }
                    }
                }
                catch (TimeoutException e)
                {
                    string message = $"Caught TimeoutException '{e.Message}'. Will wait for cluster to stabilize before continuing test";
                    ServiceEventSource.Current.ServiceMessage(this, message);
                    validationExceptionCaught = true;
                    await this.StoreEventAsync(message);
                }
                catch (FabricValidationException e)
                {
                    string message = $"Caught FabricValidationException '{e.Message}'. Will wait for cluster to stabilize before continuing test";
                    ServiceEventSource.Current.ServiceMessage(this, message);
                    validationExceptionCaught = true;
                    await this.StoreEventAsync(message);
                }
                catch (OperationCanceledException)
                {
                    if (runAsyncCancellationToken.IsCancellationRequested)
                    {
                        // if RunAsync is canceled then we need to quit.
                        throw;
                    }

                    ServiceEventSource.Current.ServiceMessage(
                        this,
                        "Caught OperationCanceledException Exception during test execution. This is expected if test was stopped");
                }
                catch (AggregateException e)
                {
                    if (e.InnerException is OperationCanceledException)
                    {
                        if (runAsyncCancellationToken.IsCancellationRequested)
                        {
                            // if RunAsync is canceled then we need to quit.
                            throw;
                        }

                        ServiceEventSource.Current.ServiceMessage(
                            this,
                            "Caught OperationCanceledException Exception during test execution. This is expected if test was stopped");
                    }
                    else
                    {
                        string message = $"Caught unexpected Exception during test excecution {e.InnerException}";
                        ServiceEventSource.Current.ServiceMessage(this, message);
                        await this.StoreEventAsync(message);
                    }
                }
                catch (Exception e)
                {
                    string message = $"Caught unexpected Exception during test excecution {e}";
                    ServiceEventSource.Current.ServiceMessage(this, message);
                    await this.StoreEventAsync(message);
                }
            }
        }
Exemple #26
0
        public async Task <IActionResult> UpdateGame(string roomid, string playerid, string playerdata)
        {
            try
            {
                if (!RoomManager.IsActive)
                {
                    return new ContentResult {
                               StatusCode = 500, Content = "Service is still starting up. Please retry."
                    }
                }
                ;

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

                IReliableDictionary <string, Room> roomdict =
                    await this.stateManager.GetOrAddAsync <IReliableDictionary <string, Room> >(RoomDictionaryName);

                using (ITransaction tx = this.stateManager.CreateTransaction())
                {
                    //Make sure the room exists
                    if (!await roomdict.ContainsKeyAsync(tx, roomid))
                    {
                        await tx.CommitAsync();

                        return(new ContentResult {
                            StatusCode = 400, Content = "This room does not exist"
                        });
                    }


                    IReliableDictionary <string, ActivePlayer> activeroomdict =
                        await this.stateManager.GetOrAddAsync <IReliableDictionary <string, ActivePlayer> >(roomid);

                    //Check that the player exists, take update lcok because we will write to this key
                    ConditionalValue <ActivePlayer> playerOption = await activeroomdict.TryGetValueAsync(tx, playerid, LockMode.Update);

                    if (!playerOption.HasValue)
                    {
                        await tx.CommitAsync();

                        return(new ContentResult {
                            StatusCode = 400, Content = "This player is not in this room"
                        });
                    }

                    //Generate the new player package and update it
                    ActivePlayer newPlayerPackage = playerOption.Value;
                    newPlayerPackage.Player      = newPlayerData;
                    newPlayerPackage.LastUpdated = DateTime.UtcNow;

                    await activeroomdict.SetAsync(tx, playerid, newPlayerPackage);

                    await tx.CommitAsync();
                }

                return(new ContentResult {
                    StatusCode = 200, Content = "Game successfully updated"
                });
            }
            catch (Exception e)
            {
                return(exceptionHandler(e));
            }
        }
Exemple #27
0
 public Task <bool> ContainsAsync(ITransaction tx, TKey key, LockMode lockMode = LockMode.Default, TimeSpan timeout = default(TimeSpan), CancellationToken cancellationToken = default(CancellationToken))
 => m_dictionary.ContainsKeyAsync(tx, key, lockMode, timeout.DefaultToInfinite(), cancellationToken);