Exemplo n.º 1
0
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            using (var connector = new ConnectorClient(new Uri(activity.ServiceUrl)))
            {
                if (activity.IsComposeExtensionQuery())
                {
                    var response = MessageExtension.HandleMessageExtensionQuery(connector, activity);
                    return(response != null
                        ? Request.CreateResponse <ComposeExtensionResponse>(response)
                        : new HttpResponseMessage(HttpStatusCode.OK));
                }
                else if (activity.GetTextWithoutMentions().ToLower().Trim() == "score")
                {
                    await connector.Conversations.ReplyToActivityWithRetriesAsync(activity.CreateReply(tracker.GetScore().ToString()));

                    return(new HttpResponseMessage(HttpStatusCode.Accepted));
                }
                else
                {
                    //if (tracker.GetScore() < 0.4) await EchoBot.SendMessage(connector, activity, "Cheer up buddy!");
                    await EchoBot.EchoMessage(connector, activity, tracker.GetScore(), tracker);

                    return(new HttpResponseMessage(HttpStatusCode.OK));
                }
            }
        }
Exemplo n.º 2
0
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            using (var connector = new ConnectorClient(new Uri(activity.ServiceUrl)))
            {
                if (activity != null && activity.GetActivityType() == ActivityTypes.Message)
                {
                    await Conversation.SendAsync(activity, () => new EchoBot());
                }
                else if (activity.Type == ActivityTypes.Invoke)
                {
                    if (activity.IsComposeExtensionQuery())
                    {
                        var response = MessageExtension.HandleMessageExtensionQuery(connector, activity);
                        return(response != null
                            ? Request.CreateResponse <ComposeExtensionResponse>(response)
                            : new HttpResponseMessage(HttpStatusCode.OK));
                    }
                    else if (activity.IsO365ConnectorCardActionQuery())
                    {
                        //CreateDataRecords();
                        return(await HandleO365ConnectorCardActionQuery(activity));
                    }
                }
                else
                {
                    HandleSystemMessage(activity);
                }

                return(new HttpResponseMessage(HttpStatusCode.Accepted));
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <typeparam name="T">消息类型</typeparam>
        /// <param name="hubConnectionBuilder">Hub连接建造者</param>
        /// <param name="message">消息</param>
        public static async Task SendAsync <T>(HubConnectionBuilder hubConnectionBuilder, T message) where T : IMessage
        {
            #region # 验证

            if (!hubConnectionBuilder.HubConnectionBuilt)
            {
                throw new InvalidOperationException("Hub连接未构建,不可发送消息!");
            }

            #endregion

            string hubName = MessageExtension.GetHubName <T>();

            #region # 验证

            if (!hubConnectionBuilder.SenderProxies.ContainsKey(hubName))
            {
                throw new InvalidOperationException($"要发送的消息类型\"{typeof(T).Name}\"未注册!");
            }

            #endregion

            IHubProxy proxy = hubConnectionBuilder.SenderProxies[hubName];
            await proxy.Invoke(CommonConstants.ExchangeMethodName, message);

            //消息已发送事件
            OnMessageSent?.Invoke(message);
        }
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            using (var connector = new ConnectorClient(new Uri(activity.ServiceUrl)))
            {
                if (activity.IsComposeExtensionQuery())
                {
                    var response = MessageExtension.HandleMessageExtensionQuery(connector, activity);
                    if (response == null)
                    {
                        return(new HttpResponseMessage(HttpStatusCode.OK));
                    }
                    if (response.GetType() == typeof(ComposeExtensionResponse))
                    {
                        return(Request.CreateResponse <ComposeExtensionResponse>((ComposeExtensionResponse)response));
                    }

                    return(new HttpResponseMessage(HttpStatusCode.OK));
                }
                else
                {
                    var result = await Bot.HandleActivity(connector, activity);

                    return(result == null ?
                           new HttpResponseMessage(HttpStatusCode.OK) :
                           Request.CreateResponse(HttpStatusCode.OK, result));
                }
            }
        }
        public virtual async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            // check if activity is of type message
            if (activity != null && activity.GetActivityType() == ActivityTypes.Message)
            {
                await Conversation.SendAsync(activity, () => new RootDialog());
            }
            else if (activity.Type == ActivityTypes.Invoke) // Received an invoke
            {
                // Handle ComposeExtension query
                if (activity.IsComposeExtensionQuery())
                {
                    var response = await MessageExtension.HandleMessageExtensionQuery(activity);

                    return(response != null
                        ? Request.CreateResponse <ComposeExtensionResponse>(response)
                        : new HttpResponseMessage(HttpStatusCode.OK));
                }
                else if (activity.IsO365ConnectorCardActionQuery())
                {
                    // this will handle the request coming any action on Actionable messages
                    return(await HandleO365ConnectorCardActionQuery(activity));
                }
            }
            else
            {
                HandleSystemMessage(activity);
            }
            return(new HttpResponseMessage(System.Net.HttpStatusCode.Accepted));
        }
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            using (var connector = new ConnectorClient(new Uri(activity.ServiceUrl)))
            {
                if (activity.IsComposeExtensionQuery())
                {
                    var response = MessageExtension.HandleMessageExtensionQuery(connector, activity);
                    return(response != null
                        ? Request.CreateResponse <ComposeExtensionResponse>(response)
                        : new HttpResponseMessage(HttpStatusCode.OK));
                }
                else
                {
                    switch (activity.Type)
                    {
                    case ActivityTypes.Message:
                        await Conversation.SendAsync(activity, () => new RootDialog());

                        break;

                    case ActivityTypes.Invoke:
                        return(HandleInvokeMessages(activity));
                    }

                    return(new HttpResponseMessage(HttpStatusCode.Accepted));
                }
            }
        }
        /// <summary>
        /// 注册接收消息类型
        /// </summary>
        /// <param name="messageTypes">消息类型列表</param>
        public void RegisterMessagesToReceive(IEnumerable <Type> messageTypes)
        {
            #region # 验证

            if (this.HubConnectionBuilt)
            {
                throw new InvalidOperationException("Hub连接已构建,不可注册接收消息类型!");
            }

            #endregion

            messageTypes = messageTypes?.Distinct().ToArray() ?? new Type[0];

            foreach (Type messageType in messageTypes)
            {
                #region # 验证

                if (!typeof(IMessage).IsAssignableFrom(messageType))
                {
                    throw new InvalidOperationException($"类型\"{messageType.Name}\"未实现\"{nameof(IMessage)}\"接口!");
                }

                #endregion

                string    hubName  = MessageExtension.GetHubName(messageType);
                IHubProxy hubProxy = this.HubConnection.CreateHubProxy(hubName);

                this._receiverProxies.Add(hubName, hubProxy);
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// 接收消息
        /// </summary>
        /// <typeparam name="T">消息类型</typeparam>
        /// <param name="hubConnectionBuilder">Hub连接建造者</param>
        /// <param name="onReceive">消息接收事件</param>
        public static void Receive <T>(HubConnectionBuilder hubConnectionBuilder, Action <T> onReceive) where T : IMessage
        {
            #region # 验证

            if (!hubConnectionBuilder.HubConnectionBuilt)
            {
                throw new InvalidOperationException("Hub连接未构建,不可接收消息!");
            }

            #endregion

            string hubName = MessageExtension.GetHubName <T>();

            #region # 验证

            if (!hubConnectionBuilder.ReceiverProxies.ContainsKey(hubName))
            {
                throw new InvalidOperationException($"要接收的消息类型\"{typeof(T).Name}\"未注册!");
            }

            #endregion

            IHubProxy proxy = hubConnectionBuilder.ReceiverProxies[hubName];
            proxy.On <T>(CommonConstants.ExchangeMethodName, onReceive);
        }
Exemplo n.º 9
0
        public Form1()
        {
            var queueName = @".\private$\OneTrueError.Service.Client";

            if (!MessageQueue.Exists(queueName))
            {
                MessageQueue.Create(queueName);
            }
            InitializeComponent();
            LoadContracts();


            _inboundQueue = new MessageQueue(queueName);
            _inboundQueue.MessageReadPropertyFilter.Extension = true;
            _inboundQueue.Formatter         = new JsonMessageFormatter();
            _inboundQueue.ReceiveCompleted += OnReadCompleted;
            _inboundQueue.BeginReceive();

            var queue    = new MessageQueue(@".\private$\OneTrueError.MessageBroker");
            var innerMsg = new Subscribe {
                AssemblyNames = new string[0]
            };
            var message = new Message(innerMsg, new JsonMessageFormatter());

            message.ResponseQueue = _inboundQueue;
            var ext = new MessageExtension("Client", innerMsg, 1)
            {
                FrameMethod = "SUBSCRIBE"
            };

            message.Extension = ext.Serialize();
            queue.Send(message);
        }
        public JsonResult sendmessage([FromBody] sendmessage message, string sessionid)
        {
            try
            {
                if (!string.IsNullOrEmpty(sessionid) && message != null)
                {
                    Patient lpatient = IPatient.GetPatientBySessionID(sessionid);
                    User    luser    = lIUserRepository.getUser(message.message.UserId);
                    if (lpatient != null)
                    {
                        if (luser != null)
                        {
                            if (((message.message.UserType == ConstantsVar.PatientAdministrator && lpatient.Paid == message.message.UserId) || (message.message.UserType == ConstantsVar.Therapist && lpatient.Therapistid == message.message.UserId) || (message.message.UserType == ConstantsVar.Provider && lpatient.ProviderId == message.message.UserId) || message.message.UserType == ConstantsVar.Support))
                            {
                                DateTime mdatetime = Convert.ToDateTime(Utilities.ConverTimetoServerTimeZone(Convert.ToDateTime(message.message.Datetime), message.timezoneOffset));
                                Messages lmessage  = MessageExtension.MessageViewToMessage(message.message);
                                lmessage.PatientId = lpatient.PatientLoginId;
                                lmessage.Datetime  = mdatetime;
                                int res = lIMessageRepository.InsertMessage(lmessage);
                                if (res > 0)
                                {
                                    string content = "Patient has sent a message.<br><a href='" + ConfigVars.NewInstance.url + "?ruserid=" + Utilities.EncryptText(luser.UserId) + "&rtype=" + Utilities.EncryptText(luser.Type.ToString()) + "&rpage=" + Utilities.EncryptText("meg") + "'> Click to view</a>";
                                    Smtp.SendGridEmail(luser.Email, "Messages", content);
                                    return(Json(new { Status = (int)HttpStatusCode.OK, result = "success", MessageHeaderID = lmessage.MsgHeaderId }));
                                }
                                else
                                {
                                    return(Json(new { Status = (int)HttpStatusCode.OK, result = "not inserted" }));
                                }
                            }
                            else
                            {
                                return(Json(new { Status = (int)HttpStatusCode.Forbidden, result = "patient and user is not mapping", TimeZone = DateTime.UtcNow.ToString("s") }));
                            }
                        }
                        else
                        {
                            return(Json(new { Status = (int)HttpStatusCode.Forbidden, result = "user is not configured", TimeZone = DateTime.UtcNow.ToString("s") }));
                        }
                    }
                    else
                    {
                        return(Json(new { Status = (int)HttpStatusCode.Forbidden, result = "patient is not configured", TimeZone = DateTime.UtcNow.ToString("s") }));
                    }
                }
                else
                {
                    return(Json(new { Status = (int)HttpStatusCode.Forbidden, result = "input is not valid", TimeZone = DateTime.UtcNow.ToString("s") }));
                }
            }
            catch (Exception ex)
            {
                logger.LogDebug("Get Rx Error: " + ex);

                return(Json(new { Status = (int)HttpStatusCode.InternalServerError, result = "getting messages failed" }));
            }
        }
Exemplo n.º 11
0
        public async Task EditSay(CommandContext ctx, [Description("Mensagem que eu editarei")] string message, [Description("Mensagem para eu falar.")][RemainingText] string texto)
        {
            MessageExtension msgex = new MessageExtension(ctx, message);

            if (!msgex.Success || msgex.Message.Author.Id != ctx.Client.CurrentUser.Id || msgex.Message.Channel.GuildId != ctx.Guild.Id || ctx.Channel.IsPrivate ||
                texto == "" || !ctx.HasPermissions(Permissions.ManageMessages))
            {
                throw new Exception();
            }

            await new StringVariablesExtension(ctx.Member, ctx.Guild).ModifyMessage(msgex.Message, texto);
            await ctx.Message.DeleteAsync();
        }
        /// <summary>
        /// Handle an invoke activity.
        /// </summary>
        private async Task <HttpResponseMessage> HandleInvokeActivity(Activity activity)
        {
            var activityValue = activity.Value.ToString();

            switch (activity.Name)
            {
            case "signin/verifyState":
                await Conversation.SendAsync(activity, () => new RootDialog());

                break;

            case "composeExtension/query":
                // Handle fetching task module content
                using (var connector = new ConnectorClient(new Uri(activity.ServiceUrl)))
                {
                    var channelData = activity.GetChannelData <TeamsChannelData>();
                    var tid         = channelData.Tenant.Id;

                    string emailId = await RootDialog.GetUserEmailId(activity);

                    if (emailId == null)
                    {
                        return(new HttpResponseMessage(HttpStatusCode.OK));
                    }
                    var response = await MessageExtension.HandleMessageExtensionQuery(connector, activity, tid, emailId);

                    return(response != null
                            ? Request.CreateResponse(response)
                            : new HttpResponseMessage(HttpStatusCode.OK));
                }

            case "task/fetch":
                // Handle fetching task module content
                return(await HandleTaskModuleFetchRequest(activity, activityValue));

            case "task/submit":
                // Handle submission of task module info
                // Run this on a task so that
                new Task(async() =>
                {
                    var action    = JsonConvert.DeserializeObject <TaskModule.BotFrameworkCardValue <ActionDetails> >(activityValue);
                    activity.Name = action.Data.ActionType;
                    await Conversation.SendAsync(activity, () => new RootDialog());
                }).Start();

                await Task.Delay(TimeSpan.FromSeconds(2));    // Give it some time to start showing output.

                break;
            }
            return(new HttpResponseMessage(HttpStatusCode.Accepted));
        }
Exemplo n.º 13
0
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            using (var connector = new ConnectorClient(new Uri(activity.ServiceUrl)))
            {
                if (activity.IsComposeExtensionQuery())
                {
                    var response = MessageExtension.HandleMessageExtensionQuery(connector, activity);
                    return(response != null
                        ? Request.CreateResponse <ComposeExtensionResponse>(response)
                        : new HttpResponseMessage(HttpStatusCode.OK));
                }
                else
                {
                    await EchoBot.EchoMessage(connector, activity);

                    return(new HttpResponseMessage(HttpStatusCode.Accepted));
                }
            }
        }
Exemplo n.º 14
0
        public ISignal FindSignal(string key)
        {
            string rkey  = MessageExtension.GetRedisKey(_tentantType, _tentantId, key);
            var    value = MessageExtension.PersistentStore.Get(rkey);

            if (value == null)
            {
                return(null);
            }
            var signal = new RedisSignal()
            {
                TenantType = _tentantType,
                TenantId   = _tentantId,
                UId        = key,
                Value      = value
            };

            return(signal);
        }
Exemplo n.º 15
0
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            using (var connector = new ConnectorClient(new Uri(activity.ServiceUrl)))
            {
                if (activity != null && activity.GetActivityType() == ActivityTypes.Message)
                {
                    await Conversation.SendAsync(activity, () => new EchoBot());
                }
                else if (activity.Type == ActivityTypes.Invoke)
                {
                    if (activity.IsComposeExtensionQuery())
                    {
                        var response = MessageExtension.HandleMessageExtensionQuery(connector, activity);
                        return(response != null
                            ? Request.CreateResponse <ComposeExtensionResponse>(response)
                            : new HttpResponseMessage(HttpStatusCode.OK));
                    }

                    else if (activity.IsO365ConnectorCardActionQuery())
                    {
                        return(await HandleO365ConnectorCardActionQuery(activity));
                    }
                }
                else if (activity.Type == ActivityTypes.Message)
                {
                    ConnectorClient connector1 = new ConnectorClient(new Uri(activity.ServiceUrl));
                    Activity        reply      = activity.CreateReply($"You sent {activity.Text} which was {activity.Text.Length} characters.");

                    var msgToUpdate = await connector.Conversations.ReplyToActivityAsync(reply);

                    Activity updatedReply = activity.CreateReply($"This is an updated message.");
                    await connector.Conversations.UpdateActivityAsync(reply.Conversation.Id, msgToUpdate.Id, updatedReply);
                }


                return(new HttpResponseMessage(HttpStatusCode.Accepted));
            }
        }
Exemplo n.º 16
0
        public void RemoveSignal(string key)
        {
            string rkey = MessageExtension.GetRedisKey(_tentantType, _tentantId, key);

            MessageExtension.PersistentStore.Remove(rkey);
        }
Exemplo n.º 17
0
        private Transaction MapResponse(string rawResponse)
        {
            JsonDoc doc = JsonDoc.Parse(rawResponse);

            ThreeDSecure secureEcom = new ThreeDSecure();

            // check enrolled
            secureEcom.ServerTransactionId = doc.GetValue <string>("server_trans_id");
            if (doc.Has("enrolled"))
            {
                secureEcom.Enrolled = doc.GetValue <string>("enrolled");
            }
            secureEcom.IssuerAcsUrl = doc.GetValue <string>("method_url", "challenge_request_url");

            // get authentication data
            secureEcom.AcsTransactionId             = doc.GetValue <string>("acs_trans_id");
            secureEcom.DirectoryServerTransactionId = doc.GetValue <string>("ds_trans_id");
            secureEcom.AuthenticationType           = doc.GetValue <string>("authentication_type");
            secureEcom.AuthenticationValue          = doc.GetValue <string>("authentication_value");
            secureEcom.Eci                        = doc.GetValue <int>("eci");
            secureEcom.Status                     = doc.GetValue <string>("status");
            secureEcom.StatusReason               = doc.GetValue <string>("status_reason");
            secureEcom.AuthenticationSource       = doc.GetValue <string>("authentication_source");
            secureEcom.MessageCategory            = doc.GetValue <string>("message_category");
            secureEcom.MessageVersion             = doc.GetValue <string>("message_version");
            secureEcom.AcsInfoIndicator           = doc.GetArray <string>("acs_info_indicator");
            secureEcom.DecoupledResponseIndicator = doc.GetValue <string>("decoupled_response_indicator");
            secureEcom.WhitelistStatus            = doc.GetValue <string>("whitelist_status");
            secureEcom.ExemptReason               = doc.GetValue <string>("eos_reason");
            if (secureEcom.ExemptReason == ExemptReason.APPLY_EXEMPTION.ToString())
            {
                secureEcom.ExemptStatus = ExemptStatus.TRANSACTION_RISK_ANALYSIS;
            }

            // challenge mandated
            if (doc.Has("challenge_mandated"))
            {
                secureEcom.ChallengeMandated = doc.GetValue <bool>("challenge_mandated");
            }

            // initiate authentication
            secureEcom.CardHolderResponseInfo = doc.GetValue <string>("cardholder_response_info");

            // device_render_options
            if (doc.Has("device_render_options"))
            {
                JsonDoc renderOptions = doc.Get("device_render_options");
                secureEcom.SdkInterface = renderOptions.GetValue <string>("sdk_interface");
                secureEcom.SdkUiType    = renderOptions.GetArray <string>("sdk_ui_type");
            }

            // message_extension
            if (doc.Has("message_extension"))
            {
                secureEcom.MessageExtensions = new List <MessageExtension>();
                foreach (JsonDoc messageExtension in doc.GetEnumerator("message_extension"))
                {
                    MessageExtension msgExtension = new MessageExtension
                    {
                        CriticalityIndicator = messageExtension.GetValue <string>("criticality_indicator"),
                        MessageExtensionData = messageExtension.GetValue <JsonDoc>("data")?.ToString(),
                        MessageExtensionId   = messageExtension.GetValue <string>("id"),
                        MessageExtensionName = messageExtension.GetValue <string>("name")
                    };
                    secureEcom.MessageExtensions.Add(msgExtension);
                }
            }

            // versions
            secureEcom.DirectoryServerEndVersion   = doc.GetValue <string>("ds_protocol_version_end");
            secureEcom.DirectoryServerStartVersion = doc.GetValue <string>("ds_protocol_version_start");
            secureEcom.AcsEndVersion   = doc.GetValue <string>("acs_protocol_version_end");
            secureEcom.AcsStartVersion = doc.GetValue <string>("acs_protocol_version_start");

            // payer authentication request
            if (doc.Has("method_data"))
            {
                JsonDoc methodData = doc.Get("method_data");
                secureEcom.PayerAuthenticationRequest = methodData.GetValue <string>("encoded_method_data");
            }
            else if (doc.Has("encoded_creq"))
            {
                secureEcom.PayerAuthenticationRequest = doc.GetValue <string>("encoded_creq");
            }

            Transaction response = new Transaction {
                ThreeDSecure = secureEcom
            };

            return(response);
        }
Exemplo n.º 18
0
        public async Task <HttpResponseMessage> Post([FromBody] Activity activity)
        {
            using (var connector = new ConnectorClient(new Uri(activity.ServiceUrl)))
            {
                var val = activity.Value;
                if (activity.IsComposeExtensionQuery())
                {
                    var response = MessageExtension.HandleMessageExtensionQuery(connector, activity, result);
                    return(response != null
                    ? Request.CreateResponse <ComposeExtensionResponse>(response)
                    : new HttpResponseMessage(HttpStatusCode.OK));
                }
                else
                {
                    if (activity.Value != null)
                    {
                        result = await GetActivity(activity);
                    }
                    else
                    {
                        await EchoBot.EchoMessage(connector, activity);
                    }
                }
                if (activity.Type == ActivityTypes.ConversationUpdate)
                {
                    for (int i = 0; i < activity.MembersAdded.Count; i++)
                    {
                        if (activity.MembersAdded[i].Id == activity.Recipient.Id)
                        {
                            var reply = activity.CreateReply();
                            reply.Text = "Hi! I am the Event Management bot for Dev Days 2019 happening in Taiwan. Ask me questions about the event and I can help you find answers Ask me questions like \n\n" +
                                         "   *\r What is the venue? \r\n\n" +
                                         "   *\r What tracks are available? \r\n\n" +
                                         "   *\r Do we have workshops planned? \n\n".Replace("\n", Environment.NewLine);

                            await connector.Conversations.ReplyToActivityAsync(reply);

                            var channelData = activity.GetChannelData <TeamsChannelData>();
                            if (channelData.Team != null)
                            {
                                ConversationParameters param = new ConversationParameters()
                                {
                                    Members = new List <ChannelAccount>()
                                    {
                                        new ChannelAccount()
                                        {
                                            Id = activity.From.Id
                                        }
                                    },
                                    ChannelData = new TeamsChannelData()
                                    {
                                        Tenant       = channelData.Tenant,
                                        Notification = new NotificationInfo()
                                        {
                                            Alert = true
                                        }
                                    }
                                };

                                var resource = await connector.Conversations.CreateConversationAsync(param);

                                await connector.Conversations.SendToConversationAsync(resource.Id, reply);
                            }
                            break;
                        }
                    }
                }
                return(new HttpResponseMessage(HttpStatusCode.Accepted));
            }
        }
Exemplo n.º 19
0
        public static Transaction Map3DSecureData(string rawResponse)
        {
            if (!string.IsNullOrEmpty(rawResponse))
            {
                JsonDoc json = JsonDoc.Parse(rawResponse);

                var transaction = new Transaction
                {
                    ThreeDSecure = new ThreeDSecure
                    {
                        ServerTransactionId = !string.IsNullOrEmpty(json.GetValue <string>("id")) ?
                                              json.GetValue <string>("id") :
                                              json.Get("three_ds")?.GetValue <string>("server_trans_ref"),
                        MessageVersion = json.Get("three_ds")?.GetValue <string>("message_version"),
                        Version        = Parse3DSVersion(json.Get("three_ds")?.GetValue <string>("message_version")),
                        Status         = json.GetValue <string>("status"),
                        DirectoryServerStartVersion = json.Get("three_ds")?.GetValue <string>("ds_protocol_version_start"),
                        DirectoryServerEndVersion   = json.Get("three_ds")?.GetValue <string>("ds_protocol_version_end"),
                        AcsStartVersion             = json.Get("three_ds")?.GetValue <string>("acs_protocol_version_start"),
                        AcsEndVersion              = json.Get("three_ds")?.GetValue <string>("acs_protocol_version_end"),
                        Enrolled                   = json.Get("three_ds")?.GetValue <string>("enrolled_status"),
                        Eci                        = !string.IsNullOrEmpty(json.Get("three_ds")?.GetValue <string>("eci")) ? json.Get("three_ds")?.GetValue <string>("eci") : null,
                        AcsInfoIndicator           = json.Get("three_ds")?.GetArray <string>("acs_info_indicator"),
                        ChallengeMandated          = json.Get("three_ds")?.GetValue <string>("challenge_status") == "MANDATED",
                        PayerAuthenticationRequest = (!string.IsNullOrEmpty(json.Get("three_ds").GetValue <string>("acs_challenge_request_url")) && json.GetValue <string>("status") == "CHALLENGE_REQUIRED") ?
                                                     json.Get("three_ds")?.GetValue <string>("challenge_value") :
                                                     json.Get("three_ds")?.Get("method_data")?.GetValue <string>("encoded_method_data"),
                        IssuerAcsUrl = (!string.IsNullOrEmpty(json.Get("three_ds").GetValue <string>("acs_challenge_request_url")) && json.GetValue <string>("status") == "CHALLENGE_REQUIRED") ?
                                       json.Get("three_ds")?.GetValue <string>("acs_challenge_request_url") :
                                       json.Get("three_ds")?.GetValue <string>("method_url"),
                        Currency                     = json.GetValue <string>("currency"),
                        Amount                       = json.GetValue <string>("amount").ToAmount(),
                        AuthenticationValue          = json.Get("three_ds")?.GetValue <string>("authentication_value"),
                        DirectoryServerTransactionId = json.Get("three_ds")?.GetValue <string>("ds_trans_ref"),
                        AcsTransactionId             = json.Get("three_ds")?.GetValue <string>("acs_trans_ref"),
                        StatusReason                 = json.Get("three_ds")?.GetValue <string>("status_reason"),
                        MessageCategory              = json.Get("three_ds")?.GetValue <string>("message_category"),
                        MessageType                  = json.Get("three_ds")?.GetValue <string>("message_type"),
                        SessionDataFieldName         = json.Get("three_ds")?.GetValue <string>("session_data_field_name"),
                        ChallengeReturnUrl           = json.Get("notifications")?.GetValue <string>("challenge_return_url"),
                        LiabilityShift               = json.Get("three_ds")?.GetValue <string>("liability_shift"),
                        AuthenticationSource         = json.Get("three_ds")?.GetValue <string>("authentication_source"),
                        AuthenticationType           = json.Get("three_ds")?.GetValue <string>("authentication_request_type"),
                        //AcsInfoIndicator = json.Get("three_ds")?.GetArray<string>("acs_decoupled_response_indicator"),
                        WhitelistStatus   = json.Get("three_ds")?.GetValue <string>("whitelist_status"),
                        MessageExtensions = new List <MessageExtension>()
                    }
                };

                // Mobile data
                if (!string.IsNullOrEmpty(json.GetValue <string>("source")) && json.GetValue <string>("source").Equals("MOBILE_SDK"))
                {
                    if (json.Get("three_ds")?.Get("mobile_data") != null)
                    {
                        JsonDoc mobile_data = json.Get("three_ds").Get("mobile_data");

                        transaction.ThreeDSecure.PayerAuthenticationRequest = mobile_data.GetValue <string>("acs_signed_content");

                        if (mobile_data.Get("acs_rendering_type").HasKeys())
                        {
                            JsonDoc acs_rendering_type = mobile_data.Get("acs_rendering_type");
                            transaction.ThreeDSecure.AcsInterface  = acs_rendering_type.GetValue <string>("acs_interface");
                            transaction.ThreeDSecure.AcsUiTemplate = acs_rendering_type.GetValue <string>("acs_ui_template");
                        }
                    }
                }

                var messageExtensions = json.Get("three_ds")?.GetEnumerator("message_extension");

                if (messageExtensions != null)
                {
                    foreach (JsonDoc messageExtension in messageExtensions)
                    {
                        MessageExtension msgExtension = new MessageExtension
                        {
                            CriticalityIndicator = messageExtension.GetValue <string>("criticality_indicator"),
                            MessageExtensionData = messageExtension.GetValue <JsonDoc>("data")?.ToString(),
                            MessageExtensionId   = messageExtension.GetValue <string>("id"),
                            MessageExtensionName = messageExtension.GetValue <string>("name")
                        };
                        transaction.ThreeDSecure.MessageExtensions.Add(msgExtension);
                    }
                }

                return(transaction);
            }
            return(new Transaction());
        }
Exemplo n.º 20
0
        private async Task <HttpResponseMessage> HandleInvokeActivity(Activity activity)
        {
            var    activityValue = activity.Value.ToString();
            string ETid;

            Models.TaskInfo     taskInfo;
            Models.TaskEnvelope taskEnvelope;
            switch (activity.Name)
            {
            case "signin/verifyState":
                await Conversation.SendAsync(activity, () => new RootDialog());

                break;

            case "composeExtension/query":
                // Handle fetching task module content
                var connector = new ConnectorClient(new Uri(activity.ServiceUrl));
                var response  = MessageExtension.HandleMessageExtensionQuery(connector, activity);
                return(response != null?Request.CreateResponse <ComposeExtensionResponse>(response) : new HttpResponseMessage(HttpStatusCode.OK));

            case "task/fetch":
                // Handle fetching task module content
                string action = string.Empty;

                try
                {
                    var input = JsonConvert.DeserializeObject <TaskFetchData>(activityValue);
                    action = input.data.data;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    // action = JsonConvert.DeserializeObject<Models.BotFrameworkCardValue<string>>(activityValue);
                }
                taskInfo = GetTaskInfo(action);

                taskEnvelope = new Models.TaskEnvelope
                {
                    Task = new Models.Task()
                    {
                        Type     = Models.TaskType.Continue.ToString().ToLower(),
                        TaskInfo = taskInfo
                    }
                };
                return(Request.CreateResponse(HttpStatusCode.OK, taskEnvelope));

            case "task/submit":
                string taskId = JsonConvert.DeserializeObject <TaskModuleSubmitData <TicketTaskData> >(activityValue).Data.action;
                //string commandid = details.commandId;
                switch (taskId)
                {
                case "ticketcomplete":
                    var createTicketData = JsonConvert.DeserializeObject <SubmitActionData <TicketTaskData> >(activityValue).data;
                    taskInfo = GetTaskInfo(taskId);
                    var ticketurl = "?ticketNoId=" + createTicketData.ticketNo + "&description=" + createTicketData.TDescription + "&category=" + createTicketData.TCategory + "&priority=" + createTicketData.TPriority;
                    taskInfo.Url         = taskInfo.Url + ticketurl;
                    taskInfo.FallbackUrl = taskInfo.FallbackUrl + ticketurl;

                    taskEnvelope = new Models.TaskEnvelope
                    {
                        Task = new Models.Task()
                        {
                            Type     = Models.TaskType.Continue.ToString().ToLower(),
                            TaskInfo = taskInfo
                        }
                    };

                    return(Request.CreateResponse(HttpStatusCode.OK, taskEnvelope));

                case "podecline":
                    var podeclineData = JsonConvert.DeserializeObject <SubmitActionData <PODeclineData> >(activityValue).data;
                    taskInfo = GetTaskInfo(taskId);
                    var declineUrl = "?poNo=" + podeclineData.poNumber;
                    taskInfo.Url         = taskInfo.Url + declineUrl;
                    taskInfo.FallbackUrl = taskInfo.FallbackUrl + declineUrl;

                    taskEnvelope = new Models.TaskEnvelope
                    {
                        Task = new Models.Task()
                        {
                            Type     = Models.TaskType.Continue.ToString().ToLower(),
                            TaskInfo = taskInfo
                        }
                    };

                    return(Request.CreateResponse(HttpStatusCode.OK, taskEnvelope));

                case "decline":
                    var declineData = JsonConvert.DeserializeObject <SubmitActionData <DeclineData> >(activityValue).data;
                    taskId   = "declined";
                    taskInfo = GetTaskInfo(taskId);
                    var decUrl = "?poNo=" + declineData.PONo + "&reason=" + declineData.reason + "&comment=" + declineData.comments;
                    taskInfo.Url         = taskInfo.Url + decUrl;
                    taskInfo.FallbackUrl = taskInfo.FallbackUrl + decUrl;

                    taskEnvelope = new Models.TaskEnvelope
                    {
                        Task = new Models.Task()
                        {
                            Type     = Models.TaskType.Continue.ToString().ToLower(),
                            TaskInfo = taskInfo
                        }
                    };

                    return(Request.CreateResponse(HttpStatusCode.OK, taskEnvelope));

                case "editVisitorRequest":
                    taskInfo     = GetTaskInfo(taskId);
                    taskEnvelope = new Models.TaskEnvelope
                    {
                        Task = new Models.Task()
                        {
                            Type     = Models.TaskType.Continue.ToString().ToLower(),
                            TaskInfo = taskInfo
                        }
                    };
                    return(Request.CreateResponse(HttpStatusCode.OK, taskEnvelope));

                case "editTicket":

                    taskInfo     = GetTaskInfo(taskId);
                    taskEnvelope = new Models.TaskEnvelope
                    {
                        Task = new Models.Task()
                        {
                            Type     = Models.TaskType.Continue.ToString().ToLower(),
                            TaskInfo = taskInfo
                        }
                    };

                    return(Request.CreateResponse(HttpStatusCode.OK, taskEnvelope));

                case "sendrequest":
                    var savevisitordata = JsonConvert.DeserializeObject <SubmitActionData <VisitorData> >(activityValue).data;
                    taskInfo = GetTaskInfo(taskId);
                    var vurl = "?Date=" + savevisitordata.Vdate + "&Time=" + savevisitordata.Vtime + "&Contact=" + savevisitordata.Vcontact + "&location=" + savevisitordata.VhostLocation + "&purpose=" + savevisitordata.Vpurpose + "&hostName=" + savevisitordata.VhostName + "&org=" + savevisitordata.Vorg;
                    taskInfo.Url         = taskInfo.Url + vurl;
                    taskInfo.FallbackUrl = taskInfo.FallbackUrl + vurl;

                    taskEnvelope = new Models.TaskEnvelope
                    {
                        Task = new Models.Task()
                        {
                            Type     = Models.TaskType.Continue.ToString().ToLower(),
                            TaskInfo = taskInfo
                        }
                    };

                    return(Request.CreateResponse(HttpStatusCode.OK, taskEnvelope));

                case TaskModuleIds.toggleEventStatus:
                    // TODO Event - EventTaskData
                    var eventData = JsonConvert.DeserializeObject <SubmitActionData <EventTaskData> >(activityValue).data;

                    //will update the button action Added<->Removed
                    GetDataHelper.ETStatusUpdate(eventData.eventId);
                    return(new HttpResponseMessage(HttpStatusCode.Accepted));

                default:         // Handled all remaining cases for task module. Ex-  Close, PoDeclinedClosed
                    return(Request.CreateResponse(HttpStatusCode.OK));
                }

            case "composeExtension/submitAction":

                var    details   = JsonConvert.DeserializeObject <SubmitActionData>(activityValue);
                string commandid = details.commandId;
                switch (details.commandId)
                {
                case "createticket":
                    var createTicketData = JsonConvert.DeserializeObject <SubmitActionData <TicketTaskData> >(activityValue);
                    if (createTicketData.data == null)
                    {
                        commandid    = details.commandId;
                        taskInfo     = GetTaskInfo(commandid);
                        taskEnvelope = new Models.TaskEnvelope
                        {
                            Task = new Models.Task()
                            {
                                Type     = Models.TaskType.Continue.ToString().ToLower(),
                                TaskInfo = taskInfo
                            }
                        };

                        return(Request.CreateResponse(HttpStatusCode.OK, taskEnvelope));
                    }
                    else if (createTicketData.data.action == "submit")
                    {
                        return(Request.CreateResponse(HttpStatusCode.OK));
                    }
                    else if (createTicketData.data.action == "submitTicket")
                    {
                        return(Request.CreateResponse(HttpStatusCode.OK));
                    }
                    else
                    {
                        commandid = createTicketData.data.action;
                        taskInfo  = GetTaskInfo(commandid);
                        var ticketurl = "?ticketNoId=" + createTicketData.data.ticketNo + "&description=" + createTicketData.data.TDescription + "&category=" + createTicketData.data.TCategory + "&priority=" + createTicketData.data.TPriority;
                        taskInfo.Url         = taskInfo.Url + ticketurl;
                        taskInfo.FallbackUrl = taskInfo.FallbackUrl + ticketurl;
                        taskEnvelope         = new Models.TaskEnvelope
                        {
                            Task = new Models.Task()
                            {
                                Type     = Models.TaskType.Continue.ToString().ToLower(),
                                TaskInfo = taskInfo
                            }
                        };

                        return(Request.CreateResponse(HttpStatusCode.OK, taskEnvelope));
                    }

                case "visitorregistration":
                    var savevisitordata = JsonConvert.DeserializeObject <SubmitActionData <VisitorData> >(activityValue);

                    if (savevisitordata.data == null)
                    {
                        commandid    = details.commandId;
                        taskInfo     = GetTaskInfo(commandid);
                        taskEnvelope = new Models.TaskEnvelope
                        {
                            Task = new Models.Task()
                            {
                                Type     = Models.TaskType.Continue.ToString().ToLower(),
                                TaskInfo = taskInfo
                            }
                        };

                        return(Request.CreateResponse(HttpStatusCode.OK, taskEnvelope));
                    }
                    else if (savevisitordata.data.action == "submitVisitor")
                    {
                        return(Request.CreateResponse(HttpStatusCode.OK));
                    }
                    else if (savevisitordata.data.action == "submitRequest")
                    {
                        return(Request.CreateResponse(HttpStatusCode.OK));
                    }
                    else
                    {
                        commandid = savevisitordata.data.action;
                        taskInfo  = GetTaskInfo(commandid);
                        var ticketurl = "?Date=" + savevisitordata.data.Vdate + "&Time=" + savevisitordata.data.Vtime + "&Contact=" + savevisitordata.data.Vcontact + "&location=" + savevisitordata.data.VhostLocation + "&purpose=" + savevisitordata.data.Vpurpose + "&hostName=" + savevisitordata.data.VhostName + "&org=" + savevisitordata.data.Vorg;
                        taskInfo.Url         = taskInfo.Url + ticketurl;
                        taskInfo.FallbackUrl = taskInfo.FallbackUrl + ticketurl;
                        taskEnvelope         = new Models.TaskEnvelope
                        {
                            Task = new Models.Task()
                            {
                                Type     = Models.TaskType.Continue.ToString().ToLower(),
                                TaskInfo = taskInfo
                            }
                        };

                        return(Request.CreateResponse(HttpStatusCode.OK, taskEnvelope));
                    }

                default:
                    commandid = details.commandId;
                    break;
                }
                break;

            case "composeExtension/onCardButtonClicked":
                ETid = JsonConvert.DeserializeObject <Models.TaskModuleSubmitData <string> >(activityValue).Data;
                GetDataHelper.ETStatusUpdate(ETid);
                break;
            }
            return(new HttpResponseMessage(HttpStatusCode.Accepted));
        }