public async void Init(AuthDialog dialogHost)
        {
            this.dialogHost = dialogHost;

            IsLoading      = true;
            LoadingMessage = "Please press Link button on your Hue Bridge within 1 minute... We will discover it automatically for you.";

            try
            {
                var user = await HueAuthClient.RegisterHueBridge();

                AccountManager.SaveUserToVault(user);
                AppGlobalVariables.Users.Add(user);
                Debugger.WriteDebugLog("Successfully discovered Hue bridge " + user.Bridge.Config.BridgeId + " at " + user.Bridge.Config.IpAddress + ".");

                dialogHost.Hide();
            }
            catch (Exception ex)
            {
                Debugger.WriteErrorLog("Failed to add Hue Bridge.", ex);
                var message = new MessageDialog("Failed to discover Hue Bridge. Exception=" + ex.GetType().ToString() + ex.Message);
                await message.ShowAsync();

                dialogHost.Hide();
            }
        }
Пример #2
0
        public async Task <Uri> AcquireAuthorizationCodeAsync(
            Uri authorizationUri,
            Uri redirectUri,
            CancellationToken cancellationToken)
        {
            Uri result = await CoreApplication.MainView.CoreWindow.Dispatcher.RunTaskAsync(async() =>
            {
                var authDialog = new AuthDialog(authorizationUri, redirectUri.AbsoluteUri);
                return(await authDialog.AuthenticateAsync());
            });

            return(result);
        }
Пример #3
0
        private static void Mediator()
        {
            #region Mediator

            var dialog = new AuthDialog();
            dialog.TextboxLogin.Click();
            dialog.TextboxLogin.Keypress();
            dialog.TextboxPassword.Click();
            dialog.TextboxPassword.Keypress();
            dialog.CheckboxRememberMe.Click();
            dialog.ButtonOK.Click();

            #endregion Mediator
        }
Пример #4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CarwashService"/> class.
        /// CarWash Service for accessing the CarWash API.
        /// </summary>
        /// <param name="dc">Dialog context.</param>
        /// <param name="cancellationToken" >(Optional) A <see cref="CancellationToken"/> that can be used by other objects
        /// or threads to receive notice of cancellation.</param>
        internal CarwashService(DialogContext dc, CancellationToken cancellationToken = default(CancellationToken))
        {
            var token = AuthDialog.GetToken(dc, cancellationToken).GetAwaiter().GetResult();

            if (string.IsNullOrEmpty(token))
            {
                throw new AuthenticationException("Not authenticated.");
            }

            _client             = new HttpClient();
            _client.BaseAddress = new Uri("https://carwashu.azurewebsites.net/");
            _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

            _telemetryClient = new TelemetryClient();
        }
        /// <summary>
        /// Post to user.
        /// </summary>
        /// <param name="item">Item activity</param>
        /// <param name="state">State string</param>
        /// <param name="token">Cancellation token</param>
        /// <returns>Awaitable task.</returns>
        protected override async Task PostAsync(IActivity item, string state, CancellationToken token)
        {
            var dialog = new AuthDialog(this.authProvider, this.authOptions);

            _botData.PrivateConversationData.SetValue("AuthenticationStarted", true);

#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
            var interruption = dialog
                               .Do(async(context, result) => context.PrivateConversationData.RemoveValue("AuthenticationStarted"))
                               .ContinueWith(async(context, result) => Chain.Return(item));
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously

            await _dialogTask.Forward(interruption, null, item, token);

            await _dialogTask.PollAsync(token);
        }
Пример #6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CarWashBot"/> class.
        /// </summary>
        /// <param name="accessors">The state accessors for managing bot state.</param>
        /// <param name="botConfig">The parsed .bot config file.</param>
        /// <param name="services">External services.</param>
        /// <param name="loggerFactory">Logger.</param>
        /// <param name="telemetryClient">Telemetry client.</param>
        public CarWashBot(StateAccessors accessors, BotConfiguration botConfig, BotServices services, ILoggerFactory loggerFactory, TelemetryClient telemetryClient)
        {
            _accessors = accessors ?? throw new ArgumentNullException(nameof(accessors));
            if (botConfig == null)
            {
                throw new ArgumentNullException(nameof(botConfig));
            }
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            _telemetryClient = telemetryClient;

            // Verify LUIS configuration.
            if (!services.LuisServices.ContainsKey(LuisConfiguration))
            {
                throw new InvalidOperationException($"Invalid configuration. Please check your '.bot' file for a LUIS service named '{LuisConfiguration}'.");
            }
            _luis = services.LuisServices[LuisConfiguration];

            // Verify QnAMaker configuration.
            if (!services.QnAServices.ContainsKey(QnAMakerConfiguration))
            {
                throw new ArgumentException($"Invalid configuration. Please check your '.bot' file for a QnA service named '{QnAMakerConfiguration}'.");
            }
            _qna = services.QnAServices[QnAMakerConfiguration];

            // Verify Storage configuration.
            if (!services.StorageServices.ContainsKey(StorageConfiguration))
            {
                throw new ArgumentException($"Invalid configuration. Please check your '.bot' file for a Storage service named '{StorageConfiguration}'.");
            }
            _storage = services.StorageServices[StorageConfiguration];

            Dialogs = new DialogSet(_accessors.DialogStateAccessor);
            Dialogs.Add(new NewReservationDialog(_accessors.NewReservationStateAccessor, telemetryClient));
            Dialogs.Add(new ConfirmDropoffDialog(_accessors.ConfirmDropoffStateAccessor, telemetryClient));
            Dialogs.Add(new CancelReservationDialog(_accessors.CancelReservationStateAccessor, telemetryClient));
            Dialogs.Add(new FindReservationDialog(telemetryClient));
            Dialogs.Add(new NextFreeSlotDialog(telemetryClient));
            Dialogs.Add(new AuthDialog(accessors.UserProfileAccessor, _storage, telemetryClient));
            Dialogs.Add(AuthDialog.LoginPromptDialog());

            // Dialogs.Add(FormDialog.FromForm(NewReservationForm.BuildForm));
        }
Пример #7
0
        public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> item)
        {
            var message = await item;

            var options = new AuthenticationOptions
            {
                ClientId     = ConfigurationManager.AppSettings["aad:ClientId"],
                ClientSecret = ConfigurationManager.AppSettings["aad:ClientSecret"],
                RedirectUrl  = ConfigurationManager.AppSettings["aad:Callback"],

                Authority = ConfigurationManager.AppSettings["aad:Authority"],
                Scopes    = new[] { ConfigurationManager.AppSettings["aad:Scopes"] }
            };

            var authDialog = new AuthDialog(authProvider, options);

            await context.Forward(authDialog, AuthenticationResumeAfterAsync, message, CancellationToken.None);
        }
Пример #8
0
        private static string getAuthorizationCodeCore(string authUrl)
        {
            string authCode = "";

            // Thread umjesto taskova tako da mozemo apartment state postaviti
            // inace ce web kontrola pucati
            Thread thread = new Thread(() =>
            {
                using (var authForm = new AuthDialog())
                {
                    authForm.NavigateTo(authUrl);
                    authForm.ShowDialog();
                    authCode = authForm.AuthorizationCode;
                }
            });

            thread.IsBackground = true;
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();
            return(authCode);
        }
Пример #9
0
 /// <summary>
 /// Initializes a new instance of the <see cref="WashStartedMessage"/> class.
 /// </summary>
 /// <param name="configuration">CarWash app configuration.</param>
 /// <param name="accessors">The state accessors for managing bot state.</param>
 /// <param name="adapterIntegration">The <see cref="BotFrameworkAdapter"/> connects the bot to the service endpoint of the given channel.</param>
 /// <param name="env">Provides information about the web hosting environment an application is running in.</param>
 /// <param name="services">External services.</param>
 public WashStartedMessage(CarWashConfiguration configuration, StateAccessors accessors, IAdapterIntegration adapterIntegration, IHostingEnvironment env, BotServices services)
     : base(accessors, adapterIntegration, env, services, configuration.ServiceBusQueues.BotWashStartedQueue, new Dialog[] { AuthDialog.LoginPromptDialog(), new FindReservationDialog() })
 {
 }
Пример #10
0
 public void Init(AuthDialog dialogHost)
 {
     this.dialogHost = dialogHost;
 }
Пример #11
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CarWashCommentLeftMessage"/> class.
 /// </summary>
 /// <param name="configuration">CarWash app configuration.</param>
 /// <param name="accessors">The state accessors for managing bot state.</param>
 /// <param name="adapterIntegration">The <see cref="BotFrameworkAdapter"/> connects the bot to the service endpoint of the given channel.</param>
 /// <param name="env">Provides information about the web hosting environment an application is running in.</param>
 /// <param name="services">External services.</param>
 /// <param name="telemetryClient">Telemetry client.</param>
 public CarWashCommentLeftMessage(CarWashConfiguration configuration, StateAccessors accessors, IAdapterIntegration adapterIntegration, IHostingEnvironment env, BotServices services, TelemetryClient telemetryClient)
     : base(accessors, adapterIntegration, env, services, configuration.ServiceBusQueues.BotCarWashCommentLeftQueue, new Dialog[] { AuthDialog.LoginPromptDialog(), new FindReservationDialog(telemetryClient) }, telemetryClient)
 {
     _telemetryClient = telemetryClient;
 }
Пример #12
0
        public void Run()
        {
            var dialog = new AuthDialog();

            dialog.Start();
        }
Пример #13
0
        public AuthData ShowAuthDialog()
        {
            Trace.WriteLine("Entering RTCPresence.ShowAuthDialog");

            AuthDialog dlg = new AuthDialog();

            if (dlg.ShowDialog() == DialogResult.OK )
            {
                AuthData authData = new AuthData();

                authData.Uri = dlg.Uri;
                authData.Account = dlg.Account;
                authData.Password = dlg.Password;

                return authData;
            }

            return null;
        }
Пример #14
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            SetContentView(Resource.Layout.activity_main);

            Android.Support.V7.Widget.Toolbar toolbar = FindViewById <Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
            SetSupportActionBar(toolbar);

            //Создаем адаптер для отображения
            var lvTasks = FindViewById <ListView>(Resource.Id.lvTasks);

            tasklist        = new TaskListAdapter(this, UpdateTasks(true));
            lvTasks.Adapter = tasklist;

            // Initialize the "storage"
            Storage.Instance.Init();


            FloatingActionButton fab = FindViewById <FloatingActionButton>(Resource.Id.fab);

            fab.Click += FabOnClick;
            FloatingActionButton fabNext = FindViewById <FloatingActionButton>(Resource.Id.fabNextPage);
            FloatingActionButton fabPrev = FindViewById <FloatingActionButton>(Resource.Id.fabPrevPage);

            fabNext.Click     += FabNext_Click;
            fabPrev.Click     += FabPrev_Click;
            fabPrev.Visibility = ViewStates.Invisible;

            RadioButton rb = FindViewById <RadioButton>(Resource.Id.rbSortId);

            rb.Click += Rb_Click;
            rb        = FindViewById <RadioButton>(Resource.Id.rbSortUsename);
            rb.Click += Rb_Click;
            rb        = FindViewById <RadioButton>(Resource.Id.rbSortEmail);
            rb.Click += Rb_Click;
            rb        = FindViewById <RadioButton>(Resource.Id.rbSortStatus);
            rb.Click += Rb_Click;

            lvTasks.ItemClick += LvTasks_Click;

            // Instance dialogs and set actions when hiding dialogs
            authDialog = new AuthDialog(this);
            authDialog.OnHide(() => { // When hiding the authorization dialog, we check whether it has been completed. And if so, change the menu items
                if (!string.IsNullOrEmpty(Storage.Instance.GetToken()))
                {
                    mnuAuth.SetVisible(false);
                    mnuLogoff.SetVisible(true);
                }
            });
            taskEditDialog = new TaskEditDialog(this);
            taskEditDialog.OnHide((modified) => { // When hiding the dialog, we update the task list data if there are changes.
                if (modified)
                {
                    if (taskEditDialog.IsNewItem) // If we created a new task, then reload the data with the current sorting parameters.
                    {
                        tasklist.ListSource = UpdateTasks(false) ?? tasklist.ListSource;
                    }
                    tasklist.NotifyDataSetChanged();
                }
            });
        }
Пример #15
0
 /// <summary>
 /// Initializes a new instance of the <see cref="VehicleArrivedMessage"/> class.
 /// </summary>
 /// <param name="configuration">CarWash app configuration.</param>
 /// <param name="accessors">The state accessors for managing bot state.</param>
 /// <param name="adapterIntegration">The <see cref="BotFrameworkAdapter"/> connects the bot to the service endpoint of the given channel.</param>
 /// <param name="env">Provides information about the web hosting environment an application is running in.</param>
 /// <param name="services">External services.</param>
 /// <param name="telemetryClient">Telemetry client.</param>
 public VehicleArrivedMessage(CarWashConfiguration configuration, StateAccessors accessors, IAdapterIntegration adapterIntegration, IHostingEnvironment env, BotServices services, TelemetryClient telemetryClient)
     : base(accessors, adapterIntegration, env, services, configuration.ServiceBusQueues.BotVehicleArrivedNotificationQueue, new Dialog[] { AuthDialog.LoginPromptDialog(), new FindReservationDialog(telemetryClient) }, telemetryClient)
 {
 }
Пример #16
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            SetContentView(Resource.Layout.activity_main);

            Android.Support.V7.Widget.Toolbar toolbar = FindViewById <Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
            SetSupportActionBar(toolbar);

            //Создаем адаптер для отображения
            var lvTasks = FindViewById <ListView>(Resource.Id.lvTasks);

            tasklist        = new TaskListAdapter(this, UpdateTasks(true));
            lvTasks.Adapter = tasklist;

            //Инициализируем "хранилище"
            Storage.Instance.Init();

            //Вешаем обработчики событий
            FloatingActionButton fab = FindViewById <FloatingActionButton>(Resource.Id.fab);

            fab.Click += FabOnClick;
            FloatingActionButton fabNext = FindViewById <FloatingActionButton>(Resource.Id.fabNextPage);
            FloatingActionButton fabPrev = FindViewById <FloatingActionButton>(Resource.Id.fabPrevPage);

            fabNext.Click     += FabNext_Click;
            fabPrev.Click     += FabPrev_Click;
            fabPrev.Visibility = ViewStates.Invisible; //Скрываем кнопку предидущей страницы, т.к. стартуем на первой странице.

            RadioButton rb = FindViewById <RadioButton>(Resource.Id.rbSortId);

            rb.Click += Rb_Click;
            rb        = FindViewById <RadioButton>(Resource.Id.rbSortUsename);
            rb.Click += Rb_Click;
            rb        = FindViewById <RadioButton>(Resource.Id.rbSortEmail);
            rb.Click += Rb_Click;
            rb        = FindViewById <RadioButton>(Resource.Id.rbSortStatus);
            rb.Click += Rb_Click;

            lvTasks.ItemClick += LvTasks_Click;

            //Инстансим диалоги и задаем действия при скрытии диалогов
            authDialog = new AuthDialog(this);
            authDialog.OnHide(() => { //При скрытии диалога авторизации проверяем была ли она выполнена. И если да, то меняем пункты меню
                if (!string.IsNullOrEmpty(Storage.Instance.GetToken()))
                {
                    mnuAuth.SetVisible(false);
                    mnuLogoff.SetVisible(true);
                }
            });
            taskEditDialog = new TaskEditDialog(this);
            taskEditDialog.OnHide((modified) => { //При скрытии диалога выполняем обновление данных списка задач в случае наличия изменений.
                if (modified)
                {
                    if (taskEditDialog.IsNewItem) //Если создали новую задачу, тогда перезагружаем данные с текущими параметрами сортировки.
                    {
                        tasklist.ListSource = UpdateTasks(false) ?? tasklist.ListSource;
                    }
                    tasklist.NotifyDataSetChanged();
                }
            });
        }