コード例 #1
0
ファイル: Coordinator.cs プロジェクト: josesegarra/eduasync
 public Coordinator(params Func <Coordinator <T>, T, Task <T> >[] coroutines)
 {
     // We can't refer to "this" in the variable initializer. We can use
     // the same awaitable for all yield calls.
     this.awaitable = new Awaitable(this);
     actions        = new Queue <Action>(coroutines.Select(ConvertCoroutine));
 }
コード例 #2
0
        private async Task ResumeAfterAuth(IDialogContext context, IAwaitable <string> result)
        {
            var message = await result;

            string dialogId;
            string originalMessageText;

            await context.PostAsync(message);

            try
            {
                context.UserData.TryGetValue(AuthenticationConstants.AuthDialogIdKey, out dialogId);
                context.UserData.TryGetValue(dialogId + '_' + AuthenticationConstants.OriginalMessageText, out originalMessageText);

                IMessageActivity originalMessage = context.MakeMessage();
                originalMessage.Text = originalMessageText;
                IAwaitable <IMessageActivity> awaitableMessage = Awaitable.FromItem(originalMessage);

                await MessageReceived(context, awaitableMessage);
            }
            catch (Exception ex)
            {
                context.Wait(MessageReceived);
            }
        }
コード例 #3
0
ファイル: GltfTextureLoader.cs プロジェクト: des04/UniVRM
        public static async Awaitable <Texture2D> LoadTextureAsync(glTF gltf, IStorage storage, int textureIndex)
        {
            var imageBytes = await Awaitable.Run(() =>
            {
                var imageIndex = gltf.textures[textureIndex].source;
                var segments   = gltf.GetImageBytes(storage, imageIndex);
                return(ToArray(segments));
            });

            //
            // texture from image(png etc) bytes
            //
            var textureType = TextureIO.GetglTFTextureType(gltf, textureIndex);
            var colorSpace  = TextureIO.GetColorSpace(textureType);
            var isLinear    = colorSpace == RenderTextureReadWrite.Linear;
            var sampler     = gltf.GetSamplerFromTextureIndex(textureIndex);

            var texture = new Texture2D(2, 2, TextureFormat.ARGB32, false, isLinear);

            texture.name = gltf.textures[textureIndex].name;
            if (imageBytes != null)
            {
                texture.LoadImage(imageBytes);
            }
            if (sampler != null)
            {
                TextureSamplerUtil.SetSampler(texture, sampler);
            }
            return(texture);
        }
コード例 #4
0
ファイル: FiberTests.cs プロジェクト: gopal300/Localizedbot
        public async Task Awaitable_From_Item()
        {
            var expected  = Guid.NewGuid();
            var awaitable = Awaitable.FromItem(expected);

            Assert.AreEqual(expected, await awaitable);
        }
コード例 #5
0
        public async Task None(IDialogContext context, LuisResult result)
        {
            var qnaAnswer = await qnaMakerProvider.GetQandAResponse(result.Query);

            if (qnaAnswer.FoundAnswer)
            {
                if (Regex.IsMatch(qnaAnswer.Answer, GREETINGTAG, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant))
                {
                    await context.PostAsync(Regex.Replace(qnaAnswer.Answer, GREETINGTAG, string.Empty));
                }
                else
                {
                    await context.PostAsync(qnaAnswer.Answer);
                }
            }
            else if (context.ConversationData.ContainsKey("question"))
            {
                context.ConversationData.SetValue("questionToAnswer", context.ConversationData.GetValue <string>("question"));
                await AfterAnswer(context, Awaitable.FromItem(result.Query));
            }
            else
            {
                await context.PostAsync(messageProvider.GetMessage("NoneIntent"));
            }
        }
コード例 #6
0
        //private Microsoft.Bot.Connector.Activity message = null;
        private async Task EnsureAuthentication(IDialogContext context, Microsoft.Bot.Connector.Activity activity)
        {
            string token = null;

            if (activity.ChannelId.Equals("cortana", StringComparison.InvariantCultureIgnoreCase))
            {
                token = await context.GetAccessToken(string.Empty);
            }
            else
            {
                token = await context.GetAccessToken(AuthSettings.Scopes);
            }

            if (string.IsNullOrEmpty(token))
            {
                if (activity.ChannelId.Equals("cortana", StringComparison.InvariantCultureIgnoreCase))
                {
                    //Cortana channel uses Connected Service for authentication, it has to be authorized to use cortana, we should not get here...
                    throw new InvalidOperationException("Cortana channel has to be used with Conencted Service Account");
                }
                else
                {
                    //message = activity;
                    await context.Forward(new AzureAuthDialog(AuthSettings.Scopes), this.ResumeAfterAuth, context.Activity, CancellationToken.None);
                }
            }
            else
            {
                //await MessageReceived(context, Awaitable.FromItem<Microsoft.Bot.Connector.Activity>(activity));
                await base.MessageReceived(context, Awaitable.FromItem <Microsoft.Bot.Connector.Activity>(activity));
            }
        }
コード例 #7
0
        public async Task ProcessStoreHours(IDialogContext context, LuisResult result)
        {
            // Figuring out if the action is triggered or not
            var bestIntent = BestIntentFrom(result);

            // extracting day parameter value from Entities, if present
            var entity = result.Entities.FirstOrDefault(e => e.Type.ToLower() == "day");

            if (entity != null)
            {
                var  dayParam = entity.Entity;
                Days day;
                if (Enum.TryParse(dayParam, true, out day))
                {
                    await this.StoreHoursResult(context, Awaitable.FromItem(day));

                    return;
                }
            }

            var days = (IEnumerable <Days>)Enum.GetValues(typeof(Days));

            PromptDialog.Choice(context, StoreHoursResult, days, "Which day of the week?",
                                descriptions: from day in days
                                select(day == Days.Saturday || day == Days.Sunday) ? day.ToString() + "(no holidays)" : day.ToString());
        }
コード例 #8
0
        private async Task OnIncidentIdPromptComplete(IDialogContext context, IAwaitable <string> result)
        {
            try
            {
                var userResponse      = await result;
                var incidentIdPattern = @"inc[0-9]{7}";
                var regex             = new Regex(incidentIdPattern, RegexOptions.IgnoreCase);
                var match             = regex.Match(userResponse);
                if (match.Success)
                {
                    var incidentId = match.Value;
                    var incident   = await this.incidentsService.GetIncidentById(incidentId);

                    if (incident == null)
                    {
                        await context.PostAsync($"No incident with Id **{incidentId}** has been found.");
                    }
                    else
                    {
                        await context.PostAsync($"State of incident with Id **{incidentId}** is {incident.State}.");
                    }
                }
                else
                {
                    await base.MessageReceived(context, Awaitable.FromItem(context.Activity.AsMessageActivity()));
                }
            }
            catch (Exception)
            {
                await context.PostAsync("I'm sorry but something happened. Please, try again later on.");
            }
        }
コード例 #9
0
        protected virtual async Task LuisActionMissingDialogFinished(IDialogContext context, IAwaitable <ActionExecutionContext> executionContext)
        {
            var messageActivity        = (IMessageActivity)context.Activity;
            var executionContextResult = await executionContext;

            await this.DispatchToLuisActionActivityHandler(context, Awaitable.FromItem(messageActivity), executionContextResult.Intent, executionContextResult.Action);
        }
コード例 #10
0
        public async Task AnswerQuestion(IDialogContext context, LuisResult result)
        {
            var question = result.Entities.FirstOrDefault(x => x.Type == "question");

            string questionEntity = null;

            if (question != null)
            {
                questionEntity = question.Entity;
            }

            if (string.IsNullOrEmpty(questionEntity))
            {
                questionEntity = context.ConversationData.GetValueOrDefault("question", string.Empty);
            }


            var answer = result.Entities.FirstOrDefault(x => x.Type == "answer");

            if (answer != null)
            {
                context.ConversationData.SetValue("answer", answer.Entity);
            }
            if (string.IsNullOrEmpty(questionEntity))
            {
                IEnumerable <MessageEntity> unansweredQuestions = await GetUnansweredQuestions();

                await context.PostAsync(messageProvider.GetMessage("NoQuestionOrMatch"));
                await GenerateUnansweredQuestions(context, unansweredQuestions);
            }
            else
            {
                await AfterChooseQuestion(context, Awaitable.FromItem(questionEntity));
            }
        }
コード例 #11
0
        private async Task OptionMadeAsync(IDialogContext context, IAwaitable <object> result)
        {
            switch (context.Activity.AsMessageActivity().Text)
            {
            case "room":
                await BookRoom(context, null);

                return;

            case "table":
            case "checkout":
            case "weather":
            case "feedback":
            case "taxi":
            case "special":
            case "question":
                break;

            default:
                var message = context.MakeMessage();
                message.Text = context.Activity.AsMessageActivity().Text;
                await base.MessageReceived(context, Awaitable.FromItem(message));

                break;
            }
        }
コード例 #12
0
        public async Task ProcessStoreHours(IDialogContext context, LuisResult result)
        {
            // Figuring out if the action is triggered or not
            var bestIntent = BestIntentFrom(result);
            var action     = bestIntent.Actions.FirstOrDefault(t => t.Triggered.HasValue && t.Triggered.Value);

            if (action != null)
            {
                // extracting day parameter value from action parameters
                var  dayParam = action.Parameters.Where(t => t.Name == "day").Select(t => t.Value.FirstOrDefault(e => e.Type == "Day")?.Entity).First();
                Days day;
                if (Enum.TryParse(dayParam, true, out day))
                {
                    await this.StoreHoursResult(context, Awaitable.FromItem(day));

                    return;
                }
            }

            var days = (IEnumerable <Days>)Enum.GetValues(typeof(Days));

            PromptDialog.Choice(context, StoreHoursResult, days, "Which day of the week?",
                                descriptions: from day in days
                                select(day == Days.Saturday || day == Days.Sunday) ? day.ToString() + "(no holidays)" : day.ToString());
        }
コード例 #13
0
        public void TryGetResultRecursive_is_recursive()
        {
            const int expectedResult = 42;
            var       obj            = Task.FromResult(Task.FromResult(expectedResult));
            var       result         = Awaitable.TryGetResultRecursive(obj);

            Assert.Equal(expectedResult, result);
        }
コード例 #14
0
 private async Task AfterResumeMessage(IDialogContext context, IAwaitable<string> result)
 {
     var argument = await result;
     Activity myActivity = (Activity)context.Activity;
     myActivity.Text = argument.ToString();
     await MessageReceived(context, Awaitable.FromItem(myActivity));
     
 }
コード例 #15
0
        /**
         * Method to hold the responses enterd by the user
         * */

        private async Task ChoiceRecievedAsync(IDialogContext context, IAwaitable <object> result)
        {
            var      response   = await result;
            Activity myActivity = (Activity)context.Activity;

            myActivity.Text = response.ToString();
            await MessageReceived(context, Awaitable.FromItem(myActivity));
        }
コード例 #16
0
ファイル: InnerMockSetup.cs プロジェクト: v-prla/moq4
        public InnerMockSetup(Expression originalExpression, Mock mock, InvocationShape expectation, object returnValue)
            : base(originalExpression, mock, expectation)
        {
            Debug.Assert(Awaitable.TryGetResultRecursive(returnValue) is IMocked);

            this.returnValue = returnValue;

            this.MarkAsVerifiable();
        }
コード例 #17
0
        private async Task NewDialogCompleteAsync(IDialogContext context, IAwaitable <Choice> result)
        {
            context.Call(new RaiseDialog(), ChildDialogComplete);
            var      response   = await result;
            Activity myActivity = (Activity)context.Activity;

            myActivity.Text = response.ToString();
            await MessageReceived(context, Awaitable.FromItem(myActivity));
        }
コード例 #18
0
        public async Task Cumprimento(IDialogContext context, LuisResult result)
        {
            ConversationStarter.TextReference = string.Empty;
            await context.PostAsync($"Texto enviado: {result.Query}");

            var qnaService = new QnAMakerService(new QnAMakerAttribute(qnaSubscriptionKey, qnaKnowledgebaseId, "Buguei aqui, pera!  ¯\(º_o)/¯"));
            var qnaMaker   = new QnAMakerDialog(qnaService);
            await qnaMaker.MessageReceivedAsync(context, Awaitable.FromItem(activity));
        }
コード例 #19
0
        protected AwaitableAttachment(SerializationInfo info, StreamingContext context)
        {
            // constructor arguments
            var jsonAttachment = default(string);

            SetField.NotNullFrom(out jsonAttachment, nameof(this.attachment), info);
            this.attachment = JsonConvert.DeserializeObject <Attachment>(jsonAttachment);

            this.awaiter = Awaitable.FromSource(this.attachment, this.ResolveFromSourceAsync) as IAwaiter <Stream>;
        }
コード例 #20
0
        public async Task MessageReceivedAsync_ReceivesMessage_DisplaysTextAndLength()
        {
            var message = Activity.CreateMessageActivity();

            message.Text = "abc";

            await _dialog.MessageReceivedAsync(_context.Object, Awaitable.FromItem(message));

            _chat.Verify(c => c.PostAsync(_context.Object, "You sent abc which was 3 characters"));
        }
コード例 #21
0
 private async Task GetIssue(IDialogContext context, ResumeAfter <double> resume)
 {
     if (_lastIssue == 0)
     {
         PromptDialog.Number(context, resume, "What issue are you referring to?", "I didn't catch that...try again?");
     }
     else
     {
         await resume(context, Awaitable.FromItem((double)_lastIssue));
     }
 }
コード例 #22
0
ファイル: Awaitable.cs プロジェクト: uzbekdev1/moq4
        /// <summary>
        ///   Recursively gets the result of (i.e. "unwraps") completed awaitables
        ///   until a value is found that isn't a successfully completed awaitable.
        /// </summary>
        /// <remarks>
        ///   As an example, given <paramref name="obj"/> := <c>Task.FromResult(Task.FromResult(42))</c>,
        ///   this method will return <c>42</c>.
        /// </remarks>
        /// <param name="obj">The (possibly awaitable) object to be "unwrapped".</param>
        public static object TryGetResultRecursive(object obj)
        {
            if (obj != null &&
                AwaitableFactory.TryGet(obj.GetType()) is { } awaitableFactory &&
                awaitableFactory.TryGetResult(obj, out var result))
            {
                return(Awaitable.TryGetResultRecursive(result));
            }

            return(obj);
        }
コード例 #23
0
        private async Task AfterChooseQuestion(IDialogContext context, IAwaitable <string> result)
        {
            var question = await result;

            context.ConversationData.SetValue("questionToAnswer", question);
            if (string.IsNullOrEmpty(context.ConversationData.GetValueOrDefault("answer", string.Empty)))
            {
                PromptDialog.Text(context, AfterAnswer, string.Format(messageProvider.GetMessage("askForAnswer"), question));
            }
            else
            {
                await AfterAnswer(context, Awaitable.FromItem(context.ConversationData.GetValue <string>("answer")));
            }
        }
コード例 #24
0
        private async Task GetRepo(IDialogContext context, string token, ResumeAfter <string> resume)
        {
            if (string.IsNullOrEmpty(_lastRepo))
            {
                IReadOnlyList <Repository> list = await GitHubCommands.GetRepoList(token, string.Empty);

                IEnumerable <string> repos = list.Select(i => i.Name);
                PromptDialog.Choice(context, resume, repos, "Which repo are you asking about?", "I didn't catch that...try again?");
            }
            else
            {
                await resume(context, Awaitable.FromItem(_lastRepo));
            }
        }
コード例 #25
0
    private async Task ResumeAfterAuth(IDialogContext context, IAwaitable <string> result)
    {
        var message = await
                      await context.PostAsync(message);

        Activity activity = (Activity)context.Activity;

        //Store the saved message back to the activity
        activity.Text = userToBot;

        //Reset the saved message
        userToBot = string.Empty;
        //Call the base.MessageReceived to trigger the LUIS intenet
        await base.MessageReceived(context, Awaitable.FromItem(activity));
    }
コード例 #26
0
        protected virtual async Task ResumeAfterCallback(IDialogContext context, IAwaitable <object> result)
        {
            var message = await result;

            if (message == null)
            {
                await context.PostAsync("대화 종료.");

                context.Done <object>(null);
            }
            else
            {
                IAwaitable <IMessageActivity> re = Awaitable.FromItem <IMessageActivity>((IMessageActivity)message);
                await this.MessageReceived(context, re);
            }
        }
コード例 #27
0
        public void TestJsonIntermediateFormatSerializer_SetActive()
        {
            /* PRECONDITION */
            Debug.Assert(serializer != null);
            Debug.Assert(inputQueue != null);
            Debug.Assert(container != null);
            Debug.Assert(!serializer.IsActive);
            Debug.Assert(serializer.IsClosed);

            /* GIVEN */
            container.ComposeExportedValue <IReadOnlyEventQueue <Event> >(inputQueue);
            container.ComposeParts(serializer);

            serializer.Initialize(true);

            const int identifier = 404;
            var       @testEvent = new TestEvent(identifier);

            using var didConsumeEvent        = new ManualResetEvent(false);
            using var didStartConsumingEvent = new ManualResetEvent(false);

            /* WHEN */
            serializer.IsActive = true;
            Assert.IsTrue(serializer.IsActive);

            var thread = new Thread(async() =>
            {
                await foreach (var @event in Awaitable.Await(serializer.GetEvents(), didStartConsumingEvent))
                {
                    var deserialized = JsonSerializer.Deserialize(@event.Data, @event.Type);

                    if ((deserialized is TestEvent receivedEvent) && receivedEvent.Identifier == @testEvent.Identifier)
                    {
                        didConsumeEvent.Set();
                    }
                }
            });

            thread.Start();
            Assert.IsTrue(didStartConsumingEvent.WaitOne(maxWaitTime));
            Assert.IsTrue(inputQueue.ConsumerAttachedEvent.WaitOne(maxWaitTime), "Serializer did not attach in time to input queue!");
            inputQueue.Enqueue(@testEvent);

            /* THEN */
            Assert.IsFalse(serializer.IsClosed, "Serializer unexpectedly still closed!");
            Assert.IsTrue(didConsumeEvent.WaitOne(maxWaitTime), "Did not receive serialized event in time!");
        }
コード例 #28
0
    private async void OnEndOfFetch(string token, string err)
    {
        string t = token ?? "";
        string e = err ?? "";

        ManageScroll.Log(DateTime.Now.ToString("tthh時mm分ss秒fffミリ秒") + ": OnEndOfGetIDToken");

        if (t != "" && e == "")
        {
            // SingIn済み
            ManageScroll.Log("token: " + t);

            // Fetch実行 TODO: エラーキャッチ
            var session = new DefaultSession(Manager.HostName, token);

            LoginRequest req = new LoginRequest();

            var awaitableCoroutine = Awaitable.Create <LoginResponse>(tcs => session.Login(req, tcs));
            var result             = await awaitableCoroutine;

            ManageScroll.Log("result: " + result);

            if (result.Token != "")
            {
                var accessToken = result.Token;
                ManageScroll.Log("accessToken: " + accessToken);

                // Fetch実行 TODO: エラーキャッチ
                var haberdasher = new DefaultHaberdasher(Manager.HostName, accessToken);

                Size req2 = new Size();
                req2.Inches = UnityEngine.Random.Range(1, 1001);

                var awaitableCoroutine2 = Awaitable.Create <Hat>(tcs => haberdasher.MakeHat(req2, tcs));
                var result2             = await awaitableCoroutine2;

                ManageScroll.Log("result: " + result2);
            }
        }

        if (e != "")
        {
            ManageScroll.Log("err: " + e);
        }
    }
コード例 #29
0
        private async Task ResumeAfterPlanDate(IDialogContext context, IAwaitable <object> result)
        {
            var newContext = await result as DynamicsContextController;

            this.customerContext = newContext;

            if (this.shouldContinueWithLastMessage)
            {
                var newMessage = context.MakeMessage();
                newMessage.Text = this.lastMessage;

                await this.MessageReceived(context, Awaitable.FromItem(newMessage));

                return;
            }

            context.Wait(this.MessageReceived);
        }
コード例 #30
0
//    private async void OnEndOfFetch(string token, string err) {
//        string t = token ?? "";
//        string e = err ?? "";
//        ManageScroll.Log(DateTime.Now.ToString("tthh時mm分ss秒fffミリ秒") + ": OnEndOfGetIDToken");
//
//        if (t != "" && e == "") {
//            // SingIn済み
//            ManageScroll.Log("token: " + t);
//
//            // Fetch実行 TODO: エラーキャッチ
//            var helloWorld = new DefaultHelloWorld(Manager.HostName, token);
//
//            string user = "******";
//            HelloReq req = new HelloReq();
//            req.Subject = user;
//
//            var awaitableCoroutine = Awaitable.Create<HelloResp>(tcs => helloWorld.Hello(req, tcs));
//            var result = await awaitableCoroutine;
//
//            ManageScroll.Log("result: " + result);
//        }
//
//        if (e != "") {
//            ManageScroll.Log("err: " + e);
//        }
//    }

    public async void OnClickButton()
    {
        ManageScroll.Log(DateTime.Now.ToString("tthh時mm分ss秒fffミリ秒") + ": Fetch");
        // 認証必要なし
        // FirebaseAuthPlugIn.CallPlugin(OnEndOfFetch);

        // Fetch実行 TODO: エラーキャッチ
        var helloWorld = new DefaultHelloWorld(Manager.HostName, "");

        HelloReq req = new HelloReq();

        req.Subject = "dummy user";

        var awaitableCoroutine = Awaitable.Create <HelloResp>(tcs => helloWorld.Hello(req, tcs));
        var result             = await awaitableCoroutine;

        ManageScroll.Log("result: " + result);
    }
コード例 #31
0
ファイル: AwaitableInterface.cs プロジェクト: evilz/Tidbits
 public async Task AwaitAwaitable()
 {
     IAwaitable awaitable = new Awaitable();
     await awaitable;
 }