Ejemplo n.º 1
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var query = new QueryInput
            {
                Text = new TextInput
                {
                    Text         = "cc",
                    LanguageCode = "en-us"
                }
            };

            var sessionId = "SomeUniqueId";
            var agent     = "test5";
            var creds     = GoogleCredential.FromJson(@"D:/test5.json");
            var channel   = new Grpc.Core.Channel(SessionsClient.DefaultEndpoint.Host,
                                                  creds.ToChannelCredentials());

            var client = SessionsClient.Create(channel);

            var dialogFlow = client.DetectIntent(
                new SessionName(agent, sessionId),
                query
                );

            channel.ShutdownAsync();
        }
Ejemplo n.º 2
0
        public static int DetectIntentFromTexts(string[] texts, string projectId = "myhr-johjri",
                                                string sessionId    = "04ab1a17-f0d1-e7af-e0b1-4e9945b749f7",
                                                string languageCode = "en-US")
        {
            var client = SessionsClient.Create();

            foreach (var text in texts)
            {
                var response = client.DetectIntent(
                    session: SessionName.FromProjectSession(projectId, sessionId),
                    queryInput: new QueryInput()
                {
                    Text = new TextInput()
                    {
                        Text         = text,
                        LanguageCode = languageCode
                    }
                }
                    );

                var queryResult = response.QueryResult;

                Console.WriteLine($"Query text: {queryResult.QueryText}");
                if (queryResult.Intent != null)
                {
                    Console.WriteLine($"Intent detected: {queryResult.Intent.DisplayName}");
                }
                Console.WriteLine($"Intent confidence: {queryResult.IntentDetectionConfidence}");
                Console.WriteLine($"Fulfillment text: {queryResult.FulfillmentText}");
                Console.WriteLine();
            }

            return(0);
        }
Ejemplo n.º 3
0
        public async Task <IActionResult> sendtext(string text, string sessionId)
        {
            var result = new RequestResult();

            try
            {
                var query = new QueryInput {
                    Text = new TextInput {
                        Text = text, LanguageCode = "ru-ru"
                    }
                };

                var agent   = "small-talk-1-cdboby";
                var creds   = GoogleCredential.FromFile($"{_env.WebRootPath}\\DFCredits.json");
                var channel = new Grpc.Core.Channel(SessionsClient.DefaultEndpoint.Host, creds.ToChannelCredentials());

                var client     = SessionsClient.Create(channel);
                var dialogFlow = await client.DetectIntentAsync(new SessionName(agent, sessionId), query);

                await channel.ShutdownAsync();

                result.IsSuccess = true;
                result.Data      = string.IsNullOrEmpty(dialogFlow?.QueryResult?.FulfillmentText) ? GetRandomDontKnow() : dialogFlow.QueryResult.FulfillmentText;
            }
            catch (Exception err)
            {
                result.IsSuccess = false;
                result.Data      = "Упс... что-то пошло не так...";
                result.Error     = $"Ошбика: {err.Message}";
            }

            return(new JsonResult(result));
        }
Ejemplo n.º 4
0
        public ActionResult DetectIntentFromTexts(string q, string sessionId)
        {
            try
            {
                var client = SessionsClient.Create();

                DetectIntentRequest request = new DetectIntentRequest();
                request.SessionAsSessionName = new SessionName(_projectAgentName.ProjectId, sessionId);
                request.QueryInput           = new QueryInput
                {
                    Text = new TextInput()
                    {
                        Text         = q,
                        LanguageCode = "pt-br"
                    }
                };

                DetectIntentResponse response = client.DetectIntent(request);

                var queryResult = response.QueryResult;

                return(Ok(queryResult));
            }
            catch (Exception ex)
            {
                return(StatusCode(500, ex.Message));
            }
        }
Ejemplo n.º 5
0
        static async Task Main(string[] args)
        {
            var channel = new Channel("localhost", 50051, ChannelCredentials.Insecure);
            var client  = new SessionsClient(channel);
            var sw      = new Stopwatch();

            while (true)
            {
                for (int i = 'A'; i <= 'Z'; i++) // yep, this will cycle A-Z
                {
                    var startsWith = new string((char)i, 1);
                    sw.Restart();
                    var response = await client.GetSessionsAsync(new GetSessionsRequest { TitleStartsWith = startsWith });

                    sw.Stop();
                    Console.WriteLine($"Found {response.Sessions.Count} sessions starting with {startsWith} in {sw.ElapsedTicks / 10} μs ({sw.ElapsedMilliseconds} ms)");
                    foreach (var session in response.Sessions)
                    {
                        Console.WriteLine($"{session.Title} by {session.SpeakerName}");
                    }
                    Console.WriteLine("");
                    if (response.Sessions.Count > 0)
                    {
                        await Task.Delay(2_000);
                    }
                }
            }
        }
Ejemplo n.º 6
0
        public static string DetectIntent(string text)
        {
            var query = new QueryInput
            {
                Text = new TextInput
                {
                    Text         = text,
                    LanguageCode = "ru"
                }
            };

            var sessionId = Guid.NewGuid().ToString();
            var agent     = "smalltalkbot-atvxnh";
            var creds     = IntentDetector.Creds;
            var channel   = new Grpc.Core.Channel(SessionsClient.DefaultEndpoint.Host,
                                                  creds.ToChannelCredentials());

            var client = SessionsClient.Create(channel);

            var dialogFlow = client.DetectIntent(
                new SessionName(agent, sessionId),
                query
                );

            channel.ShutdownAsync();
            return(dialogFlow.QueryResult.FulfillmentText);
        }
Ejemplo n.º 7
0
        public ActionResult GetEvent(string eventName, string sessionId)
        {
            try
            {
                var client = SessionsClient.Create();

                DetectIntentRequest request = new DetectIntentRequest();
                request.SessionAsSessionName = new SessionName(_projectAgentName.ProjectId, sessionId);
                request.QueryInput           = new QueryInput
                {
                    Event = new EventInput
                    {
                        Name         = eventName,
                        LanguageCode = "pt-br"
                    }
                };

                request.QueryParams = new QueryParameters();

                DetectIntentResponse response = client.DetectIntent(request);

                var queryResult = response.QueryResult;

                return(Ok(queryResult));
            }
            catch (Exception ex)
            {
                return(StatusCode(500, ex.Message));
            }
        }
Ejemplo n.º 8
0
        private string Conversation(SessionsClient clientSessions, string authFilter, string joyUserId, Guid joyGuid, bool isReInit)
        {
            EventInput evnt = new EventInput
            {
                Name         = isReInit ? ConstDialogFlow.DialogFlowReinitializeConversationEvent : ConstDialogFlow.DialogFlowInitConversationEvent,
                LanguageCode = ConstDialogFlow.Language
            };

            evnt.Parameters = new Google.Protobuf.WellKnownTypes.Struct();

            Google.Protobuf.WellKnownTypes.Value v1 = new Google.Protobuf.WellKnownTypes.Value();
            v1.StringValue = joyUserId;
            Google.Protobuf.WellKnownTypes.Value v2 = new Google.Protobuf.WellKnownTypes.Value();
            v2.StringValue = authFilter;

            evnt.Parameters.Fields.Add(ConstDialogFlow.DialogFlowUserName, v1);
            evnt.Parameters.Fields.Add(ConstDialogFlow.DialogFlowToken, v2);

            var response = clientSessions.DetectIntent(
                session: new SessionName("hr-joy", joyGuid.ToString("N", CultureInfo.CurrentCulture)),
                queryInput: new QueryInput
            {
                Event = evnt
            }
                );

            var queryResult = response.QueryResult;

            //   var joyUserDetails = _subscribeModuleService.GetIdentifier();
            return(string.IsNullOrEmpty(queryResult.FulfillmentText) ?
                   ConstDialogFlowResponseMessage.WelcomeExceptionMessage
            : string.Format(CultureInfo.CurrentCulture, ConstDialogFlowResponseMessage.WelcomeMessage, "Raju Singh"));
        }
        // [START dialogflow_detect_intent_texts]
        public static int DetectIntentFromTexts(string projectId,
                                                string sessionId,
                                                string[] texts,
                                                string languageCode = "en-US")
        {
            var client = SessionsClient.Create();

            foreach (var text in texts)
            {
                var response = client.DetectIntent(
                    session: new SessionName(projectId, sessionId),
                    queryInput: new QueryInput()
                {
                    Text = new TextInput()
                    {
                        Text         = text,
                        LanguageCode = languageCode
                    }
                }
                    );

                var queryResult = response.QueryResult;

                Console.WriteLine($"Query text: {queryResult.QueryText}");
                Console.WriteLine($"Intent detected: {queryResult.Intent.DisplayName}");
                Console.WriteLine($"Intent confidence: {queryResult.IntentDetectionConfidence}");
                Console.WriteLine($"Fulfillment text: {queryResult.FulfillmentText}");
                Console.WriteLine();
            }

            return(0);
        }
Ejemplo n.º 10
0
        public IActionResult Index(string userSay)
        {
            //由 google api console 建立服務帳號, 並匯出存取token
            System.Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", @"D:\temp\worldmap-1357-c80b706e2fa6.json");

            var input = new TextInput
            {
                Text = userSay, LanguageCode = "zh-TW"
            };

            // Create client
            SessionsClient sessionsClient = SessionsClient.Create();

            // Initialize request argument(s)
            DetectIntentRequest request = new DetectIntentRequest
            {
                SessionAsSessionName = SessionName.FromProjectSession("worldmap-1357", "[SESSION]"),
                QueryParams          = new QueryParameters(),
                QueryInput           = new QueryInput()
                {
                    Text = input
                },
                OutputAudioConfig     = new OutputAudioConfig(),
                InputAudio            = ByteString.Empty,
                OutputAudioConfigMask = new FieldMask(),
            };

            // Make the request
            DetectIntentResponse response = sessionsClient.DetectIntent(request);

            //將訊息傳送給 View 做顯示
            ViewData["response"] = response.QueryResult.FulfillmentText;
            return(View());
        }
Ejemplo n.º 11
0
        private string Conversation(SessionsClient clientSessions, string authFilter, string joyUserId, Guid joyGuid, bool isReInit, BaseEntityModel model)
        {
            EventInput evnt = new EventInput
            {
                Name         = isReInit ? "reinit_conversation_event" : "custom_welcome_event",
                LanguageCode = Language
            };

            evnt.Parameters = new Google.Protobuf.WellKnownTypes.Struct();

            Google.Protobuf.WellKnownTypes.Value v1 = new Google.Protobuf.WellKnownTypes.Value();
            v1.StringValue = joyUserId;
            Google.Protobuf.WellKnownTypes.Value v2 = new Google.Protobuf.WellKnownTypes.Value();
            v2.StringValue = authFilter;

            evnt.Parameters.Fields.Add("user_name", v1);
            evnt.Parameters.Fields.Add("token", v2);

            var response = clientSessions.DetectIntent(
                session: new SessionName(ConfigurationManager.AppSettings["DialogFlowAgentId"], joyGuid.ToString("N", CultureInfo.CurrentCulture)),
                queryInput: new QueryInput
            {
                Event = evnt
            }
                );

            var queryResult = response.QueryResult;

            return(string.IsNullOrEmpty(queryResult.FulfillmentText) ? WelcomeExceptionMessage
                                                                      : string.Format(CultureInfo.CurrentCulture, WelcomeMessage, "Raju Singh"));
        }
Ejemplo n.º 12
0
        static void Main(string[] args)
        {
            string token        = File.ReadAllText(@"C:\SKILLBOX_STUDY\C#\HOMEWORK\9\TelegramBot\Data_Files\tokens\token");             // токен для бота
            string dFlowKeyPath = @"C:\SKILLBOX_STUDY\C#\HOMEWORK\9\TelegramBot\Data_Files\tokens\small-talk-rghy-1fa31b152405.json";   // путь к токену для DialogFlow бота

            // Создание telegram-бота
            Bot = new TelegramBotClient(token);

            // Создание DialogFlow клиента
            var dic = JsonConvert.DeserializeObject <Dictionary <string, string> >(File.ReadAllText(dFlowKeyPath));

            projectID = dic["project_id"];
            sessionID = dic["private_key_id"];

            var dialogFlowBuilder = new SessionsClientBuilder {
                CredentialsPath = dFlowKeyPath
            };

            dFlowClient = dialogFlowBuilder.Build();

            games = new AllGames();

            // Подписываем обработчики на события
            Bot.OnMessage       += Bot_OnMessage;
            Bot.OnCallbackQuery += Bot_OnCallbackQuery;

            Bot.StartReceiving();

            Console.ReadKey();

            Bot.StopReceiving();
        }
Ejemplo n.º 13
0
        /// <summary>
        /// 呼叫 Dialogflow 識別出意圖
        /// </summary>
        /// <param name="userSay"></param>
        /// <returns></returns>
        public DetectIntentResponse CallDialogFlow(string userSay)
        {
            //由 google api console 建立服務帳號, 並匯出存取token
            System.Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", @"認證檔.json");

            var input = new TextInput
            {
                Text         = userSay,
                LanguageCode = "zh-TW"
            };

            // Create client
            SessionsClient sessionsClient = SessionsClient.Create();

            // Initialize request argument(s)
            DetectIntentRequest request = new DetectIntentRequest
            {
                SessionAsSessionName = SessionName.FromProjectSession("worldmap-1357", "[SESSION]"),
                QueryParams          = new QueryParameters(),
                QueryInput           = new QueryInput()
                {
                    Text = input
                },
                OutputAudioConfig     = new OutputAudioConfig(),
                InputAudio            = ByteString.Empty,
                OutputAudioConfigMask = new FieldMask(),
            };

            // Make the request
            DetectIntentResponse response = sessionsClient.DetectIntent(request);

            return(response);
        }
Ejemplo n.º 14
0
    private async Task CreateSession()
    {
        // Create client
        _sessionsClient = await SessionsClient.CreateAsync();

        // Initialize request argument(s)
        _sessionName = new SessionName(_projectId, _userID);
    }
Ejemplo n.º 15
0
        private async Task CreateSession()
        {
            // Create client
            sessionsClient = await SessionsClient.CreateAsync();

            // Initialize request argument(s)
            sessionName = new SessionName(settings.DialogFlowProject, userID);
        }
        // [START dialogflow_detect_intent_texttospeech_response]
        public static int DetectIntentTexttospeechResponseFromTexts(string projectId,
                                                                    string sessionId,
                                                                    string[] texts,
                                                                    string languageCode = "en-US")
        {
            var client            = SessionsClient.Create();
            var outputAudioConfig = new OutputAudioConfig
            {
                AudioEncoding          = OutputAudioEncoding.Linear16,
                SynthesizeSpeechConfig = new SynthesizeSpeechConfig
                {
                    SpeakingRate = 1,
                    Pitch        = 1,
                    VolumeGainDb = 1
                },
                SampleRateHertz = 16000,
            };

            foreach (var text in texts)
            {
                var response = client.DetectIntent(new DetectIntentRequest
                {
                    SessionAsSessionName = SessionName.FromProjectSession(projectId, sessionId),
                    OutputAudioConfig    = outputAudioConfig,
                    QueryInput           = new QueryInput()
                    {
                        Text = new TextInput()
                        {
                            Text         = text,
                            LanguageCode = languageCode
                        }
                    }
                }
                                                   );

                var queryResult = response.QueryResult;

                Console.WriteLine($"Query text: {queryResult.QueryText}");
                if (queryResult.Intent != null)
                {
                    Console.WriteLine($"Intent detected: {queryResult.Intent.DisplayName}");
                }
                Console.WriteLine($"Intent confidence: {queryResult.IntentDetectionConfidence}");
                Console.WriteLine($"Fulfillment text: {queryResult.FulfillmentText}");
                Console.WriteLine();

                if (response.OutputAudio.Length > 0)
                {
                    using (var output = File.Create("output.wav"))
                    {
                        response.OutputAudio.WriteTo(output);
                    }
                    Console.WriteLine("Audio content written to file \"output.wav\"");
                }
            }

            return(0);
        }
Ejemplo n.º 17
0
        private SessionsClient CreateDialogFlowClientSessions()
        {
            var dialogFlowConfigurationFilePath = System.Web.Hosting.HostingEnvironment.MapPath(@"~/App_Data/hrone-wxhfau-221616b3f7be.json");
            GoogleCredential googleCredential   = GoogleCredential.FromFile(dialogFlowConfigurationFilePath);
            Channel          channel            = new Channel(SessionsClient.DefaultEndpoint.Host,
                                                              googleCredential.ToChannelCredentials());

            return(SessionsClient.Create(channel));
        }
Ejemplo n.º 18
0
        private SessionsClient CreateDialogFlowClientSessions()
        {
            var dialogFlowConfigurationFilePath = _env.ContentRootPath + "/App_Data";
            GoogleCredential googleCredential   = GoogleCredential.FromFile(dialogFlowConfigurationFilePath + "/hr-joy-26ab70a34ae2.json");
            Channel          channel            = new Channel(SessionsClient.DefaultEndpoint.Host,
                                                              googleCredential.ToChannelCredentials());

            return(SessionsClient.Create(channel));
        }
Ejemplo n.º 19
0
        public int DetectIntentFromTexts(
            string sessionId,
            string text,
            string languageCode = "en-US")
        {
            string    projectId = "INSERT_PROJECT_ID_HERE";
            var       creds     = GoogleCredential.FromJson("INSERT_KEY_HERE");
            var       channel   = new Grpc.Core.Channel(SessionsClient.DefaultEndpoint.Host, creds.ToChannelCredentials());
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            var client = SessionsClient.Create(channel);

            var response = client.DetectIntent(
                session: new SessionName(projectId, sessionId),
                queryInput: new QueryInput()
            {
                Text = new TextInput()
                {
                    Text         = text,
                    LanguageCode = languageCode
                }
            }
                );
            var queryResult    = response.QueryResult;
            var detectedIntent = queryResult.Intent.DisplayName;
            var state          = graph.GetStateAsync(sessionId);


            if (state == null)
            {
                graph.SendHelloAsync(sessionId).Wait();
            }
            else if (state.CurrentContext == Startup.BotContext.Quiz.ToString())
            {
                QuizContextProcessing(sessionId, detectedIntent, queryResult, state);
            }
            //else if (state.CurrentContext == Startup.BotContext.Feedback.ToString())
            //{
            //    FeedbackProcessing(sessionId, detectedIntent, queryResult);
            //}
            else if (state.CurrentContext == Startup.BotContext.Email.ToString())
            {
                EmailProcessing(sessionId, detectedIntent, queryResult);
            }
            else if (state.CurrentContext == Startup.BotContext.Ineligible.ToString())
            {
                IneligibleContextProcessing(sessionId, detectedIntent, queryResult);
            }
            else if (state.CurrentContext == Startup.BotContext.Welcome.ToString())
            {
                WelcomeContextProcessing(sessionId, detectedIntent, queryResult);
            }

            return(0);
        }
Ejemplo n.º 20
0
        public DialogflowService(SessionsClient dialogflowClient, DialogflowConfiguration configuration, IMapper mapper)
        {
            _dialogflowClient = dialogflowClient;
            _configuration    = configuration;
            _mapper           = mapper;

            _eventResolvers = new Dictionary <Source, Func <Request, EventInput> >
            {
                { Source.Yandex, YandexEventResolve },
            };
        }
        /// <summary>Snippet for StreamingDetectIntent</summary>
        public async Task StreamingDetectIntent()
        {
            // Snippet: StreamingDetectIntent(CallSettings, BidirectionalStreamingSettings)
            // Create client
            SessionsClient sessionsClient = SessionsClient.Create();

            // Initialize streaming call, retrieving the stream object
            SessionsClient.StreamingDetectIntentStream response = sessionsClient.StreamingDetectIntent();

            // Sending requests and retrieving responses can be arbitrarily interleaved
            // Exact sequence will depend on client/server behavior

            // Create task to do something with responses from server
            Task responseHandlerTask = Task.Run(async() =>
            {
                // Note that C# 8 code can use await foreach
                AsyncResponseStream <StreamingDetectIntentResponse> responseStream = response.GetResponseStream();
                while (await responseStream.MoveNextAsync())
                {
                    StreamingDetectIntentResponse responseItem = responseStream.Current;
                    // Do something with streamed response
                }
                // The response stream has completed
            });

            // Send requests to the server
            bool done = false;

            while (!done)
            {
                // Initialize a request
                StreamingDetectIntentRequest request = new StreamingDetectIntentRequest
                {
                    Session               = "",
                    QueryParams           = new QueryParameters(),
                    QueryInput            = new QueryInput(),
                    OutputAudioConfig     = new OutputAudioConfig(),
                    InputAudio            = ByteString.Empty,
                    OutputAudioConfigMask = new FieldMask(),
                };
                // Stream a request to the server
                await response.WriteAsync(request);

                // Set "done" to true when sending requests is complete
            }

            // Complete writing requests to the stream
            await response.WriteCompleteAsync();

            // Await the response handler
            // This will complete once all server responses have been processed
            await responseHandlerTask;
            // End snippet
        }
 /// <summary>Snippet for DetectIntent</summary>
 public void DetectIntentResourceNames()
 {
     // Snippet: DetectIntent(SessionName, QueryInput, CallSettings)
     // Create client
     SessionsClient sessionsClient = SessionsClient.Create();
     // Initialize request argument(s)
     SessionName session    = SessionName.FromProjectLocationSession("[PROJECT]", "[LOCATION]", "[SESSION]");
     QueryInput  queryInput = new QueryInput();
     // Make the request
     DetectIntentResponse response = sessionsClient.DetectIntent(session, queryInput);
     // End snippet
 }
 /// <summary>Snippet for DetectIntent</summary>
 public void DetectIntent()
 {
     // Snippet: DetectIntent(string, QueryInput, CallSettings)
     // Create client
     SessionsClient sessionsClient = SessionsClient.Create();
     // Initialize request argument(s)
     string     session    = "projects/[PROJECT]/locations/[LOCATION]/agent/sessions/[SESSION]";
     QueryInput queryInput = new QueryInput();
     // Make the request
     DetectIntentResponse response = sessionsClient.DetectIntent(session, queryInput);
     // End snippet
 }
Ejemplo n.º 24
0
        public void Configure(IApplicationBuilder app, ILogger <Startup> logger)
        {
            var client = SessionsClient.Create();

            var jsonSettings = new JsonSerializerSettings
            {
                ContractResolver = new DefaultContractResolver
                {
                    NamingStrategy = new CamelCaseNamingStrategy()
                },
            };

            app.Map("/api/dialogflow/detectIntent", builder =>
            {
                builder.Run(async ctx =>
                {
                    try
                    {
                        var body       = await new StreamReader(ctx.Request.Body).ReadToEndAsync();
                        var request    = JsonConvert.DeserializeObject <DialogflowRequest>(body);
                        var queryInput =
                            string.IsNullOrEmpty(request.Text)
                                ? new QueryInput()
                        {
                            Event = new EventInput
                            {
                                LanguageCode = request.LanguageCode,
                                Name         = request.Event,
                            }
                        }
                                : new QueryInput()
                        {
                            Text = new TextInput()
                            {
                                Text         = request.Text,
                                LanguageCode = request.LanguageCode
                            }
                        };
                        var response = await client.DetectIntentAsync(
                            session: new SessionName(request.ProjectId, request.SessionId),
                            queryInput: queryInput
                            );
                        await ctx.Response.WriteAsync(JsonConvert.SerializeObject(response, jsonSettings));
                    }
                    catch (Exception e)
                    {
                        logger.LogError(e, "error occured");
                        ctx.Response.StatusCode = StatusCodes.Status500InternalServerError;
                        await ctx.Response.WriteAsync(e.Message);
                    }
                });
            });
        }
        public OktaSessionMgmt(string apiUrl, string apiToken)
        {
            _apiUrl = apiUrl;
            Uri orgUri = new Uri(OrgUrl);

            _orgSettings          = new OktaSettings();
            _orgSettings.ApiToken = apiToken;
            _orgSettings.BaseUri  = orgUri;
            _authclient           = new AuthClient(_orgSettings);
            _oktaClient           = new OktaClient(_orgSettings);
            _usersClient          = new UsersClient(_orgSettings);
            _sessionsClient       = new SessionsClient(_orgSettings);
        }
        public OktaAPIHelper(string orgUrlParam, string apiToken)
        {
            _orgUrl = orgUrlParam;
            Uri orgUri = new Uri(OrgUrl);

            _orgSettings          = new OktaSettings();
            _orgSettings.ApiToken = apiToken;
            _orgSettings.BaseUri  = orgUri;
            _authclient           = new AuthClient(_orgSettings);
            _oktaClient           = new OktaClient(_orgSettings);
            _usersClient          = new UsersClient(_orgSettings);
            _sessionsClient       = new SessionsClient(_orgSettings);
        }
        private void Init()
        {
            if(channel == null)
            {
                sessionId = Guid.NewGuid().ToString();

                var creds = GoogleCredential.FromFile(HttpContext.Current.Server.MapPath("Content/Account/" + GoogleCredentialJsonFile));

                channel = new Grpc.Core.Channel(SessionsClient.DefaultEndpoint.Host,
                              creds.ToChannelCredentials());

                client = SessionsClient.Create(channel);
            }          
        }
Ejemplo n.º 28
0
        public void DeleteSessionToken()
        {
            OktaSettings oktaSettings = new OktaSettings();
            oktaSettings.BaseUri = new Uri(Environment.GetEnvironmentVariable("OKTA_TEST_URL"));
            oktaSettings.ApiToken = Environment.GetEnvironmentVariable("OKTA_TEST_KEY");

            String username = Environment.GetEnvironmentVariable("OKTA_TEST_ADMIN_NAME");
            String password = Environment.GetEnvironmentVariable("OKTA_TEST_ADMIN_PASSWORD");

            SessionsClient sessionsClient = new SessionsClient(oktaSettings);

            var session = sessionsClient.Create(username, password);
            sessionsClient.Close(session.Id);
        }
        /// <summary>Snippet for DetectIntentAsync</summary>
        public async Task DetectIntentAsync()
        {
            // Snippet: DetectIntentAsync(string, QueryInput, CallSettings)
            // Additional: DetectIntentAsync(string, QueryInput, CancellationToken)
            // Create client
            SessionsClient sessionsClient = await SessionsClient.CreateAsync();

            // Initialize request argument(s)
            string     session    = "projects/[PROJECT]/locations/[LOCATION]/agent/sessions/[SESSION]";
            QueryInput queryInput = new QueryInput();
            // Make the request
            DetectIntentResponse response = await sessionsClient.DetectIntentAsync(session, queryInput);

            // End snippet
        }
 /// <summary>Snippet for DetectIntent</summary>
 public void DetectIntent_RequestObject()
 {
     // Snippet: DetectIntent(DetectIntentRequest,CallSettings)
     // Create client
     SessionsClient sessionsClient = SessionsClient.Create();
     // Initialize request argument(s)
     DetectIntentRequest request = new DetectIntentRequest
     {
         SessionAsSessionName = new SessionName("[PROJECT]", "[SESSION]"),
         QueryInput           = new QueryInput(),
     };
     // Make the request
     DetectIntentResponse response = sessionsClient.DetectIntent(request);
     // End snippet
 }
        /// <summary>Snippet for DetectIntentAsync</summary>
        public async Task DetectIntentResourceNamesAsync()
        {
            // Snippet: DetectIntentAsync(SessionName, QueryInput, CallSettings)
            // Additional: DetectIntentAsync(SessionName, QueryInput, CancellationToken)
            // Create client
            SessionsClient sessionsClient = await SessionsClient.CreateAsync();

            // Initialize request argument(s)
            SessionName session    = SessionName.FromProjectLocationSession("[PROJECT]", "[LOCATION]", "[SESSION]");
            QueryInput  queryInput = new QueryInput();
            // Make the request
            DetectIntentResponse response = await sessionsClient.DetectIntentAsync(session, queryInput);

            // End snippet
        }
Ejemplo n.º 32
0
        public void CreateSessionRedirectUrl()
        {
            String fakeEndpoint = "http://validurl.com:9999";
            String fakeSessionToken = "FakeSessionToken";
            String fakeRedirect = "https://this.is.fake:42/really?really=true&also=very+true";

            // Create a SessionsClient
            OktaSettings oktaSettings = new OktaSettings();
            oktaSettings.BaseUri = new Uri(fakeEndpoint);
            oktaSettings.ApiToken = "fakeApiToken";
            SessionsClient sessionsClient = new SessionsClient(oktaSettings);

            // Crate the session url string
            String sessionUrlString = sessionsClient.CreateSessionUrlString(fakeSessionToken, new Uri(fakeRedirect));

            // Check the format
            Assert.AreEqual("http://validurl.com:9999/login/sessionCookieRedirect?token=FakeSessionToken&redirectUrl=https%3A%2F%2Fthis.is.fake%3A42%2Freally%3Freally%3Dtrue%26also%3Dvery%2Btrue", sessionUrlString);
        }