Esempio n. 1
0
        private Activity RequestToEndOfConversationActivity(CrunchRequest skillRequest)
        {
            var activity = Activity.CreateEndOfConversationActivity() as Activity;

            activity = SetGeneralActivityProperties(activity, skillRequest);
            return(activity);
        }
Esempio n. 2
0
        private static CrunchResponse FindOneToManyWithVariance(List <CrunchItem <Transaction> > bankItems, List <CrunchItem <Transaction> > glItems)
        {
            CrunchRequest <Transaction> request = new CrunchRequest <Transaction>();

            request.One    = glItems.ToArray();
            request.Two    = bankItems.ToArray();
            request.Filter = new Filter()
            {
                Expression = @"$1.AccountIdentification == $2.AccountIdentification AND $1.TransactionValueDate == $2.TransactionValueDate AND 
                $1.TransactionType == $2.TransactionType AND $1.AccountServingInstitution == $2.AccountServingInstitution"
            };
            request.Crunch = new Core.Entities.Crunch()
            {
                Type = "1ToMany", Direction = "$1To$2", FieldName = "Amount", CreateVariance = true, VarianceOperator = "<", VarianceValue = 20M
            };
            request.FieldTypes = typeof(Transaction).GetProperties()
                                 .SelectMany(p => p.GetCustomAttributes(typeof(JsonPropertyAttribute), false).Cast <JsonPropertyAttribute>())
                                 .ToDictionary(p => p.PropertyName, p => p.PropertyName == "Amount" ? "Decimal" : "String");

            CrunchResponse response = Task.Run(async() =>
            {
                ApiClient api = new ApiClient();

                return(await api.SendAsync <CrunchRequest <Transaction>, CrunchResponse>(request, "/api/1.0/crunch/run"));
            }).GetAwaiter().GetResult();

            return(response);
        }
Esempio n. 3
0
        /// <summary>
        /// Returns an Activity object created by using properties on a SkillRequest.
        /// A base set of properties based on the SkillRequest are applied to a new Activity object
        /// for all request types with the activity type, and additional properties, set depending
        /// on the specific request type.
        /// </summary>
        /// <param name="userRequest">The SkillRequest to be used to create an Activity object.</param>
        /// <returns>Activity</returns>
        public Activity RequestToActivity(CrunchRequest userRequest)
        {
            if (userRequest.Request == null)
            {
                throw new ValidationException("Bad Request. User request missing Request property.");
            }

            switch (userRequest.Request)
            {
            case string intentRequest:
                if (intentRequest != null)
                {
                    return(RequestToMessageActivity(userRequest, intentRequest));
                }
                else
                {
                    if (intentRequest == "AMAZON.StopIntent")
                    {
                        return(RequestToEndOfConversationActivity(userRequest));
                    }

                    return(RequestToEventActivity(userRequest));
                }

            default:
                return(RequestToEventActivity(userRequest));
            }
        }
Esempio n. 4
0
        private Activity RequestToMessageActivity(CrunchRequest skillRequest, string intentRequest)
        {
            var activity = Activity.CreateMessageActivity() as Activity;

            activity      = SetGeneralActivityProperties(activity, skillRequest);
            activity.Text = intentRequest;
            return(activity);
        }
Esempio n. 5
0
        private Activity RequestToConversationUpdateActivity(CrunchRequest skillRequest)
        {
            var activity = Activity.CreateConversationUpdateActivity() as Activity;

            activity = SetGeneralActivityProperties(activity, skillRequest);
            activity.MembersAdded.Add(new ChannelAccount(id: skillRequest.Session));
            return(activity);
        }
Esempio n. 6
0
        private async Task <CrunchResponse> ProcessUserRequestAsync(CrunchRequest userRequest, BotCallbackHandler logic)
        {
            var activity = RequestToActivity(userRequest);
            var context  = new TurnContextEx(this, activity);

            await RunPipelineAsync(context, logic, default).ConfigureAwait(false);

            var activities = context.SentActivities;

            var outgoingActivity = ProcessOutgoingActivities(activities);

            var response = _requestMapper.ActivityToResponse(outgoingActivity, userRequest);

            return(response);
        }
Esempio n. 7
0
        /// <summary>
        /// Set the general properties, based on an incoming SkillRequest that can be applied
        /// irresepective of the resulting Activity type.
        /// </summary>
        /// <param name="activity">The Activity on which to set the properties on.</param>
        /// <param name="skillRequest">The incoming SkillRequest</param>
        /// <returns>Activity</returns>
        private Activity SetGeneralActivityProperties(Activity activity, CrunchRequest skillRequest)
        {
            var alexaSystem = skillRequest.Context;

            activity.ChannelId    = _options.ChannelId;
            activity.Id           = skillRequest.Request;
            activity.DeliveryMode = DeliveryModes.ExpectReplies;
            activity.ServiceUrl   = _options.ServiceUrl ?? $"{alexaSystem}?token={alexaSystem}";
            activity.Recipient    = new ChannelAccount(alexaSystem);
            activity.From         = new ChannelAccount(alexaSystem ?? alexaSystem);
            activity.Conversation = new ConversationAccount(isGroup: false, id: skillRequest.Session ?? skillRequest.Request);
            activity.Timestamp    = null;
            activity.ChannelData  = skillRequest;
            activity.Locale       = skillRequest.Language;

            return(activity);
        }
        /// <summary>
        /// Authorize the SkillRequest is coming from Alexa.
        /// </summary>
        /// <param name="skillRequest">Incoming SkillRequest from Alexa.</param>
        /// <param name="requestBody">Full request body from Alexa.</param>
        /// <param name="signatureChainUrl">Signature Chain Url. This is the SignatureCertChainUrl header value.</param>
        /// <param name="signature">Signature. This is the Signature header value.</param>
        /// <returns>True if this is a valid SkillRequest otherwise false.</returns>
        public virtual async Task <bool> ValidateSkillRequest(CrunchRequest skillRequest, string requestBody, string signatureChainUrl, string signature)
        {
            if (skillRequest == null)
            {
                _logger.LogError("Validation failed. No incoming skill request.");
                return(false);
            }

            if (string.IsNullOrWhiteSpace(signatureChainUrl))
            {
                _logger.LogError("Validation failed. Empty SignatureCertChainUrl header.");
                return(false);
            }

            Uri certUrl;

            try
            {
                certUrl = new Uri(signatureChainUrl);
            }
            catch
            {
                _logger.LogError($"Validation failed. SignatureChainUrl not valid: {signatureChainUrl}.");
                return(false);
            }

            if (string.IsNullOrWhiteSpace(signature))
            {
                _logger.LogError("Validation failed. Empty Signature header.");
                return(false);
            }

            if (!RequestVerification.RequestTimestampWithinTolerance(skillRequest))
            {
                _logger.LogError("Validation failed. Request timestamp outside of tolerance.");
                return(false);
            }
            if (!await RequestVerification.Verify(signature, certUrl, requestBody))
            {
                _logger.LogError("Validation failed. Alexa certificate validation failed.");
                return(false);
            }

            return(true);
        }
Esempio n. 9
0
        private Activity RequestToEventActivity(CrunchRequest skillRequest)
        {
            var activity = Activity.CreateEventActivity() as Activity;

            activity      = SetGeneralActivityProperties(activity, skillRequest);
            activity.Name = skillRequest.Request;

            switch (skillRequest.Request)
            {
            case string skillIntentRequest:
                activity.Value = skillIntentRequest;
                break;

            default:
                activity.Value = skillRequest.Request;
                break;
            }

            return(activity);
        }
Esempio n. 10
0
        private static CrunchResponse RunTemplate(List <CrunchItem <Transaction> > bankItems, List <CrunchItem <Transaction> > glItems)
        {
            CrunchRequest <Transaction> request = new CrunchRequest <Transaction>();

            request.One = glItems.ToArray();
            request.Two = bankItems.ToArray();

            // In case you want to run a template with multiple rules set the TemplateId property to the Id of the template.
            // Otherwise if you run a single rule set the RuleId property. You can either have the TemplateId or the RuleId set at any given time not both.
            request.TemplateId = 2;

            CrunchResponse response = Task.Run(async() =>
            {
                ApiClient api = new ApiClient();

                return(await api.SendAsync <CrunchRequest <Transaction>, CrunchResponse>(request, "/api/1.0/crunch/run"));
            }).GetAwaiter().GetResult();

            return(response);
        }
Esempio n. 11
0
        private static FilterResponse <MobilePhone> RunTemplate(List <CrunchItem <MobilePhone> > phoneItems)
        {
            CrunchRequest <MobilePhone> request = new CrunchRequest <MobilePhone>();

            request.One = phoneItems.ToArray();

            // In case you want to run a template with multiple rules set the TemplateId property to the Id of the template.
            // Otherwise if you run a single rule set the RuleId property. You can either have the TemplateId or the RuleId set at any given time not both.
            request.TemplateId = 1;
            // request.RuleId = 4;

            FilterResponse <MobilePhone> response = Task.Run(async() =>
            {
                ApiClient api = new ApiClient();

                return(await api.SendAsync <CrunchRequest <MobilePhone>, FilterResponse <MobilePhone> >(request, "/api/1.0/crunch/run"));
            }).GetAwaiter().GetResult();

            return(response);
        }
Esempio n. 12
0
        private static FilterResponse <MobilePhone> FindBestHardwareAndCameraPhones(List <CrunchItem <MobilePhone> > phoneItems)
        {
            CrunchRequest <MobilePhone> request = new CrunchRequest <MobilePhone>();

            request.One    = phoneItems.ToArray();
            request.Filter = new Filter()
            {
                Expression = "$1.status != \"Discontinued\" AND ISBLANK($1.internal_memory_mb) == FALSE AND ISBLANK($1.primary_camera_mp) == FALSE AND TONUMBER($1.internal_memory_mb) >= 8192 AND TONUMBER($1.primary_camera_mp) >= 8"
            };
            request.FieldTypes = typeof(MobilePhone).GetProperties()
                                 .SelectMany(p => p.GetCustomAttributes(typeof(JsonPropertyAttribute), false).Cast <JsonPropertyAttribute>())
                                 .ToDictionary(p => p.PropertyName, p => "String");

            FilterResponse <MobilePhone> response = Task.Run(async() =>
            {
                ApiClient api = new ApiClient();

                return(await api.SendAsync <CrunchRequest <MobilePhone>, FilterResponse <MobilePhone> >(request, "/api/1.0/crunch/run"));
            }).GetAwaiter().GetResult();

            return(response);
        }
Esempio n. 13
0
        private static FilterResponse <MobilePhone> FindDualSimPhones(List <CrunchItem <MobilePhone> > phoneItems)
        {
            CrunchRequest <MobilePhone> request = new CrunchRequest <MobilePhone>();

            request.One    = phoneItems.ToArray();
            request.Filter = new Filter()
            {
                Expression = "$1.status != \"Discontinued\" AND FIND(\"Dual SIM\", $1.sim) >= 1 AND $1.card_slot != \"No\""
            };
            request.FieldTypes = typeof(MobilePhone).GetProperties()
                                 .SelectMany(p => p.GetCustomAttributes(typeof(JsonPropertyAttribute), false).Cast <JsonPropertyAttribute>())
                                 .ToDictionary(p => p.PropertyName, p => "String");

            FilterResponse <MobilePhone> response = Task.Run(async() =>
            {
                ApiClient api = new ApiClient();

                return(await api.SendAsync <CrunchRequest <MobilePhone>, FilterResponse <MobilePhone> >(request, "/api/1.0/crunch/run"));
            }).GetAwaiter().GetResult();

            return(response);
        }
Esempio n. 14
0
        private static FilterResponse <MobilePhone> FindMostDurableBatteryPhones(List <CrunchItem <MobilePhone> > phoneItems)
        {
            CrunchRequest <MobilePhone> request = new CrunchRequest <MobilePhone>();

            request.One    = phoneItems.ToArray();
            request.Filter = new Filter()
            {
                Expression = "$1.status != \"Discontinued\" AND ISBLANK($1.stand_by_hours) == FALSE AND ISBLANK($1.talk_time_hours) == FALSE " +
                             "AND TONUMBER($1.stand_by_hours) >= 400 AND TONUMBER($1.talk_time_hours) >= 10"
            };
            request.FieldTypes = typeof(MobilePhone).GetProperties()
                                 .SelectMany(p => p.GetCustomAttributes(typeof(JsonPropertyAttribute), false).Cast <JsonPropertyAttribute>())
                                 .ToDictionary(p => p.PropertyName, p => "String");

            FilterResponse <MobilePhone> response = Task.Run(async() =>
            {
                ApiClient api = new ApiClient();

                return(await api.SendAsync <CrunchRequest <MobilePhone>, FilterResponse <MobilePhone> >(request, "/api/1.0/crunch/run"));
            }).GetAwaiter().GetResult();

            return(response);
        }
Esempio n. 15
0
        private static async Task <string> ProcessUserRequest(string userRequest, string language = "en")
        {
            if (language != "en")
            {
                language = "nl";
            }
            var request = new CrunchRequest()
            {
                Context  = "none",
                Request  = userRequest,
                Session  = "abc123",
                Version  = "1.0",
                Language = language
            };
            var content     = System.Text.Json.JsonSerializer.Serialize <CrunchRequest>(request);
            var httpContent = new StringContent(content, Encoding.UTF8, "application/json");
            var httpRequest = new HttpRequestMessage
            {
                Content = httpContent,
                Method  = HttpMethod.Post
            };

            httpRequest.Headers.Add("Authorization", "none");
            var response = await client.PostAsync(endPoint, httpContent);

            var responseContent = await response.Content.ReadAsStringAsync();

            var musicMasterResponse = JsonConvert.DeserializeObject <CrunchResponse>(responseContent, JsonSerializerSettings);

            try {
                return(musicMasterResponse.Response.Reprompt.OutputSpeech.Text);
            } catch (Exception e) {
                Console.WriteLine(e);
                return("");
            }
        }
Esempio n. 16
0
 public static bool ValidateRequest(HttpRequest request, CrunchRequest skillRequest, string body, string alexaSkillId, ILogger logger)
 {
     return(true);
 }
Esempio n. 17
0
 public static bool IsSupported(CrunchRequest request)
 {
     return(!string.IsNullOrWhiteSpace(request?.Request) &&
            !string.IsNullOrWhiteSpace(request.Context));
 }
Esempio n. 18
0
 public ProgressiveResponse(CrunchRequest request) : this(request, new HttpClient())
 {
 }
Esempio n. 19
0
 public ProgressiveResponse(CrunchRequest request, HttpClient client) : this(
         request?.Request,
         request?.Context,
         request?.Context, client)
 {
 }
Esempio n. 20
0
 public virtual Activity RequestToActivity(CrunchRequest request)
 {
     return(_requestMapper.RequestToActivity(request));
 }
 /// <summary>
 /// Verify the skill request is for the skill with the specified skill id.
 /// </summary>
 /// <param name="skillRequest">Incoming SkillRequest from Alexa.</param>
 /// <param name="alexaSkillId">Alexa Skill Id.</param>
 /// <returns>True if the SkillRequest is for this skill.</returns>
 public virtual bool ValidateSkillId(CrunchRequest skillRequest, string alexaSkillId)
 {
     return(true);
 }
Esempio n. 22
0
        /// <summary>
        /// Creates a SkillResponse based on an Activity and original SkillRequest.
        /// </summary>
        /// <param name="mergedActivityResult">The Merged Activity Result to use to create the SkillResponse</param>
        /// <param name="alexaRequest">Original SkillRequest received from Alexa Skills service. This is used
        /// to check if the original request was a SessionEndedRequest which should not return a response.</param>
        /// <returns>SkillResponse</returns>
        public CrunchResponse ActivityToResponse(MergedActivityResult mergedActivityResult, CrunchRequest alexaRequest)
        {
            var response = new CrunchResponse()
            {
                Version  = "1.0",
                Response = new ResponseBody()
            };

            var activity = mergedActivityResult?.MergedActivity;

            if (activity == null || activity.Type != ActivityTypes.Message)
            {
                response.Response.ShouldEndSession = true;
                response.Response.OutputSpeech     = new PlainTextOutputSpeech
                {
                    Text = string.Empty
                };
                return(response);
            }

            if (!string.IsNullOrEmpty(activity.Speak))
            {
                response.Response.OutputSpeech = new SsmlOutputSpeech(activity.Speak);
            }
            else
            {
                response.Response.OutputSpeech = new PlainTextOutputSpeech(activity.Text);
            }

            ProcessActivityAttachments(activity, response);

            if (ShouldSetEndSession(response))
            {
                // If end of conversation was flagged use that, othwerwise look at the InputHint.
                if (mergedActivityResult.EndOfConversationFlagged)
                {
                    response.Response.ShouldEndSession = true;
                }
                else
                {
                    switch (activity.InputHint)
                    {
                    case InputHints.IgnoringInput:
                        response.Response.ShouldEndSession = true;
                        break;

                    case InputHints.ExpectingInput:
                        response.Response.ShouldEndSession = false;
                        response.Response.Reprompt         = new Reprompt(activity.Text);
                        break;

                    default:
                        response.Response.ShouldEndSession = _options.ShouldEndSessionByDefault;
                        break;
                    }
                }
            }

            return(response);
        }