Exemplo n.º 1
0
        public static HttpClient CreateClient(string channelId, string userId)
        {
            ChatState  state      = ChatState.RetrieveChatState(channelId, userId);
            HttpClient httpClient = new HttpClient();

            httpClient.BaseAddress = new Uri(state.OrganizationUrl);
            httpClient.Timeout     = new TimeSpan(0, 2, 0);
            httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
            httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", state.AccessToken);
            return(httpClient);
        }
Exemplo n.º 2
0
 public static ChatState RetrieveChatState(string channelId, string userId)
 {
     if (!MemoryCache.Default.Contains(channelId + userId))
     {
         CacheItemPolicy policy = new CacheItemPolicy();
         policy.Priority          = CacheItemPriority.Default;
         policy.SlidingExpiration = TimeSpan.FromMinutes(chatCacheDurationMinutes);
         ChatState state = new ChatState(channelId, userId);
         InitializeState(state);
         MemoryCache.Default.Add(channelId + userId, state, policy);
     }
     return(MemoryCache.Default[channelId + userId] as ChatState);
 }
Exemplo n.º 3
0
        public ActionResult Authorize(string code)
        {
            AuthenticationContext authContext = new AuthenticationContext(ConfigurationManager.AppSettings["CrmAuthority"]);
            var authResult = authContext.AcquireTokenByAuthorizationCodeAsync(
                code, new Uri(ConfigurationManager.AppSettings["CrmRedirectUrl"]),
                new ClientCredential(ConfigurationManager.AppSettings["CrmClientId"],
                                     ConfigurationManager.AppSettings["CrmClientSecret"]));

            // Saving token in Bot State
            var botCredentials = new MicrosoftAppCredentials(ConfigurationManager.AppSettings["MicrosoftAppId"],
                                                             ConfigurationManager.AppSettings["MicrosoftAppPassword"]);
            ChatState state = ChatState.RetrieveChatState(Session["channelId"].ToString(), Session["userId"].ToString());

            state.AccessToken = authResult.Result.AccessToken;

            ViewBag.Message = $"Your Token - {authResult.Result.AccessToken} Channel Id - {Session["channelId"].ToString()} User Id - {Session["userId"].ToString()}";

            // Use the data stored previously to create the required objects.
            var userAccount = new ChannelAccount(Session["userId"].ToString(), Session["userName"].ToString());
            var botAccount  = new ChannelAccount(Session["fromId"].ToString(), Session["fromName"].ToString());
            var connector   = new ConnectorClient(new Uri(Session["serviceUrl"].ToString()));

            string conversationId;
            // Create a new message.
            IMessageActivity message = Activity.CreateMessageActivity();

            if (!string.IsNullOrEmpty(Session["conversationId"].ToString()) && !string.IsNullOrEmpty(Session["channelId"].ToString()))
            {
                // If conversation ID and channel ID was stored previously, use it.
                message.ChannelId = Session["channelId"].ToString();
                conversationId    = Session["conversationId"].ToString();
            }
            else
            {
                // Conversation ID was not stored previously, so create a conversation.
                // Note: If the user has an existing conversation in a channel, this will likely create a new conversation window.
                conversationId = connector.Conversations.CreateDirectConversation(botAccount, userAccount).Id;
            }

            // Set the address-related properties in the message and send the message.
            message.From         = botAccount;
            message.Recipient    = userAccount;
            message.Conversation = new ConversationAccount(id: conversationId);
            message.Text         = $"Thanks! You're logged in now. Try saying 'How many contacts were created this week?'";
            message.Locale       = "en-us";
            connector.Conversations.SendToConversation((Activity)message);

            return(View());
        }
Exemplo n.º 4
0
        public ActionResult Login(string channelId, string userId, string userName, string fromId, string fromName, string serviceUrl, string conversationId, string extraQueryParams)
        {
            // CRM Url
            Session["fromId"]         = fromId;
            Session["fromName"]       = fromName;
            Session["serviceUrl"]     = serviceUrl;
            Session["conversationId"] = conversationId;
            Session["channelId"]      = channelId;
            Session["userId"]         = userId;
            Session["userName"]       = userName;
            ChatState state = ChatState.RetrieveChatState(Session["channelId"].ToString(), Session["userId"].ToString());

            AuthenticationContext authContext = new AuthenticationContext(ConfigurationManager.AppSettings["CrmAuthority"]);
            var authUri = authContext.GetAuthorizationRequestUrlAsync(state.OrganizationUrl, ConfigurationManager.AppSettings["CrmClientId"],
                                                                      new Uri(ConfigurationManager.AppSettings["CrmRedirectUrl"]), UserIdentifier.AnyUser, extraQueryParams);

            return(Redirect(authUri.Result.ToString()));
        }
Exemplo n.º 5
0
        private static string InitializeState(ChatState state)
        {
            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["CrmUserName"]) && !string.IsNullOrEmpty(ConfigurationManager.AppSettings["CrmPassword"]) && !string.IsNullOrEmpty(ConfigurationManager.AppSettings["CrmServiceUrl"]) && !string.IsNullOrEmpty(ConfigurationManager.AppSettings["CrmAuthority"]) && !string.IsNullOrEmpty(ConfigurationManager.AppSettings["CrmClientId"]) && !string.IsNullOrEmpty(ConfigurationManager.AppSettings["CrmClientSecret"]))
            {
                try
                {
                    AuthenticationContext authContext =
                        new AuthenticationContext(ConfigurationManager.AppSettings["CrmAuthority"].ToString(), false);

                    //No prompt for credentials
                    var credentials = new UserPasswordCredential(ConfigurationManager.AppSettings["CrmUserName"].ToString(), ConfigurationManager.AppSettings["CrmPassword"].ToString());
                    var authResult  = authContext.AcquireTokenAsync(ConfigurationManager.AppSettings["CrmServiceUrl"].ToString(), ConfigurationManager.AppSettings["CrmClientId"].ToString(), credentials).Result;

                    state.AccessToken     = authResult.AccessToken;
                    state.OrganizationUrl = ConfigurationManager.AppSettings["CrmServiceUrl"].ToString();
                }
                catch (Exception ex)
                {
                    string message = ex.ToString();
                }
            }
            return(string.Empty);
        }
Exemplo n.º 6
0
        public virtual async Task <HttpResponseMessage> Post([FromBody] Activity message)
        {
            ConnectorClient connector = new ConnectorClient(new Uri(message.ServiceUrl));

            try
            {
                // check if activity is of type message
                if (message != null && message.GetActivityType() == ActivityTypes.Message)
                {
                    ChatState state = ChatState.RetrieveChatState(message.ChannelId, message.From.Id);

                    if (string.IsNullOrEmpty(state.OrganizationUrl) && CrmFunctions.ParseCrmUrl(message) == string.Empty)
                    {
                        await connector.Conversations.ReplyToActivityAsync(message.CreateReply("Hi there, before we can work together you need to tell me your Dynamics 365 URL (e.g. https://contoso.crm.dynamics.com)"));
                    }
                    else if (string.IsNullOrEmpty(state.AccessToken) || CrmFunctions.ParseCrmUrl(message) != string.Empty)
                    {
                        string extraQueryParams = string.Empty;

                        string crmUrl = CrmFunctions.ParseCrmUrl(message);

                        if (crmUrl != string.Empty && state.OrganizationUrl != crmUrl)
                        {
                            if (!string.IsNullOrEmpty(state.OrganizationUrl) && state.OrganizationUrl != crmUrl)
                            {
                                extraQueryParams = "prompt=login";
                            }
                            state.OrganizationUrl = crmUrl;
                        }

                        Activity replyToConversation = message.CreateReply();
                        replyToConversation.Recipient   = message.From;
                        replyToConversation.Type        = "message";
                        replyToConversation.Attachments = new List <Attachment>();

                        List <CardAction> cardButtons = new List <CardAction>();
                        CardAction        plButton    = new CardAction()
                        {
                            // ASP.NET Web Application Hosted in Azure
                            // Pass the user id
                            Value = $"{ConfigurationManager.AppSettings["BotAuthUrl"]}?channelId={HttpUtility.UrlEncode(message.ChannelId)}&userId={HttpUtility.UrlEncode(message.From.Id)}&userName={HttpUtility.UrlEncode(message.From.Name)}&fromId={HttpUtility.UrlEncode(message.Recipient.Id)}&fromName={HttpUtility.UrlEncode(message.Recipient.Name)}&serviceUrl={HttpUtility.UrlEncode(message.ServiceUrl)}&conversationId={HttpUtility.UrlEncode(message.Conversation.Id)}&extraQueryParams={extraQueryParams}",
                            Type  = "signin",
                            Title = "Connect"
                        };

                        cardButtons.Add(plButton);

                        SigninCard plCard = new SigninCard("Click connect to signin to Dynamics 365 (" + state.OrganizationUrl + ").", new List <CardAction>()
                        {
                            plButton
                        });
                        Attachment plAttachment = plCard.ToAttachment();
                        replyToConversation.Attachments.Add(plAttachment);
                        await connector.Conversations.SendToConversationAsync(replyToConversation);
                    }
                    else
                    {
                        await Conversation.SendAsync(message, () => new CrmLuisDialog());
                    }
                }
                else
                {
                    HandleSystemMessage(message);
                }
            }
            catch (Exception ex)
            {
                await connector.Conversations.ReplyToActivityAsync(message.CreateReply($"Kabloooey! Well played human you just fried my circuits. Thanks for being patient, I'm still learning to do some things while in preview. Hopefully, I'll get this worked out soon. Here's your prize: {ex.Message}"));
            }
            return(new HttpResponseMessage(System.Net.HttpStatusCode.Accepted));
        }