示例#1
0
        private async Task <DecisionResponse> ResolveVariationDmn(DecisionRequest decisionRequest)
        {
            using (var httpClient = _httpClientFactory.CreateClient())
            {
                httpClient.AddDefaultJsonHeaders();
                var dataAsString   = JsonConvert.SerializeObject(decisionRequest);
                var requestContent = new StringContent(dataAsString, Encoding.UTF8, "application/json");
                requestContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                try
                {
                    using (HttpResponseMessage response = await httpClient.PostAsync(_apiEndPoints.GetServiceUrl("decision") + "decisions?x-asee-auth=true", requestContent))
                    {
                        var res = await response.Content.ReadAsStringAsync();

                        if (res.Equals(""))
                        {
                            throw new Exception("Could not resolve DMN variations table");
                        }
                        var decisionResponse = (DecisionResponse)CaseUtil.ConvertFromJsonToObject(res, typeof(DecisionResponse));
                        return(decisionResponse);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Decision endpoint: " + _apiEndPoints.GetServiceUrl("decision") + "decisions");
                    Console.WriteLine("Request content: " + dataAsString);
                    throw e;
                }
            }
        }
示例#2
0
        public void DoUpdateInfo(DecisionRequest decisionRequest)// long playerId, databaseCache genericGameCache, CacheTracker cacheTracker, RequestedInfoKey updateKey)
        {
            this.decisionRequest = decisionRequest;

            try
            {
                //Can set the random seed value here for all providers if necessary
                if (aiRandomControl.InfoProviderRandomPerHandSeedEnabled)
                {
                    //var handDetails = decisionRequest.Cache.getCurrentHandDetails();
                    //var holeCards = decisionRequest.Cache.getPlayerHoleCards(decisionRequest.PlayerId);

                    var hashFunc = new Func <long, long>((long key) =>
                    {
                        key = (~key) + (key << 21);            // key = (key << 21) - key - 1;
                        key = key ^ (key >> 24);
                        key = (key + (key << 3)) + (key << 8); // key * 265
                        key = key ^ (key >> 14);
                        key = (key + (key << 2)) + (key << 4); // key * 21
                        key = key ^ (key >> 28);
                        key = key + (key << 31);
                        return(key);
                    });

                    //long randomSeed = hashFunc(
                    //        hashFunc(991 + providerInitialisationSequenceNum) ^
                    //        hashFunc(decisionRequest.Cache.getNumHandsPlayed()) ^
                    //        hashFunc((decisionRequest.Cache.getActivePositions().Length - decisionRequest.Cache.getActivePositionsLeftToAct().Length + 1)) ^
                    //        hashFunc(handDetails.dealerPosition + 1) ^
                    //        hashFunc((long)(100 *handDetails.potValue)) ^
                    //        hashFunc((1L << holeCards.holeCard1) + (1L << holeCards.holeCard2) + (1L << handDetails.tableCard1) +
                    //            (1L << handDetails.tableCard2) + (1L << handDetails.tableCard3) + (1L << handDetails.tableCard4) +
                    //            (1L << handDetails.tableCard5)));

                    //(randomGen as CMWCRandom).ReSeed(randomSeed);

                    (randomGen as CMWCRandom).ReSeed((long)(hashFunc(991 + providerInitialisationSequenceNum) ^ hashFunc(decisionRequest.Cache.TableRandomNumber) ^ decisionRequest.Cache.CurrentHandRandomNumber() ^ hashFunc(1 + decisionRequest.Cache.getCurrentHandSeqIndex())));
                }

                updateInfo();
            }
            catch (Exception ex)
            {
                string fileName = LogError.Log(ex, "InfoProviderError");
                decisionRequest.Cache.SaveToDisk("", fileName);

                //If we are running in safe mode then we return defaults
                //If not we re throw the error
                if (decisionRequest.AIManagerInSafeMode)
                {
                    SetAllProvidedTypesToDefault((from current in providedInfoTypes select current.InformationType).ToList());
                }
                else
                {
                    throw;
                }
            }
        }
示例#3
0
文件: Form1.cs 项目: madddmax/jackal
        private DecisionAnswer ProcessDecision(DecisionRequest decisionRequest)
        {
            var decisionAnswer = new DecisionAnswer();

            decisionAnswer.RequestId = decisionRequest.RequestId;
            var gameState = decisionRequest.GetGameState();

            decisionAnswer.Decision = player.OnMove(gameState);
            return(decisionAnswer);
        }
示例#4
0
 public DialogViewModel(IEventAggregator eventAggregator, DecisionRequest confirmationRequest)
     : this(
         eventAggregator,
         confirmationRequest.TaskId,
         confirmationRequest.Title,
         confirmationRequest.DialogText,
         true,   // for a decision, always send a confirmation to get to know the decision ... ;)
         true
         )
 {
 }
示例#5
0
        private async Task SaveTokenProvisioning(DecisionRequest model, int statusCode, int delay, DecisionResponse response)
        {
            var entity = new TokenProvisioningEntity
            {
                SharedSecret = GetSharedSecretFromHeaders(),
                StatusCode   = statusCode,
                DelayMls     = delay,
                RequestJson  = model.ToJson(),
                ResponseJson = response.ToJson()
            };

            await _tokenProvisioningStorage
            .Insert(model.AcctId, entity, CancellationToken.None);
        }
示例#6
0
        public int OnMove(GameState gameState)
        {
            DecisionRequest request = new DecisionRequest(gameState);

            request.RequestId = Guid.NewGuid();

            DecisionAnswer answer = _client.Query(request) as DecisionAnswer;

            if (answer.RequestId != request.RequestId)
            {
                throw new Exception("Wrong requestid");
            }
            return(answer.Decision);
        }
示例#7
0
        public async Task <DecisionResponse> GetResponse(DecisionRequest request)
        {
            var json = JsonConvert.SerializeObject(request);

            using (var stringContent = new StringContent(json, Encoding.UTF8, "application/json"))
            {
                HttpResponseMessage response = await httpClient.PostAsync($"{DecisionApiUrl}/v2/{environmentId}/campaigns?exposeAllKeys=true", stringContent);

                response.EnsureSuccessStatusCode();

                string responseBody = await response.Content.ReadAsStringAsync();

                return(JsonConvert.DeserializeObject <DecisionResponse>(responseBody));
            }
        }
示例#8
0
            public override int OnMove(GameState gameState)
            {
                DecisionRequest request = new DecisionRequest(gameState);

                request.RequestId = Guid.NewGuid();

                var    gameState2 = request.GetGameState();
                string json       = JsonHelper.SerialiazeWithType(gameState, Formatting.Indented);
                string json2      = JsonHelper.SerialiazeWithType(gameState2, Formatting.Indented);

                Assert.IsTrue(json == json2);

                CheckSerialization(request);

                return(base.OnMove(gameState));
            }
示例#9
0
        public async Task <IActionResult> DecideAsync(DecisionRequest decision)
        {
            var request = await _context.Contacts.FirstOrDefaultAsync(o => o.ReceiverId == decision.ReceiverId && o.SenderId == decision.SenderId);

            if (request == null)
            {
                return(BadRequest());
            }
            if (decision.Approved)
            {
                request.IsApproved = true;
                _context.Contacts.Update(request);

                // Создать диалог и добавить два контакта
                ChatRoom chatRoom = new ChatRoom {
                    Name = "", RoomType = Entities.Enums.RoomType.Dialog
                };
                await _context.ChatRooms.AddAsync(chatRoom);

                await _context.SaveChangesAsync();

                var receiver = await _context.Users.FirstOrDefaultAsync(o => o.Id == decision.ReceiverId);

                var sender = await _context.Users.FirstOrDefaultAsync(o => o.Id == decision.SenderId);

                var participant1 = new Participants {
                    ChatRoomId = chatRoom.Id, UserId = receiver.Id
                };
                var participant2 = new Participants {
                    ChatRoomId = chatRoom.Id, UserId = sender.Id
                };
                await _context.Participants.AddAsync(participant1);

                await _context.Participants.AddAsync(participant2);

                await _context.SaveChangesAsync();
            }
            else
            {
                _context.Contacts.Remove(request);
            }
            await _context.SaveChangesAsync();

            return(Ok());
        }
示例#10
0
        public async Task <ActionResult <DecisionResponse> > TokenProvisioning(DecisionRequest model, CancellationToken ct)
        {
            var response = new DecisionResponse
            {
                AcctId          = model.AcctId,
                BusinessAcctId  = model.BusinessAcctId,
                Last4CardNumber = model.Last4CardNumber
            };

            var settings = await _responseSettingsStorage
                           .Get(model.BusinessAcctId, model.AcctId, ct);

            if (settings == null)
            {
                await SaveTokenProvisioning(model, 404, 0, null);

                return(NotFound());
            }

            if (!SecretsAreEqual(settings.SharedSecret))
            {
                await SaveTokenProvisioning(model, 403, 0, null);

                return(StatusCode(403, "SharedSecret in Authorization header doesn't match the one configured"));
            }

            await Task
            .Delay(settings.DelayMls, ct);

            var customResult = GetCustomResult(settings.StatusCode);

            if (customResult != null)
            {
                await SaveTokenProvisioning(model, settings.StatusCode, settings.DelayMls, null);

                return(customResult);
            }

            response.Contacts = settings.ContactsJson.DeserializeTo <List <ContactItem> >();

            await SaveTokenProvisioning(model, settings.StatusCode, settings.DelayMls, response);

            return(response);
        }
示例#11
0
        public async Task <List <InterestRateVariation> > ResolveInterestRateVariationDmn(string dmnContent, VariationDefinitionParams definitionParams, string variationDefinition = "")
        {
            var responseForDmn = await GetGenericParamsForDmn(definitionParams, variationDefinition.Replace(".dmn", "-configuration"));

            var decisionRequest = new DecisionRequest
            {
                Data           = responseForDmn ?? definitionParams,
                RuleDefinition = dmnContent
            };
            var resolvedDmn = await ResolveVariationDmn(decisionRequest);

            var variations = resolvedDmn.ToInterestRateVariations();

            if (variations != null)
            {
                foreach (InterestRateVariation interestRateVariation in variations)
                {
                    interestRateVariation.Origin = PriceVariationOrigins.Product;
                }
            }
            return(variations);
        }
示例#12
0
        public async Task <DecisionResponse> GetResponse(DecisionRequest request)
        {
            var response = new DecisionResponse()
            {
                VisitorID = request.VisitorId,
                Campaigns = new HashSet <Model.Campaign>()
            };

            if (configuration == null)
            {
                logger.Log(LogLevel.WARN, LogCode.BUCKETING_NOT_LOADED);
                return(response);
            }

            response.Panic = configuration.Panic;
            if (configuration.Panic)
            {
                logger.Log(LogLevel.WARN, LogCode.BUCKETING_PANIC_MODE_ENABLED);
                return(response);
            }

            sender.SendEvent(new EventRequest(this.environmentId, request.VisitorId, EventType.CONTEXT, request.Context)).ContinueWith((Task t) =>
            {
                logger.Log(LogLevel.DEBUG, LogCode.CONTEXT_SENT_TRACKING, new { request.Context });
            });

            foreach (var campaign in configuration.Campaigns ?? new List <Model.Bucketing.Campaign>().AsEnumerable())
            {
                foreach (var vg in campaign.VariationGroups)
                {
                    var match = vg.Targeting.TargetingGroups.Any(tg => tg.Targetings.All(t =>
                    {
                        switch (t.Key)
                        {
                        case "fs_users":
                            return(targetingMatch.Match(request.VisitorId, t.Operator, t.Value));

                        case "fs_all_users":
                            return(true);

                        default:
                            if (request.Context.ContainsKey(t.Key))
                            {
                                return(targetingMatch.Match(request.Context[t.Key], t.Operator, t.Value));
                            }
                            return(false);
                        }
                    }));

                    if (match)
                    {
                        var variation = variationAllocation.GetVariation(vg, request.VisitorId);
                        if (variation != null)
                        {
                            response.Campaigns.Add(new Model.Campaign()
                            {
                                Id        = campaign.Id,
                                Variation = new Model.Variation()
                                {
                                    Id            = variation.Id,
                                    Reference     = variation.Reference,
                                    Modifications = variation.Modifications
                                },
                                VariationGroupId = vg.Id
                            });
                        }
                    }
                }
            }
            return(response);
        }
示例#13
0
        private void HandleDeinstallationRequest(DeinstallationRequest message)
        {
            _log.Debug("Entered HandleDeinstallationRequest with Id " + Id.ToString());

            if (!TaskCanceled)
            {
                FeatureDefinitionToUninstall = message.FeatureDefinition;

                Title = message.Title;

                string mentionForce = string.Empty;

                // these settings are only required for feature deactivation, not needed for uninstall
                // in case definition has scope invalid, feature deactivation is only possible with force
                if (FeatureDefinitionToUninstall.Scope == Enums.Scope.ScopeInvalid)
                {
                    force        = true;
                    mentionForce = "\n\nfyi - As this definition has an invalid scope, feature deactivation will be done with 'force' flag enabled, no mater what is set in feature admin UI.";
                }
                else
                {
                    force = message.Force.Value;
                }
                elevatedPrivileges = message.ElevatedPrivileges.Value;

                // retrieve activated features with this feature definition in this farm
                var featuresToDeactivate = repository.GetActivatedFeatures(message.FeatureDefinition);

                if (featuresToDeactivate.Any())
                {
                    FeatureDeactivations = repository.GetAsActivatedFeatureSpecial(featuresToDeactivate);

                    var confirmRequest = new DecisionRequest(
                        Title,
                        string.Format(
                            "You requested to uninstall the feature definition\n\n{0}\n\nThere are still features activated in this farm. Count: {1} \n\n" +
                            "It is recommended to deactivate these features before uninstalling the definition. Should activated features first be deactivated?\n" +
                            "(If you click 'No', the deinstallation of feature definition will start without activating any active features based on this definition before --> not recommended.{2}",
                            message.FeatureDefinition.ToString(),
                            featuresToDeactivate.Count(),
                            mentionForce
                            ),
                        Id
                        );

                    eventAggregator.PublishOnUIThread(confirmRequest);
                }
                else
                {
                    var confirmRequest = new ConfirmationRequest(
                        Title,
                        string.Format(
                            "Uninstall of feature definition\n\n{0}\n\nThere were no activated features found in this farm.\n\n",
                            message.FeatureDefinition.ToString()
                            ),
                        Id
                        );

                    eventAggregator.PublishOnUIThread(confirmRequest);
                }
            }
        }
示例#14
0
        public void Handle(DecisionRequest message)
        {
            DialogViewModel dialogVm = new DialogViewModel(eventAggregator, message);

            this.windowManager.ShowDialog(dialogVm, null, GetDialogSettings());
        }