示例#1
0
 public Deferral GetDeferral()
 {
     var tcs = new TaskCompletionSource<object>();
     var deferral = new Deferral(() => tcs.SetResult(null));
     _taskCompletionSources.Add(tcs);
     return deferral;
 }
        public void OnCameraAdded(
            HolographicSpace sender,
            HolographicSpaceCameraAddedEventArgs args
            )
        {
            Deferral deferral = args.GetDeferral();
            HolographicCamera holographicCamera = args.Camera;

            Task task1 = new Task(() =>
            {
                //
                // TODO: Allocate resources for the new camera and load any content specific to
                //       that camera. Note that the render target size (in pixels) is a property
                //       of the HolographicCamera object, and can be used to create off-screen
                //       render targets that match the resolution of the HolographicCamera.
                //

                // Create device-based resources for the holographic camera and add it to the list of
                // cameras used for updates and rendering. Notes:
                //   * Since this function may be called at any time, the AddHolographicCamera function
                //     waits until it can get a lock on the set of holographic camera resources before
                //     adding the new camera. At 60 frames per second this wait should not take long.
                //   * A subsequent Update will take the back buffer from the RenderingParameters of this
                //     camera's CameraPose and use it to create the ID3D11RenderTargetView for this camera.
                //     Content can then be rendered for the HolographicCamera.
                deviceResources.AddHolographicCamera(holographicCamera);

                // Holographic frame predictions will not include any information about this camera until
                // the deferral is completed.
                deferral.Complete();
            });
            task1.Start();
        }
        private async void SystemNavigationManager_CloseRequested(object sender, SystemNavigationCloseRequestedPreviewEventArgs e)
        {
            Deferral            deferral = e.GetDeferral();
            ConfirmCloseDialog  dlg      = new ConfirmCloseDialog();
            ContentDialogResult result   = await dlg.ShowAsync();

            if (result == ContentDialogResult.Secondary)
            {
                // user cancelled the close operation
                e.Handled = true;
                deferral.Complete();
            }
            else
            {
                switch (dlg.Result)
                {
                case CloseAction.Terminate:
                    e.Handled = false;
                    deferral.Complete();
                    break;

                case CloseAction.Systray:
                    if (ApiInformation.IsApiContractPresent(
                            "Windows.ApplicationModel.FullTrustAppContract", 1, 0))
                    {
                        await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync();
                    }
                    e.Handled = false;
                    deferral.Complete();
                    break;
                }
            }
        }
        // This event handler for server certificate validation executes synchronously as part of the SSL/TLS handshake.
        // An app should not perform lengthy operations inside this handler. Otherwise, the remote server may terminate the connection abruptly.
        private async void MyCustomServerCertificateValidator(HttpBaseProtocolFilter sender, HttpServerCustomValidationRequestedEventArgs args)
        {
            // Get the server certificate and certificate chain from the args parameter.
            Certificate serverCert = args.ServerCertificate;
            IReadOnlyList <Certificate> serverCertChain = args.ServerIntermediateCertificates;

            // To illustrate the use of async APIs, we use the IsCertificateValidAsync method.
            // In order to call async APIs in this handler, you must first take a deferral and then
            // release it once you are done with the operation. The "using" statement
            // ensures that the deferral completes when control leaves the method.
            using (Deferral deferral = args.GetDeferral())
            {
                try
                {
                    bool isCertificateValid = await IsCertificateValidAsync(serverCert);

                    if (!isCertificateValid)
                    {
                        args.Reject();
                    }
                }
                catch
                {
                    // If we get an exception from IsCertificateValidAsync, we reject the certificate
                    // (secure by default).
                    args.Reject();
                }
            }
        }
        private void OnEnteredBackground(object sender, EnteredBackgroundEventArgs e)
        {
            Debug.WriteLine("Entering Background: " + e);
            Deferral deferral = e.GetDeferral();

            deferral.Complete();
        }
示例#6
0
        // Helper function for async Read callback
        protected virtual async void Characteristic_ReadRequested(
            GattLocalCharacteristic sender,
            GattReadRequestedEventArgs args,
            Deferral deferral = null
            )
        {
            Debug.WriteLine($"base.Characteristic_ReadRequested Entry");

            // Get an event deferral for async operations if we don't have one
            if (deferral == null)
            {
                deferral = args.GetDeferral();
            }

            //
            // Normally, GetRequestAsync() is recommended to run on a UI thread
            // because, even with paired devices, the device may prompt the
            // user for consent. But, we're running in a background service so
            // we won't run this on a UI thread. According to one of the devs
            // on the core Bluetooth team, because this is for a "test
            // application," consent prompts are not currently part of MS's
            // policy and it will be auto-accepted.
            //
            var request = await args.GetRequestAsync();

            request.RespondWithValue(Value);
            Debug.WriteLine($"Characteristic ReadRequested- Length: " +
                            $"{request.Length}, State: {request.State}, " +
                            $"Offset: {request.Offset}"
                            );

            deferral.Complete();

            Debug.WriteLine("base.Characteristic_ReadRequested Exit");
        }
示例#7
0
        private async void Close_Requested(object sender, SystemNavigationCloseRequestedPreviewEventArgs e)
        {
            Deferral deferral = e.GetDeferral();

            ContentDialog exitDialog = new ContentDialog
            {
                Title               = "Exit?",
                Content             = "Have you saved your latest Changes? They otherwise will be lost forever!",
                CloseButtonText     = "Cancel",
                PrimaryButtonText   = "Save",
                SecondaryButtonText = "Exit",
                DefaultButton       = ContentDialogButton.Secondary
            };

            ContentDialogResult result = await exitDialog.ShowAsync();

            if (result == ContentDialogResult.Primary)
            {
                e.Handled = true;
                Save_Click(null, null);
            }
            else if (result != ContentDialogResult.Secondary)
            {
                e.Handled = true;
            }

            deferral.Complete();
        }
示例#8
0
        public void OnTeachingTipClosing(TeachingTip sender, TeachingTipClosingEventArgs args)
        {
            if (lstTeachingTipEvents != null)
            {
                lstTeachingTipEvents.Items.Add(lstTeachingTipEvents.Items.Count.ToString() + ") " + args.ToString() + " Reason: " + args.Reason.ToString());
                lstTeachingTipEvents.ScrollIntoView(lstTeachingTipEvents.Items.Last <object>());
            }

            CheckBox cancelClosesCheckBox = null;

            if (sender == TeachingTipInResources)
            {
                cancelClosesCheckBox = CancelClosesCheckBoxInResources;
            }
            else
            {
                cancelClosesCheckBox = CancelClosesCheckBoxInVisualTree;
            }

            if (cancelClosesCheckBox != null && cancelClosesCheckBox.IsChecked == true)
            {
                deferral       = args.GetDeferral();
                args.Cancel    = true;
                timer          = new DispatcherTimer();
                timer.Tick    += Timer_Tick;
                timer.Interval = new TimeSpan(0, 0, 1);
                timer.Start();
            }
        }
        BuildExpressionFactoryRecursively(Boolean directlyToTheRightOfABinaryOperator)
        {
            var binaryOperatorExpressionFactory =
                Synthesis.Create(
                    Deferral.Create(
                        () =>
                        BuildExpressionFactoryRecursively(
                            directlyToTheRightOfABinaryOperator)),
                    Deferral.Create(() => BuildExpressionFactoryRecursively(true)),
                    BinaryOperatorFactory, BinaryExpressionFrom);

            var negatedExpressionFactory =
                Synthesis.Create(
                    Deferral.Create(() => BuildExpressionFactoryRecursively(true)),
                    expression =>
                    Tuple.Create(expression.Item1,
                                 String.Format(
                                     directlyToTheRightOfABinaryOperator ? "(-{0})" : "-{0}",
                                     expression.Item2)));

            var bracketedExpressionFactory =
                Synthesis.Create(
                    Deferral.Create(() => BuildExpressionFactoryRecursively(false)),
                    expression =>
                    Tuple.Create(false, String.Format("({0})", expression.Item2)));

            return
                (Interleaving.Create(new[]
            {
                ConstantFactory, binaryOperatorExpressionFactory,
                negatedExpressionFactory, bracketedExpressionFactory
            }));
        }
示例#10
0
        public static async void HandlePairing(CoreDispatcher dispatcher, DevicePairingRequestedEventArgs args)
        {
            using (Deferral deferral = args.GetDeferral())
            {
                switch (args.PairingKind)
                {
                case DevicePairingKinds.DisplayPin:
                    await ShowPinToUserAsync(dispatcher, args.Pin);

                    args.Accept();
                    break;

                case DevicePairingKinds.ConfirmOnly:
                    args.Accept();
                    break;

                case DevicePairingKinds.ProvidePin:
                {
                    string pin = await GetPinFromUserAsync(dispatcher);

                    if (String.IsNullOrEmpty(pin))
                    {
                        args.Accept(pin);
                    }
                }
                break;
                }
            }
        }
        private async void OnServerCustomValidationRequested(StreamWebSocket sender, WebSocketServerCustomValidationRequestedEventArgs args)
        {
            // In order to call async APIs in this handler, you must first take a deferral and then
            // release it once you are done with the operation. The "using" statement
            // ensures that the deferral completes when control leaves the block.
            bool isValid;

            using (Deferral deferral = args.GetDeferral())
            {
                // Get the server certificate and certificate chain from the args parameter.
                isValid = await MainPage.AreCertificateAndCertChainValidAsync(args.ServerCertificate, args.ServerIntermediateCertificates);

                if (!isValid)
                {
                    args.Reject();
                }
            }

            // Continue on the UI thread so we can update UI.
            var task = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                if (isValid)
                {
                    AppendOutputLine("Custom validation of server certificate passed.");
                }
                else
                {
                    AppendOutputLine("Custom validation of server certificate failed.");
                }
            });
        }
示例#12
0
        /// <summary>
        /// Handle the Print Task Setup Event
        /// Raised when the source app sets the Print Ticket. This event provides a callback method for the app to signal it is done handling this event
        /// and optionally specifying the need for UI, which will cause the UI part of this App to be launched in OnActivated() with ActivationKind.PrintWorkflowForegroundTask .
        /// </summary>
        /// <param name="sessionManager">Session manager</param>
        /// <param name="printTaskSetupArgs">Has the Configuration, which include the PrintTicket, and other information</param>
        private void OnSetupRequested(PrintWorkflowBackgroundSession sessionManager, PrintWorkflowBackgroundSetupRequestedEventArgs printTaskSetupArgs)
        {
            // Request a deferral if any of the calls here might result in an Async method being called
            Deferral setupRequestedDeferral = printTaskSetupArgs.GetDeferral();

            // Get information about the source application, print job title, and session ID
            string sourceApplicationName = printTaskSetupArgs.Configuration.SourceAppDisplayName;
            string jobTitle  = printTaskSetupArgs.Configuration.JobTitle;
            string sessionId = printTaskSetupArgs.Configuration.SessionId;

            // Check to see if user wanted to use the watermark already when the program was run "standalone" and saved in local storage
            // and not have UI every time. It can always be reset by running the app again and unchecking the check box
            localStorage = new LocalStorageUtilities();
            suppressUI   = localStorage.GetUseStandaloneSettings();
            if (!suppressUI)
            {
                // Indicate that we need to launch the UI, in this example, because we need to get watermarking text, and optionally an image
                printTaskSetupArgs.SetRequiresUI();
                // Set storage prefix so that foreground and background can pass properties
                string localStorageVariablePrefix = string.Format("{0}::", sessionId.Substring(0, 8));
                localStorage.SetStorageKeyPrefix(localStorageVariablePrefix);
            }
            else
            {
                // Use unprefixed default values set in "standalone" mode, without showing UI when activated in workflow mode
                localStorage.SetStorageKeyPrefix("");
            }

            // Complete the deferral taken out at the start of OnSetupRequested
            setupRequestedDeferral.Complete();
        }
示例#13
0
        public ActionResult Index()
        {
            ApplicationUser currentUser = (from u in _context.Users
                                           where u.UserName == User.Identity.Name
                                           select u).FirstOrDefault();

            LeaveList list = new LeaveList();

            list.Holidays = _context.PublicHoliday.ToList();

            list.UserLeaves = (from u in _context.Users
                               where u.Manager.Id == currentUser.Id
                               select new UserLeave()
            {
                UserID = u.Id,
                Leaves = (from tbl in _context.Leave where tbl.User.Id == u.Id select tbl).ToList(),
                Name = u.FullName,
                EmploymentStartDate = u.EmploymentStartDate
            }).ToList();

            List <UserLeave> subLeaves = (from u in _context.Users
                                          where u.Manager.Manager.Id == currentUser.Id
                                          select new UserLeave()
            {
                UserID = u.Id,
                Leaves = (from tbl in _context.Leave where tbl.User.Id == u.Id select tbl).ToList(),
                Name = u.FullName,
                EmploymentStartDate = u.EmploymentStartDate
            }).ToList();

            list.UserLeaves.AddRange(subLeaves);

            list.Leaves = _context.Leave.Where(tbl => tbl.User.Id == currentUser.Id).ToList();

            list.Leaves = Deferral.AddDeferral(list.Leaves, list.Holidays);
            list.Leaves = Accrual.AddAccrual(currentUser.EmploymentStartDate, currentUser.FullName, list.Leaves);

            foreach (UserLeave userLeave in list.UserLeaves)
            {
                userLeave.Leaves = Deferral.AddDeferral(userLeave.Leaves, list.Holidays);
                userLeave.Leaves = Accrual.AddAccrual(userLeave.EmploymentStartDate, userLeave.Name, userLeave.Leaves);
            }

            list.FormModel = new LeaveFormModel()
            {
                StartDate     = DateTime.Now.Date,
                EndDate       = DateTime.Now.Date,
                UserID        = currentUser.Id,
                RequestDate   = DateTime.Now,
                LeaveStateID  = 1,
                Note          = "",
                Attachement   = "",
                Institution   = "",
                StudentNumber = ""
            };

            ViewBag.LeaveStateID = new SelectList(_context.LeaveState, "LeaveStateID", "Description", 1);

            return(View(list));
        }
示例#14
0
        private async void SystemNavigationManager_CloseRequested(object sender, SystemNavigationCloseRequestedPreviewEventArgs e)
        {
            Deferral      deferral = e.GetDeferral();
            ContentDialog dlg      = new ContentDialog()
            {
                Title = "Do you really want to exit the application?", PrimaryButtonText = "Yes", SecondaryButtonText = "No"
            };
            ContentDialogResult result = await dlg.ShowAsync();

            if (result == ContentDialogResult.Secondary)
            {
                // user cancelled the close operation
                e.Handled = true;
                deferral.Complete();
            }
            else
            {
                if (Connection != null)
                {
                    ValueSet message = new ValueSet();
                    message.Add("InterCommunication", JsonSerializer.Serialize(new Common.InterCommunication()
                    {
                        InterCommunicationType = InterCommunicationType.Exit
                    }));
                    await Connection.SendMessageAsync(message);
                }
                e.Handled = false;
                deferral.Complete();
            }
        }
        private async void SystemNavigationManager_CloseRequested(object sender, SystemNavigationCloseRequestedPreviewEventArgs e)
        {
            int      closeNum = 1;
            Deferral deferral = e.GetDeferral();

            if (false)
            {
                // user cancelled the close operation
                e.Handled = true;
                deferral.Complete();
            }
            else
            {
                switch (closeNum)
                {
                case 0:
                    e.Handled = false;
                    deferral.Complete();
                    break;

                case 1:
                    if (ApiInformation.IsApiContractPresent(
                            "Windows.ApplicationModel.FullTrustAppContract", 1, 0))
                    {
                        await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync();
                    }
                    e.Handled = false;
                    deferral.Complete();
                    break;
                }
            }
        }
示例#16
0
 /// <inheritdoc/>
 public void StartDeferral()
 {
     if (Deferral == null)
     {
         Deferral = GetDeferral();
     }
 }
示例#17
0
        private void OnEnteredBackground(object sender, EnteredBackgroundEventArgs e)
        {
            Deferral deferral = e.GetDeferral();

            IsForeground = false;
            NotificationSystem.RefreshCallNotification(CallSystem.CallManager.CurrentCalls);
            deferral.Complete();
        }
示例#18
0
        // X 버튼 누르시에 할 일을 추가해야함
        private void SystemNavigationManager_CloseRequested(object sender, SystemNavigationCloseRequestedPreviewEventArgs e)
        {
            Deferral deferral = e.GetDeferral();


            e.Handled = false;
            deferral.Complete();
        }
示例#19
0
        /// <summary>
        /// Adds an outstanding deferral to the internal deferral tracker such that
        /// <see cref="DeferAsync"/> will not complete until this deferral does.
        /// </summary>
        /// <returns></returns>
        public Deferral GetDeferral()
        {
            TaskCompletionSource <bool> deferralCompletion = new TaskCompletionSource <bool>();
            Deferral deferral = new Deferral(() => deferralCompletion.SetResult(true));

            this.deferralCompletions.Add(deferralCompletion);
            return(deferral);
        }
示例#20
0
        private void OnLeavingBackground(object sender, LeavingBackgroundEventArgs e)
        {
            Deferral deferral = e.GetDeferral();

            IsForeground = true;
            NotificationSystem.RemoveCallToastNotifications();
            deferral.Complete();
        }
示例#21
0
        public Deferral GetDeferral()
        {
            var tcs      = new TaskCompletionSource <object>();
            var deferral = new Deferral(() => tcs.SetResult(null));

            _taskCompletionSources.Add(tcs);
            return(deferral);
        }
示例#22
0
        private async void OnAppWindowCloseRequested(AppWindow sender, AppWindowCloseRequestedEventArgs e)
        {
            Deferral deferral = e.GetDeferral();

            e.Cancel = !await ViewModel.TryCloseAsync();

            deferral.Complete();
        }
示例#23
0
        private async void RefreshContainer_RefreshRequested(RefreshContainer sender, RefreshRequestedEventArgs e)
        {
            Deferral deferral = e.GetDeferral();

            await ViewModel.RefreshAsync();

            deferral.Complete();
        }
示例#24
0
 /// <summary>
 /// Gets a deferral. The deferral is complete when disposed.
 /// </summary>
 /// <returns>The deferral.</returns>
 public IDisposable GetDeferral()
 {
     if (_count == null)
         _count = new AsyncCountdownEvent(1);
     var ret = new Deferral(_count);
     _count.AddCount();
     return ret;
 }
示例#25
0
        /// <summary>
        /// Read request callback to update the value
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        protected override async void Characteristic_ReadRequested(GattLocalCharacteristic sender, GattReadRequestedEventArgs args)
        {
            Deferral deferral = args.GetDeferral();

            Debug.WriteLine($"MSFTLongReadCharacteristic: ReadRequested - MaxPduSize {args.Session.MaxPduSize}");
            await UpdateValue(args);

            base.Characteristic_ReadRequested(sender, args, deferral);
        }
示例#26
0
 /// <inheritdoc/>
 public void EndDeferral()
 {
     if (Deferral != null)
     {
         Deferral.Complete();
         Dispose();
         Deferral = null;
     }
 }
 private void WorkListBox_RefreshRequested(object sender, Controls.RefreshRequestedEventArgs e)
 {
     using (Deferral deferral = WorkListBox.AutoRefresh ? e.GetDeferral() : null)
     {
         galleries.Clear();
         ListProgressBar.Visibility = Visibility.Visible;
         LoadGalleries();
     }
 }
示例#28
0
        private async void OnCloseRequested(object sender, SystemNavigationCloseRequestedPreviewEventArgs e)
        {
            Deferral deferral = e.GetDeferral();

            e.Handled = await ViewModel.TabViewManager.TabViewManager.MainTabView.GetUnclosableTabsAsync().CountAsync() > 0 ||
                        await ViewModel.TabViewManager.TabViewManager.SolutionExplorerTabView.GetUnclosableTabsAsync().CountAsync() > 0;

            deferral.Complete();
        }
示例#29
0
 void CompleteRefresh()
 {
     if (_refreshCompletionDeferral != null)
     {
         _refreshCompletionDeferral.Complete();
         _refreshCompletionDeferral.Dispose();
         _refreshCompletionDeferral = null;
     }
 }
示例#30
0
 private void WorkCompletedForMemory()
 {
     if (this.RefreshCompletionDeferralForMemory != null)
     {
         this.RefreshCompletionDeferralForMemory.Complete();
         this.RefreshCompletionDeferralForMemory.Dispose();
         this.RefreshCompletionDeferralForMemory = null;
     }
 }
示例#31
0
        private async void CustomPairInfo_PairingRequested(DeviceInformationCustomPairing sender, DevicePairingRequestedEventArgs args)
        {
            Deferral PairDeferral = args.GetDeferral();

            try
            {
                PairConfirmaion = new TaskCompletionSource <bool>();

                switch (args.PairingKind)
                {
                case DevicePairingKinds.ConfirmPinMatch:
                {
                    await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                        {
                            Tips.Text             = $"{Globalization.GetString("BluetoothUI_Tips_Text_5")}{Environment.NewLine}{args.Pin}";
                            Tips.Visibility       = Visibility.Visible;
                            PinConfirm.Visibility = Visibility.Visible;
                            PinRefuse.Visibility  = Visibility.Visible;
                        });

                    if (await PairConfirmaion.Task)
                    {
                        args.Accept(args.Pin);
                    }

                    break;
                }

                case DevicePairingKinds.ConfirmOnly:
                {
                    await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                        {
                            Tips.Text             = Globalization.GetString("BluetoothUI_Tips_Text_6");
                            Tips.Visibility       = Visibility.Visible;
                            PinConfirm.Visibility = Visibility.Visible;
                            PinRefuse.Visibility  = Visibility.Visible;
                        });

                    if (await PairConfirmaion.Task)
                    {
                        args.Accept();
                    }

                    break;
                }
                }
            }
            catch (Exception ex)
            {
                LogTracer.Log(ex, $"An exception was threw in {nameof(CustomPairInfo_PairingRequested)}, pair with bluetooth failed");
            }
            finally
            {
                PairDeferral.Complete();
            }
        }
示例#32
0
        /// <summary>
        /// Called when a custom pairing is initiated so that we can handle its custom ceremony
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        public async void PairingRequestedHandlerAsync(DeviceInformationCustomPairing sender, DevicePairingRequestedEventArgs args)
        {
            LogService.Write((Enum.GetName(typeof(DevicePairingKinds), args.PairingKind)), LoggingLevel.Information);

            BluetoothDeviceInfo currentDevice = new BluetoothDeviceInfo(args.DeviceInformation);

            // Save the args for use in ProvidePin case
            _pairingRequestedArgs = args;

            // Save the deferral away and complete it where necessary.
            if (args.PairingKind != DevicePairingKinds.DisplayPin)
            {
                _deferral = args.GetDeferral();
            }

            switch (args.PairingKind)
            {
            // Windows itself will pop the confirmation dialog as part of "consent" depending on which operating OS is running
            case DevicePairingKinds.ConfirmOnly:
            {
                var confirmationMessage = string.Format(BluetoothConfirmOnlyText, args.DeviceInformation.Name, args.DeviceInformation.Id);
                if (await DisplayMessagePanel(confirmationMessage, MessageType.InformationalMessage))
                {
                    AcceptPairing();
                }
            }
            break;

            // We only show the PIN on this side. The ceremony is actually completed when the user enters the PIN on the target device.
            case DevicePairingKinds.DisplayPin:
            {
                var confirmationMessage = string.Format(BluetoothDisplayPINText, args.Pin);
                await DisplayMessagePanel(confirmationMessage, MessageType.OKMessage);
            }
            break;

            // A PIN may be shown on the target device and the user needs to enter the matching PIN on the originating device.
            case DevicePairingKinds.ProvidePin:
            {
                _inProgressPairButton.Flyout = _savedPairButtonFlyout;
                _inProgressPairButton.Flyout.ShowAt(_inProgressPairButton);
            }
            break;

            // We show the PIN here and the user responds with whether the PIN matches what is displayed on the target device.
            case DevicePairingKinds.ConfirmPinMatch:
            {
                var confirmationMessage = string.Format(BluetoothConfirmPINMatchText, args.Pin);
                if (await DisplayMessagePanel(confirmationMessage, MessageType.YesNoMessage))
                {
                    AcceptPairing();
                }
            }
            break;
            }
        }