示例#1
0
 public void engine(int val)
 {
     if (val != engineStatus && (limitReached == 0 || limitReached != val))
     {
         this.UseWaitCursor = true;
         if (val == 0 || engineStatus != 0)
         {
             int prevDir = engineStatus;
             if (currentConnection.deviceType == 0)
             {
                 toggleLine(currentTemplate.engineLines[prevDir][1], 0);
                 this.Invoke((MethodInvoker) delegate
                 {
                     if (slCalibration.Text != "Концевик" || !slCalibration.Visible)
                     {
                         slCalibration.Text    = "Остановка";
                         slCalibration.Visible = true;
                     }
                 });
                 if (engineTaskActive)
                 {
                     engineTaskCTS.Cancel();
                     try
                     {
                         engineTask.Wait();
                     }
                     catch (AggregateException) { }
                 }
                 engineTaskActive = true;
                 pMap.Enabled     = false;
                 engineTask       = TaskEx.Run(
                     async() =>
                 {
                     await TaskEx.Delay(currentConnection.switchIntervals[1] * 1000);
                     toggleLine(currentTemplate.engineLines[prevDir][0], 0);
                     clearEngineTask();
                 });
             }
             else if (currentConnection.deviceType == 1)
             {
                 toggleLine(currentTemplate.engineLines[prevDir][0], 0);
             }
         }
         if (val != 0 && !engineTaskActive)
         {
             if (currentConnection.deviceType == 0)
             {
                 toggleLine(currentTemplate.engineLines[val][0], 1);
                 pMap.Enabled = false;
                 this.Invoke((MethodInvoker) delegate
                 {
                     if (slCalibration.Text != "Концевик" || !slCalibration.Visible)
                     {
                         slCalibration.Text    = "Пуск";
                         slCalibration.Visible = true;
                     }
                 });
                 engineTaskActive = true;
                 CancellationToken ct = engineTaskCTS.Token;
                 engineTask = TaskEx.Run(
                     async() =>
                 {
                     await TaskEx.Delay(currentConnection.switchIntervals[0] * 1000, ct);
                     if (!ct.IsCancellationRequested)
                     {
                         toggleLine(currentTemplate.engineLines[val][1], 1);
                     }
                     clearEngineTask();
                 }, ct);
                 if (limitReached != 0 && !currentConnection.hwLimits)
                 {
                     offLimit();
                 }
             }
             else if (currentConnection.deviceType == 1)
             {
                 toggleLine(currentTemplate.engineLines[val][0], 1);
             }
         }
         engineStatus = val;
         if (!engineTaskActive)
         {
             UseWaitCursor = false;
         }
     }
 }
示例#2
0
        /// <summary>
        /// The Create Cloud Service operation creates a Windows Azure cloud
        /// service in a Windows Azure subscription.
        /// </summary>
        /// <param name='parameters'>
        /// Required. Parameters used to specify how the Create procedure will
        /// function.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response body contains the status of the specified asynchronous
        /// operation, indicating whether it has succeeded, is inprogress, or
        /// has failed. Note that this status is distinct from the HTTP status
        /// code returned for the Get Operation Status operation itself.  If
        /// the asynchronous operation succeeded, the response body includes
        /// the HTTP status code for the successful request.  If the
        /// asynchronous operation failed, the response body includes the HTTP
        /// status code for the failed request, and also includes error
        /// information regarding the failure.
        /// </returns>
        public async System.Threading.Tasks.Task <OperationStatusResponse> CreateAsync(CloudServiceCreateParameters parameters, CancellationToken cancellationToken)
        {
            StoreManagementClient client = this.Client;
            bool   shouldTrace           = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId          = null;

            if (shouldTrace)
            {
                invocationId = Tracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("parameters", parameters);
                Tracing.Enter(invocationId, this, "CreateAsync", tracingParameters);
            }
            try
            {
                if (shouldTrace)
                {
                    client = this.Client.WithHandler(new ClientRequestTrackingHandler(invocationId));
                }

                cancellationToken.ThrowIfCancellationRequested();
                OperationStatusResponse response = await client.CloudServices.BeginCreatingAsync(parameters, cancellationToken).ConfigureAwait(false);

                if (response.Status == OperationStatus.Succeeded)
                {
                    return(response);
                }
                cancellationToken.ThrowIfCancellationRequested();
                OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);

                int delayInSeconds = 30;
                if (client.LongRunningOperationInitialTimeout >= 0)
                {
                    delayInSeconds = client.LongRunningOperationInitialTimeout;
                }
                while ((result.Status != OperationStatus.InProgress) == false)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);

                    cancellationToken.ThrowIfCancellationRequested();
                    result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);

                    delayInSeconds = 30;
                    if (client.LongRunningOperationRetryTimeout >= 0)
                    {
                        delayInSeconds = client.LongRunningOperationRetryTimeout;
                    }
                }

                if (shouldTrace)
                {
                    Tracing.Exit(invocationId, result);
                }

                if (result.Status != OperationStatus.Succeeded)
                {
                    if (result.Error != null)
                    {
                        CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
                        ex.ErrorCode    = result.Error.Code;
                        ex.ErrorMessage = result.Error.Message;
                        if (shouldTrace)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }
                    else
                    {
                        CloudException ex = new CloudException("");
                        if (shouldTrace)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }
                }

                return(result);
            }
            finally
            {
                if (client != null && shouldTrace)
                {
                    client.Dispose();
                }
            }
        }
        private async void clickSwitch(Object obj)
        {
            switch (obj.ToString())
            {
            case "buscar_articulo_medicamento":
                SelectedItem    = null;
                SeleccionIndice = -1;
                Nombre          = string.Empty;
                Paterno         = string.Empty;
                Materno         = string.Empty;
                Correo          = string.Empty;
                break;

            case "menu_editar":
                if (_selectedItem != null)
                {
                    EditarVisible = true;
                    NuevoVisible  = false;
                    Nombre        = SelectedItem.Nombre;
                    Paterno       = SelectedItem.Paterno;
                    Materno       = SelectedItem.Materno;
                    Correo        = SelectedItem.Sexo;

                    GuardarMenuEnabled  = true;
                    AgregarMenuEnabled  = false;
                    EliminarMenuEnabled = false;
                    EditarMenuEnabled   = false;
                    CancelarMenuEnabled = true;
                    AyudaMenuEnabled    = true;
                    SalirMenuEnabled    = true;
                    ExportarMenuEnabled = false;

                    AgregarVisible = true;

                    bandera_editar = true;
                    FocusText      = true;
                }
                else
                {
                    bandera_editar = false;
                    var met = Application.Current.Windows[0] as MetroWindow;
                    await met.ShowMessageAsync("Validación", "Debe seleccionar una opcion.");
                }
                break;

            case "menu_agregar":
                EditarVisible = false;
                NuevoVisible  = true;

                GuardarMenuEnabled  = true;
                AgregarMenuEnabled  = false;
                EliminarMenuEnabled = false;
                EditarMenuEnabled   = false;
                CancelarMenuEnabled = true;
                AyudaMenuEnabled    = true;
                SalirMenuEnabled    = true;
                ExportarMenuEnabled = false;

                AgregarVisible = true;

                bandera_editar = false;
                FocusText      = true;
                break;

            case "menu_guardar":
                if (bandera_editar == false)
                {
                    ListItems.Add(new Persona()
                    {
                        Nombre  = Nombre,
                        Paterno = Paterno,
                        Materno = Materno,
                        Sexo    = Correo
                    });
                }
                else
                {
                    SelectedItem.Nombre  = Nombre;
                    SelectedItem.Paterno = Paterno;
                    SelectedItem.Materno = Materno;
                    SelectedItem.Sexo    = Correo;
                }

                EditarVisible = false;
                NuevoVisible  = false;

                GuardarMenuEnabled  = false;
                AgregarMenuEnabled  = true;
                EliminarMenuEnabled = false;
                EditarMenuEnabled   = false;
                CancelarMenuEnabled = false;
                AyudaMenuEnabled    = true;
                SalirMenuEnabled    = true;
                ExportarMenuEnabled = true;

                AgregarVisible = false;

                SelectedItem    = null;
                SeleccionIndice = -1;
                Nombre          = string.Empty;
                Paterno         = string.Empty;
                Materno         = string.Empty;
                Correo          = string.Empty;
                break;

            case "menu_cancelar":
                NuevoVisible = false;

                GuardarMenuEnabled  = false;
                AgregarMenuEnabled  = true;
                EliminarMenuEnabled = false;
                EditarMenuEnabled   = false;
                CancelarMenuEnabled = false;
                AyudaMenuEnabled    = true;
                SalirMenuEnabled    = true;
                ExportarMenuEnabled = true;

                AgregarVisible = false;

                SelectedItem    = null;
                SeleccionIndice = -1;
                Nombre          = string.Empty;
                Paterno         = string.Empty;
                Materno         = string.Empty;
                Correo          = string.Empty;
                break;

            case "menu_eliminar":
                var metro = Application.Current.Windows[0] as MetroWindow;
                if (_selectedItem != null)
                {
                    var mySettings = new MetroDialogSettings()
                    {
                        AffirmativeButtonText = "Aceptar",
                        NegativeButtonText    = "Cancelar",
                        AnimateShow           = true,
                        AnimateHide           = false
                    };
                    var result = await metro.ShowMessageAsync("Borrar", "¿Está seguro que desea borrar esto? [ " + SelectedItem.Nombre + " " + SelectedItem.Paterno + " " + SelectedItem.Materno + " ]", MessageDialogStyle.AffirmativeAndNegative, mySettings);

                    if (result == MessageDialogResult.Affirmative)
                    {
                        var i = ListItems.IndexOf(_selectedItem);
                        if (i >= 0)
                        {
                            ListItems.RemoveAt(i);

                            var dialog = (BaseMetroDialog)metro.Resources["ConfirmacionDialog"];
                            await metro.ShowMetroDialogAsync(dialog);

                            await TaskEx.Delay(1500);

                            await metro.HideMetroDialogAsync(dialog);

                            //MENSAJE EXTERNO
                            //dialog = dialog.ShowDialogExternally();
                            //await TaskEx.Delay(1500);
                            //await dialog.RequestCloseAsync();
                        }
                    }
                }
                else
                {
                    await metro.ShowMessageAsync("Validación", "Debe seleccionar una opcion");
                }
                SelectedItem    = null;
                SeleccionIndice = -1;
                Nombre          = string.Empty;
                Paterno         = string.Empty;
                Materno         = string.Empty;
                Correo          = string.Empty;
                break;

            case "menu_exportar":
                SelectedItem    = null;
                SeleccionIndice = -1;
                Nombre          = string.Empty;
                Paterno         = string.Empty;
                Materno         = string.Empty;
                Correo          = string.Empty;
                break;

            case "menu_ayuda":
                SelectedItem    = null;
                SeleccionIndice = -1;
                Nombre          = string.Empty;
                Paterno         = string.Empty;
                Materno         = string.Empty;
                Correo          = string.Empty;
                break;

            case "menu_salir":
                PrincipalViewModel.SalirMenu();
                break;
            }
        }
示例#4
0
        /// <summary>
        /// The Delete Service Certificate operation deletes a service
        /// certificate from the certificate store of a hosted service. This
        /// operation is an asynchronous operation. To determine whether the
        /// management service has finished processing the request, call Get
        /// Operation Status.  (see
        /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460803.aspx
        /// for more information)
        /// </summary>
        /// <param name='parameters'>
        /// Required. Parameters supplied to the Delete Service Certificate
        /// operation.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response body contains the status of the specified asynchronous
        /// operation, indicating whether it has succeeded, is inprogress, or
        /// has failed. Note that this status is distinct from the HTTP status
        /// code returned for the Get Operation Status operation itself. If
        /// the asynchronous operation succeeded, the response body includes
        /// the HTTP status code for the successful request. If the
        /// asynchronous operation failed, the response body includes the HTTP
        /// status code for the failed request and error information regarding
        /// the failure.
        /// </returns>
        public async Task <OperationStatusResponse> DeleteAsync(ServiceCertificateDeleteParameters parameters, CancellationToken cancellationToken)
        {
            ComputeManagementClient client = this.Client;
            bool   shouldTrace             = TracingAdapter.IsEnabled;
            string invocationId            = null;

            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("parameters", parameters);
                TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
            }

            cancellationToken.ThrowIfCancellationRequested();
            AzureOperationResponse response = await client.ServiceCertificates.BeginDeletingAsync(parameters, cancellationToken).ConfigureAwait(false);

            cancellationToken.ThrowIfCancellationRequested();
            OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);

            int delayInSeconds = 30;

            if (client.LongRunningOperationInitialTimeout >= 0)
            {
                delayInSeconds = client.LongRunningOperationInitialTimeout;
            }
            while ((result.Status != OperationStatus.InProgress) == false)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);

                cancellationToken.ThrowIfCancellationRequested();
                result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);

                delayInSeconds = 30;
                if (client.LongRunningOperationRetryTimeout >= 0)
                {
                    delayInSeconds = client.LongRunningOperationRetryTimeout;
                }
            }

            if (shouldTrace)
            {
                TracingAdapter.Exit(invocationId, result);
            }

            if (result.Status != OperationStatus.Succeeded)
            {
                if (result.Error != null)
                {
                    CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
                    ex.Error         = new CloudError();
                    ex.Error.Code    = result.Error.Code;
                    ex.Error.Message = result.Error.Message;
                    if (shouldTrace)
                    {
                        TracingAdapter.Error(invocationId, ex);
                    }
                    throw ex;
                }
                else
                {
                    CloudException ex = new CloudException("");
                    if (shouldTrace)
                    {
                        TracingAdapter.Error(invocationId, ex);
                    }
                    throw ex;
                }
            }

            return(result);
        }
示例#5
0
        private async void alertSlow(object sender, RoutedEventArgs e)
        {
            await TaskEx.Delay(5000);

            selectionIndicatorLabel.Content = "Slow alert occurred";
        }
示例#6
0
        public async Task ResumingDownloadsWorks()
        {
            Stopwatch watch;
            ILogging  logger;

            StartTest(out watch, out logger);

            var fileSystem = NPath.FileSystem;

            var gitLfs    = new UriString($"http://localhost:{server.Port}/git-lfs.zip");
            var gitLfsMd5 = new UriString($"http://localhost:{server.Port}/git-lfs.zip.md5");

            var downloadTask = new DownloadTask(TaskManager.Token, fileSystem, gitLfsMd5, TestBasePath);

            StartTrackTime(watch, logger, gitLfsMd5);
            var task = await TaskEx.WhenAny(downloadTask.Start().Task, TaskEx.Delay(Timeout));

            StopTrackTimeAndLog(watch, logger);

            task.ShouldBeEquivalentTo(downloadTask.Task);
            var downloadPath = await downloadTask.Task;
            var md5          = downloadPath.ReadAllText();

            Assert.NotNull(md5);

            StartTrackTime(watch, logger, gitLfs);
            downloadTask = new DownloadTask(TaskManager.Token, fileSystem, gitLfs, TestBasePath);

            StartTrackTime(watch, logger, gitLfsMd5);
            task = await TaskEx.WhenAny(downloadTask.Start().Task, TaskEx.Delay(Timeout));

            StopTrackTimeAndLog(watch, logger);
            task.ShouldBeEquivalentTo(downloadTask.Task);

            downloadPath = await downloadTask.Task;
            Assert.NotNull(downloadPath);

            var md5Sum = downloadPath.CalculateMD5();

            md5Sum.Should().BeEquivalentTo(md5);

            var downloadPathBytes = downloadPath.ReadAllBytes();

            Logger.Trace("File size {0} bytes", downloadPathBytes.Length);

            var cutDownloadPathBytes = downloadPathBytes.Take(downloadPathBytes.Length - 1000).ToArray();

            downloadPath.Delete();
            new NPath(downloadPath + ".partial").WriteAllBytes(cutDownloadPathBytes);

            downloadTask = new DownloadTask(TaskManager.Token, fileSystem, gitLfs, TestBasePath);

            StartTrackTime(watch, logger, gitLfs);
            task = await TaskEx.WhenAny(downloadTask.Start().Task, TaskEx.Delay(Timeout));

            StopTrackTimeAndLog(watch, logger);
            task.ShouldBeEquivalentTo(downloadTask.Task);
            downloadPath = await downloadTask.Task;

            md5Sum = downloadPath.CalculateMD5();
            md5Sum.Should().BeEquivalentTo(md5);
        }
示例#7
0
        private async Task load(CancellationToken token)
        {
            int index = 0;

            for (int j = 0; j < _cardForms.Count; j++)
            {
                if (token.IsCancellationRequested)
                {
                    return;
                }

                if (_showArt)
                {
                    foreach (var model in _cardRepository.GetImagesArt(_cardForms[j], _imageRepository))
                    {
                        while (index > _imageIndex + 10 && !token.IsCancellationRequested)
                        {
                            await TaskEx.Delay(100);
                        }

                        if (token.IsCancellationRequested)
                        {
                            return;
                        }

                        var size = model.ImageFile.IsArt
                                                        ? getSizeArt()
                                                        : _imageLoader.ZoomedCardSize;

                        var image = _imageLoader.LoadImage(model, size);

                        if (image == null)
                        {
                            continue;
                        }

                        add(index, model, image);
                        index++;
                    }
                }

                foreach (var model in _cardRepository.GetZoomImages(_cardForms[j], _imageRepository))
                {
                    while (index > _imageIndex + 10 && !token.IsCancellationRequested)
                    {
                        await TaskEx.Delay(100);
                    }

                    if (token.IsCancellationRequested)
                    {
                        return;
                    }

                    var size = model.ImageFile.IsArt
                                                ? getSizeArt()
                                                : _imageLoader.ZoomedCardSize;

                    var image = _imageLoader.LoadImage(model, size);

                    if (image == null)
                    {
                        continue;
                    }

                    add(index, model, image);
                    index++;
                }
            }
        }
示例#8
0
        /// <summary>
        /// The Add Virtual IP operation adds a logical Virtual IP to the
        /// deployment.
        /// </summary>
        /// <param name='serviceName'>
        /// Required. The name of the hosted service that contains the given
        /// deployment.
        /// </param>
        /// <param name='deploymentName'>
        /// Required. The name of the deployment where the logical Virtual IP
        /// is to be added.
        /// </param>
        /// <param name='virtualIPName'>
        /// Required. The name of the logical Virtual IP to be added.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response body contains the status of the specified asynchronous
        /// operation, indicating whether it has succeeded, is inprogress, or
        /// has failed. Note that this status is distinct from the HTTP status
        /// code returned for the Get Operation Status operation itself. If
        /// the asynchronous operation succeeded, the response body includes
        /// the HTTP status code for the successful request. If the
        /// asynchronous operation failed, the response body includes the HTTP
        /// status code for the failed request, and also includes error
        /// information regarding the failure.
        /// </returns>
        public async Task <OperationStatusResponse> AddAsync(string serviceName, string deploymentName, string virtualIPName, CancellationToken cancellationToken)
        {
            NetworkManagementClient client = this.Client;
            bool   shouldTrace             = TracingAdapter.IsEnabled;
            string invocationId            = null;

            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("serviceName", serviceName);
                tracingParameters.Add("deploymentName", deploymentName);
                tracingParameters.Add("virtualIPName", virtualIPName);
                TracingAdapter.Enter(invocationId, this, "AddAsync", tracingParameters);
            }

            cancellationToken.ThrowIfCancellationRequested();
            OperationStatusResponse response = await client.VirtualIPs.BeginAddingAsync(serviceName, deploymentName, virtualIPName, cancellationToken).ConfigureAwait(false);

            if (response.Status == OperationStatus.Succeeded)
            {
                return(response);
            }
            cancellationToken.ThrowIfCancellationRequested();
            OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);

            int delayInSeconds = 30;

            if (client.LongRunningOperationInitialTimeout >= 0)
            {
                delayInSeconds = client.LongRunningOperationInitialTimeout;
            }
            while (result.Status == OperationStatus.InProgress)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);

                cancellationToken.ThrowIfCancellationRequested();
                result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);

                delayInSeconds = 30;
                if (client.LongRunningOperationRetryTimeout >= 0)
                {
                    delayInSeconds = client.LongRunningOperationRetryTimeout;
                }
            }

            if (shouldTrace)
            {
                TracingAdapter.Exit(invocationId, result);
            }

            if (result.Status != OperationStatus.Succeeded)
            {
                if (result.Error != null)
                {
                    CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
                    ex.Error         = new CloudError();
                    ex.Error.Code    = result.Error.Code;
                    ex.Error.Message = result.Error.Message;
                    if (shouldTrace)
                    {
                        TracingAdapter.Error(invocationId, ex);
                    }
                    throw ex;
                }
                else
                {
                    CloudException ex = new CloudException("");
                    if (shouldTrace)
                    {
                        TracingAdapter.Error(invocationId, ex);
                    }
                    throw ex;
                }
            }

            return(result);
        }
示例#9
0
        /// <summary>
        /// Clears all values in the data store. This method deletes all files in <see cref="FolderPath"/>.
        /// </summary>
        public Task ClearAsync()
        {
            Store.Clear();

            return(TaskEx.Delay(0));
        }
        /// <summary>
        /// Requests the JSON string with retry.
        /// </summary>
        /// <param name="host">The host.</param>
        /// <param name="auth">The auth type of the route.</param>
        /// <param name="routeName">Name of the route.</param>
        /// <param name="routeStyle">The route style.</param>
        /// <param name="requestArg">The request argument.</param>
        /// <param name="body">The body to upload if <paramref name="routeStyle"/>
        /// is <see cref="RouteStyle.Upload"/>.</param>
        /// <returns>The asynchronous task with the result.</returns>
        private async Task <Result> RequestJsonStringWithRetry(
            string host,
            string routeName,
            string auth,
            RouteStyle routeStyle,
            string requestArg,
            Stream body = null)
        {
            var attempt    = 0;
            var maxRetries = this.options.MaxClientRetries;
            var r          = new Random();

            if (routeStyle == RouteStyle.Upload)
            {
                if (body == null)
                {
                    throw new ArgumentNullException("body");
                }

                // to support retry logic, the body stream must be seekable
                // if it isn't we won't retry
                if (!body.CanSeek)
                {
                    maxRetries = 0;
                }
            }

            try
            {
                while (true)
                {
                    try
                    {
                        return(await this.RequestJsonString(host, routeName, auth, routeStyle, requestArg, body)
                               .ConfigureAwait(false));
                    }
                    catch (RateLimitException)
                    {
                        throw;
                    }
                    catch (RetryException)
                    {
                        // dropbox maps 503 - ServiceUnavailable to be a rate limiting error.
                        // do not count a rate limiting error as an attempt
                        if (++attempt > maxRetries)
                        {
                            throw;
                        }
                    }

                    // use exponential backoff
                    var backoff = TimeSpan.FromSeconds(Math.Pow(2, attempt) * r.NextDouble());
#if PORTABLE40
                    await TaskEx.Delay(backoff);
#else
                    await Task.Delay(backoff).ConfigureAwait(false);
#endif
                    if (body != null)
                    {
                        body.Position = 0;
                    }
                }
            }
            finally
            {
                if (body != null)
                {
                    body.Dispose();
                }
            }
        }
 public static Task RandomDelay(this IRandomGenerator<ulong> generator, TimeSpan minimum, TimeSpan maximum, CancellationToken cancellationToken)
 {
   return TaskEx.Delay(RandomTimeExtensions.RandomTimeSpan(generator, minimum, maximum), cancellationToken);
 }
示例#12
0
        private void ProcessSearchRequest(string mx, string searchTarget, UdpEndPoint endPoint)
        {
            if (String.IsNullOrEmpty(searchTarget))
            {
                WriteTrace(String.Format("Invalid search request received From {0}, Target is null/empty.", endPoint.ToString()));
                return;
            }

            WriteTrace(String.Format("Search Request Received From {0}, Target = {1}", endPoint.ToString(), searchTarget));

            if (IsDuplicateSearchRequest(searchTarget, endPoint))
            {
                WriteTrace("Search Request is Duplicate, ignoring.");
                return;
            }

            //Wait on random interval up to MX, as per SSDP spec.
            //Also, as per UPnP 1.1/SSDP spec ignore missing/bank MX header. If over 120, assume random value between 0 and 120.
            //Using 16 as minimum as that's often the minimum system clock frequency anyway.
            int maxWaitInterval = 0;

            if (String.IsNullOrEmpty(mx))
            {
                //Windows Explorer is poorly behaved and doesn't supply an MX header value.
                if (this.SupportPnpRootDevice)
                {
                    mx = "1";
                }
                else
                {
                    return;
                }
            }

            if (!Int32.TryParse(mx, out maxWaitInterval) || maxWaitInterval <= 0)
            {
                return;
            }

            if (maxWaitInterval > 120)
            {
                maxWaitInterval = _Random.Next(0, 120);
            }

            //Do not block synchronously as that may tie up a threadpool thread for several seconds.
            TaskEx.Delay(_Random.Next(16, (maxWaitInterval * 1000))).ContinueWith((parentTask) =>
            {
                //Copying devices to local array here to avoid threading issues/enumerator exceptions.
                IEnumerable <SsdpDevice> devices = null;
                lock (_Devices)
                {
                    if (String.Compare(SsdpConstants.SsdpDiscoverAllSTHeader, searchTarget, StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        devices = GetAllDevicesAsFlatEnumerable().ToArray();
                    }
                    else if (String.Compare(SsdpConstants.UpnpDeviceTypeRootDevice, searchTarget, StringComparison.OrdinalIgnoreCase) == 0 || (this.SupportPnpRootDevice && String.Compare(SsdpConstants.PnpDeviceTypeRootDevice, searchTarget, StringComparison.OrdinalIgnoreCase) == 0))
                    {
                        devices = _Devices.ToArray();
                    }
                    else if (searchTarget.Trim().StartsWith("uuid:", StringComparison.OrdinalIgnoreCase))
                    {
                        devices = (from device in GetAllDevicesAsFlatEnumerable() where String.Compare(device.Uuid, searchTarget.Substring(5), StringComparison.OrdinalIgnoreCase) == 0 select device).ToArray();
                    }
                    else if (searchTarget.StartsWith("urn:", StringComparison.OrdinalIgnoreCase))
                    {
                        devices = (from device in GetAllDevicesAsFlatEnumerable() where String.Compare(device.FullDeviceType, searchTarget, StringComparison.OrdinalIgnoreCase) == 0 select device).ToArray();
                    }
                }

                if (devices != null)
                {
                    WriteTrace(String.Format("Sending {0} search responses", devices.Count()));

                    foreach (var device in devices)
                    {
                        SendDeviceSearchResponses(device, endPoint);
                    }
                }
                else
                {
                    WriteTrace(String.Format("Sending 0 search responses."));
                }
            });
        }
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            Log.Info("Before: Clicking to Find Customer Record in FindCustomer");
            if (!string.IsNullOrEmpty(showCustomer.Text) &&
                !string.IsNullOrEmpty(FirstDate.Text) && !string.IsNullOrEmpty(SecondDate.Text))
            {
                MainWindow mainWindow = (MainWindow)Application.Current.MainWindow;

                var controller = await mainWindow.ShowProgressAsync("Please wait...", "Process is Going on..!");

                controller.SetIndeterminate();
                await TaskEx.Delay(1000);

                ShowRecord flyout = mainWindow.Flyouts.Items[16] as ShowRecord;

                Log.Info("Before: Set to Datagrid Customer Record in FindCustomer");
                flyout.datalist.ItemsSource = Queries.GetAllByCondition <Sale>(x => x.Customer.Cid == (int)showCustomer.SelectedValue &&
                                                                               (x.SaleDate >= FirstDate.SelectedDate) && (x.SaleDate <= SecondDate.SelectedDate));

                flyout.cname.Content = showCustomer.Text;
                flyout.fdate.Content = FirstDate.SelectedDate.Value.ToString("dd-MMM-yyyy");
                flyout.ldate.Content = SecondDate.SelectedDate.Value.ToString("dd-MMM-yyyy");
                Log.Info("After: Set to Datagrid Customer Record in FindCustomer");

                //  Type == true  for sales.

                //lst = (List<Products>)showProduct.ItemsSource;

                //Products _chk = (from l in lst
                //                 where l.Pid == (int)showProduct.SelectedValue
                //                 select l).FirstOrDefault<Products>();
                Log.Info("Before: Get list of customer in FindCustomer");

                List <Sale> _lst = Queries.GetAllByCondition <Sale>(x => x.Customer.Cid == (int)showCustomer.SelectedValue);
                Log.Info("After: Get list of customer in FindCustomer");

                float b = 0, total = 0;
                foreach (Sale item in _lst)
                {
                    b     += item.RemainingBalance;
                    total += item.TotalAmount;
                }

                flyout.advance.Content = total;
                flyout.balance.Content = b;

                Helpful.CloseAllFlyouts(mainWindow.Flyouts);
                mainWindow.ToggleFlyout(16);
                showCustomer.Text = string.Empty;
                FirstDate.Text    = string.Empty;
                SecondDate.Text   = string.Empty;

                await controller.CloseAsync();

                if (flyout == null)
                {
                    return;
                }
                Log.Info("After: Clicking to Find Customer Record");
            }
            else
            {
                MainWindow mainWindow = (MainWindow)Application.Current.MainWindow;
                await mainWindow.ShowMessageAsync("Please Enter the Complete Details", "");
            }
        }
        public async Task WaitForNotBusy(int seconds = 1)
        {
            await TaskEx.WhenAny(IsBusy, TaskEx.Delay(TimeSpan.FromSeconds(seconds)));

            await TaskEx.WhenAny(IsNotBusy, TaskEx.Delay(TimeSpan.FromSeconds(seconds)));
        }
示例#15
0
        private static async void ConnectCurrentServer()
        {
            DisconnectCurrentServer();

            // Set up a cancellation token source
            _currentConnectionCancellationTokenSource = new CancellationTokenSource();
            var token  = _currentConnectionCancellationTokenSource.Token;
            var server = CurrentServer;

            while (!token.IsCancellationRequested && server == CurrentServer)
            {
                // Attempt to connect to the server
                _log.Info("Attempting to connect to server at {0}:{1}", server.Hostname, server.Port);
                var result = await server.ConnectAsync(token);

                // If this connection attempt has been cancelled, don't do anything else
                if (token.IsCancellationRequested || server != CurrentServer)
                {
                    return;
                }

                switch (result)
                {
                case ConnectionResult.Success:
                    server.StartUpdateRequests();
                    HandleServerConnected();
                    return;

                case ConnectionResult.InvalidPIN:
                    HandleInvalidPIN();
                    return;

                case ConnectionResult.ConnectionError:
                    NetService service = BonjourManager.DiscoveredServers.GetValueOrDefault(SelectedServerInfo.ServiceID);
                    if (service == null)
                    {
                        _log.Info("Server is not currently available via Bonjour.");
                        ConnectionState = ServerConnectionState.LookingForLibrary;
                        return;
                    }

                    // A connection attempt failed, but we have the service in Bonjour.
                    _log.Info("Server connection failed, but server is available via Bonjour.");

                    // Select the next IP address and try to connect to it.
                    var  ips      = service.IPAddresses.Select(ip => ip.ToString()).ToList();
                    bool hasNewIP = false;
                    if (ips.Count > 0)
                    {
                        int index = ips.IndexOf(CurrentServer.Hostname);
                        index++;
                        if (index >= ips.Count)
                        {
                            index = 0;
                        }

                        if (ips[index] != CurrentServer.Hostname)
                        {
                            _log.Info("Trying new IP: {0} (Previous: {1})", ips[index], CurrentServer.Hostname);
                            CurrentServer.Hostname = ips[index];
                            hasNewIP = true;
                        }
                    }

                    // Update the port if necessary
                    CurrentServer.Port = service.Port;

                    // Delay reconnection if the IP hasn't changed
                    if (!hasNewIP)
                    {
                        _log.Info("Delaying reconnection...");
#if WP7
                        await TaskEx.Delay(_reconnectionDelay);
#else
                        await Task.Delay(_reconnectionDelay);
#endif
                    }
                    break;
                }
            }
        }
示例#16
0
        public static T Retry <T>(Func <T> retryme, int timeOut, int retries, ILogger logger)
        {
            var tries = 0;

            do
            {
                tries++;

                try
                {
                    return(retryme());
                }

                // might occur on lua script execution on a readonly slave because the master just died.
                // Should recover via fail over
                catch (StackRedis.RedisServerException ex)
                {
                    if (tries >= retries)
                    {
                        logger.LogError(ex, ErrorMessage, retries);
                        throw;
                    }

                    logger.LogWarn(ex, WarningMessage, tries, retries);
#if NET40
                    TaskEx.Delay(timeOut).Wait();
#else
                    Task.Delay(timeOut).Wait();
#endif
                }
                catch (StackRedis.RedisConnectionException ex)
                {
                    if (tries >= retries)
                    {
                        logger.LogError(ex, ErrorMessage, retries);
                        throw;
                    }

                    logger.LogWarn(ex, WarningMessage, tries, retries);
#if NET40
                    TaskEx.Delay(timeOut).Wait();
#else
                    Task.Delay(timeOut).Wait();
#endif
                }
                catch (TimeoutException ex)
                {
                    if (tries >= retries)
                    {
                        logger.LogError(ex, ErrorMessage, retries);
                        throw;
                    }

                    logger.LogWarn(ex, WarningMessage, tries, retries);
#if NET40
                    TaskEx.Delay(timeOut).Wait();
#else
                    Task.Delay(timeOut).Wait();
#endif
                }
                catch (AggregateException aggregateException)
                {
                    if (tries >= retries)
                    {
                        logger.LogError(aggregateException, ErrorMessage, retries);
                        throw;
                    }

                    aggregateException.Handle(e =>
                    {
                        if (e is StackRedis.RedisConnectionException || e is System.TimeoutException || e is StackRedis.RedisServerException)
                        {
                            logger.LogWarn(e, WarningMessage, tries, retries);
#if NET40
                            TaskEx.Delay(timeOut).Wait();
#else
                            Task.Delay(timeOut).Wait();
#endif

                            return(true);
                        }

                        logger.LogCritical("Unhandled exception occurred.", aggregateException);
                        return(false);
                    });
                }
            }while (tries < retries);

            return(default(T));
        }
示例#17
0
        /// <summary>
        /// The Delete Reserved IP operation removes a reserved IP from your
        /// the subscription.
        /// </summary>
        /// <param name='ipName'>
        /// The name of the reserved IP.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response body contains the status of the specified asynchronous
        /// operation, indicating whether it has succeeded, is inprogress, or
        /// has failed. Note that this status is distinct from the HTTP status
        /// code returned for the Get Operation Status operation itself.  If
        /// the asynchronous operation succeeded, the response body includes
        /// the HTTP status code for the successful request.  If the
        /// asynchronous operation failed, the response body includes the HTTP
        /// status code for the failed request, and also includes error
        /// information regarding the failure.
        /// </returns>
        public async Task <VirtualNetworkOperationStatusResponse> DeleteAsync(string ipName, CancellationToken cancellationToken)
        {
            VirtualNetworkManagementClient client = this.Client;
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = Tracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("ipName", ipName);
                Tracing.Enter(invocationId, this, "DeleteAsync", tracingParameters);
            }
            try
            {
                if (shouldTrace)
                {
                    client = this.Client.WithHandler(new ClientRequestTrackingHandler(invocationId));
                }

                cancellationToken.ThrowIfCancellationRequested();
                OperationResponse response = await client.ReservedIPs.BeginDeletingAsync(ipName, cancellationToken).ConfigureAwait(false);

                cancellationToken.ThrowIfCancellationRequested();
                VirtualNetworkOperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);

                int delayInSeconds = 30;
                while ((result.Status != OperationStatus.InProgress) == false)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);

                    cancellationToken.ThrowIfCancellationRequested();
                    result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);

                    delayInSeconds = 30;
                }

                if (shouldTrace)
                {
                    Tracing.Exit(invocationId, result);
                }

                if (result.Status != OperationStatus.Succeeded)
                {
                    if (result.Error != null)
                    {
                        CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
                        ex.ErrorCode    = result.Error.Code;
                        ex.ErrorMessage = result.Error.Message;
                        if (shouldTrace)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }
                    else
                    {
                        CloudException ex = new CloudException("");
                        if (shouldTrace)
                        {
                            Tracing.Error(invocationId, ex);
                        }
                        throw ex;
                    }
                }

                return(result);
            }
            finally
            {
                if (client != null && shouldTrace)
                {
                    client.Dispose();
                }
            }
        }
        private async void ClickSwitch(Object obj)
        {
            switch (obj.ToString())
            {
            case "buscar":
                this.GetCentros();
                break;

            case "menu_editar":
                if (SelectedItem != null)
                {
                    HeaderAgregar       = "Editar Centro";
                    EditarVisible       = true;
                    NuevoVisible        = false;
                    GuardarMenuEnabled  = true;
                    AgregarMenuEnabled  = false;
                    EliminarMenuEnabled = false;
                    EditarMenuEnabled   = false;
                    CancelarMenuEnabled = true;
                    AyudaMenuEnabled    = true;
                    SalirMenuEnabled    = true;
                    ExportarMenuEnabled = false;
                    AgregarVisible      = true;
                    bandera_editar      = true;
                    FocusText           = true;
                    #region Obtener Valores
                    Nombre        = string.IsNullOrEmpty(SelectedItem.DESCR) ? string.Empty : SelectedItem.DESCR.TrimEnd();
                    Calle         = string.IsNullOrEmpty(SelectedItem.CALLE) ? string.Empty : SelectedItem.CALLE.TrimEnd();
                    Colonia       = string.IsNullOrEmpty(SelectedItem.COLONIA) ? string.Empty : SelectedItem.CALLE.TrimEnd();
                    No_exterior   = string.IsNullOrEmpty(SelectedItem.NUM_EXT.ToString()) ? string.Empty : SelectedItem.NUM_EXT.ToString();
                    No_interior   = string.IsNullOrEmpty(SelectedItem.NUM_INT) ? string.Empty : SelectedItem.NUM_INT.TrimEnd();
                    Codigo_postal = string.IsNullOrEmpty(SelectedItem.CP.ToString()) ? string.Empty : SelectedItem.CP.ToString();
                    Telefono      = string.IsNullOrEmpty(SelectedItem.TELEFONO.ToString()) ? string.Empty : SelectedItem.TELEFONO.ToString();
                    Fax           = string.IsNullOrEmpty(SelectedItem.FAX.ToString()) ? string.Empty : SelectedItem.FAX.ToString();
                    Director      = string.IsNullOrEmpty(SelectedItem.DIRECTOR) ? string.Empty : SelectedItem.DIRECTOR.TrimEnd();

                    SelectEntidad   = ListEntidad.Where(w => w.ID_ENTIDAD == SelectedItem.ID_ENTIDAD).FirstOrDefault();
                    SelectMunicipio = ListMunicipio.Where(w => w.ID_MUNICIPIO == SelectedItem.ID_MUNICIPIO).FirstOrDefault();
                    SelectedEstatus = Lista_Estatus.LISTA_ESTATUS.Where(w => w.CLAVE == SelectedItem.ESTATUS).SingleOrDefault();
                    #endregion Obtener Valores
                }
                else
                {
                    bandera_editar = false;
                    var met = Application.Current.Windows[0] as MetroWindow;
                    await met.ShowMessageAsync("Validación", "Debe seleccionar una opción.");
                }
                break;

            case "menu_agregar":
                HeaderAgregar = "Agregar Centro";
                //Limpiamos el objeto de tipo centro
                SeleccionIndice = -1;
                Nombre          = string.Empty;
                Calle           = string.Empty;
                Colonia         = string.Empty;
                No_exterior     = string.Empty;
                No_interior     = string.Empty;
                Codigo_postal   = string.Empty;
                Telefono        = string.Empty;
                Fax             = string.Empty;
                Director        = string.Empty;
                SelectEntidad   = ListEntidad.Where(w => w.ID_ENTIDAD == -1).FirstOrDefault();
                SelectMunicipio = ListMunicipio.Where(w => w.ID_MUNICIPIO == -1).FirstOrDefault();
                SelectedEstatus = Lista_Estatus.LISTA_ESTATUS.Where(w => w.CLAVE == "S").FirstOrDefault();
                /****************************************/
                EditarVisible       = false;
                NuevoVisible        = true;
                GuardarMenuEnabled  = true;
                AgregarMenuEnabled  = false;
                EliminarMenuEnabled = false;
                EditarMenuEnabled   = false;
                CancelarMenuEnabled = true;
                AyudaMenuEnabled    = true;
                SalirMenuEnabled    = true;
                ExportarMenuEnabled = false;
                AgregarVisible      = true;
                bandera_editar      = false;
                FocusText           = true;
                break;

            case "menu_guardar":
                if (!string.IsNullOrEmpty(Nombre))
                {
                    EditarVisible       = false;
                    NuevoVisible        = false;
                    GuardarMenuEnabled  = false;
                    AgregarMenuEnabled  = true;
                    EliminarMenuEnabled = false;
                    EditarMenuEnabled   = false;
                    CancelarMenuEnabled = false;
                    AyudaMenuEnabled    = true;
                    SalirMenuEnabled    = true;
                    ExportarMenuEnabled = true;
                    AgregarVisible      = false;
                    /**********************************/
                    this.GuardarCentros();
                    /**********************************/
                }
                else
                {
                    FocusText = true;
                }
                break;

            case "menu_cancelar":
                NuevoVisible        = false;
                GuardarMenuEnabled  = false;
                AgregarMenuEnabled  = true;
                EliminarMenuEnabled = false;
                EditarMenuEnabled   = false;
                CancelarMenuEnabled = false;
                AyudaMenuEnabled    = true;
                SalirMenuEnabled    = true;
                ExportarMenuEnabled = true;
                AgregarVisible      = false;
                //Limpiamos las variables
                SeleccionIndice = -1;
                Nombre          = string.Empty;
                Calle           = string.Empty;
                Colonia         = string.Empty;
                No_exterior     = string.Empty;
                No_interior     = string.Empty;
                Codigo_postal   = string.Empty;
                Telefono        = string.Empty;
                Fax             = string.Empty;
                Director        = string.Empty;
                SelectEntidad   = ListEntidad.Where(w => w.ID_ENTIDAD == -1).FirstOrDefault();
                SelectMunicipio = ListMunicipio.Where(w => w.ID_MUNICIPIO == -1).FirstOrDefault();
                break;

            case "menu_eliminar":
                var metro = Application.Current.Windows[0] as MetroWindow;
                if (SelectedItem != null)
                {
                    var mySettings = new MetroDialogSettings()
                    {
                        AffirmativeButtonText = "Aceptar",
                        NegativeButtonText    = "Cancelar",
                        AnimateShow           = true,
                        AnimateHide           = false
                    };
                    var result = await metro.ShowMessageAsync("Borrar", "¿Está seguro que desea borrar esto? [ " + SelectedItem.DESCR + " ]", MessageDialogStyle.AffirmativeAndNegative, mySettings);

                    if (result == MessageDialogResult.Affirmative)
                    {
                        if (Eliminar())
                        {
                            var dialog = (BaseMetroDialog)metro.Resources["ConfirmacionDialog"];
                            await metro.ShowMetroDialogAsync(dialog);

                            await TaskEx.Delay(1500);

                            await metro.HideMetroDialogAsync(dialog);
                        }
                        else
                        {
                            mySettings = new MetroDialogSettings()
                            {
                                AffirmativeButtonText = "Aceptar"
                            };
                            await metro.ShowMessageAsync("Algo ocurrió...", "No se puede eliminar información del centro: Tiene dependencias.", MessageDialogStyle.Affirmative, mySettings);

                            await TaskEx.Delay(1500);
                        }
                    }
                }
                else
                {
                    await metro.ShowMessageAsync("Validación", "Debe seleccionar una opción");
                }
                SeleccionIndice = -1;
                break;

            case "menu_exportar":
                SeleccionIndice = -1;
                Cambio          = string.Empty;
                break;

            case "menu_ayuda":
                SeleccionIndice = -1;
                Cambio          = string.Empty;
                break;

            case "menu_salir":
                SeleccionIndice = -1;
                Cambio          = string.Empty;
                PrincipalViewModel.SalirMenu();
                break;
            }
        }
示例#19
0
 protected override Task Wait(TimeSpan ts, CancellationToken cancellationToken)
 {
     Waits.Add(ts);
     return(TaskEx.Delay(0));
 }
示例#20
0
        public async Task Save()
        {
            try {
                BeginAction();
                MessagePatchToPost patch  = null;
                Signer             signer = GetSigner();
                if (ReqRevocationSign)
                {
                    Entity revocReq = Payload.Message.Entities.FirstOrDefault(x => x.AttachmentTypeValue == Diadoc.Api.Com.AttachmentType.RevocationRequest);
                    patch = Payload.Patch();
                    DocumentSignature acceptSignature = new DocumentSignature();
                    acceptSignature.IsApprovementSignature = true;
                    acceptSignature.ParentEntityId         = revocReq.EntityId;
                    byte[] sign = null;
                    if (!TrySign(revocReq.Content.Data, out sign))
                    {
                        throw new Exception("Ошибка подписи документа TrySign");
                    }
                    if (Settings.Value.DebugUseTestSign)
                    {
                        acceptSignature.SignWithTestSignature = true;
                    }
                    acceptSignature.Signature = sign;
                    patch.AddSignature(acceptSignature);
                    await Async(x => Payload.Api.PostMessagePatch(x, patch));
                }
                else
                {
                    if (Payload.Entity.AttachmentType == AttachmentType.Nonformalized)
                    {
                        patch = Payload.Patch();
                        byte[] sign = null;
                        if (!TrySign(Payload.Entity.Content.Data, out sign))
                        {
                            throw new Exception("Ошибка подписи документа TrySign");
                        }
                        var signature = new DocumentSignature {
                            ParentEntityId = Payload.Entity.EntityId,
                            Signature      = sign
                        };
                        if (Settings.Value.DebugUseTestSign)
                        {
                            signature.SignWithTestSignature = true;
                        }
                        patch.AddSignature(signature);
                        await Async(x => Payload.Api.PostMessagePatch(x, patch));
                    }
                    else if (Payload.Entity.AttachmentType == AttachmentType.XmlTorg12)
                    {
                        if (SaveData.Value)
                        {
                            SignTorg12Autosave autosave = new SignTorg12Autosave();
                            autosave.SignerJobTitle = RcvJobTitle.Value;
                            if (LikeReciever.Value)
                            {
                                autosave.LikeReciever = true;
                            }
                            else
                            {
                                autosave.AcptFirstName  = AcptFirstName.Value;
                                autosave.AcptSurename   = AcptSurename.Value;
                                autosave.AcptPatronimic = AcptPatronimic.Value;
                                autosave.AcptJobTitle   = AcptJobTitle.Value;
                            }
                            if (ByAttorney.Value)
                            {
                                autosave.ByAttorney      = true;
                                autosave.AtrNum          = AtrNum.Value;
                                autosave.AtrDate         = AtrDate.Value.Value;
                                autosave.AtrOrganization = AtrOrganization.Value;
                                autosave.AtrJobTitle     = AtrJobTitle.Value;
                                autosave.AtrSurename     = AtrSurename.Value;
                                autosave.AtrFirstName    = AtrFirstName.Value;
                                autosave.AtrPatronymic   = AtrPatronymic.Value;
                                autosave.AtrAddInfo      = AtrAddInfo.Value;
                            }
                            autosave.Comment = Comment.Value;
                            Session.Save(autosave);
                            for (int i = autosave_max - 1; i < SavedData.Value.Count; i++)
                            {
                                Session.Delete(SavedData.Value[i]);
                            }
                        }
                        Official recived  = GetRevicedOfficial();
                        Official accepted = GetAcceptetOfficial();
                        Attorney attorney = GetAttorney();

                        var inf = new Torg12BuyerTitleInfo()
                        {
                            ReceivedBy          = recived,                    //лицо, получившее груз signer
                            AcceptedBy          = accepted,                   //лицо, принявшее груз
                            Attorney            = attorney,
                            AdditionalInfo      = Comment,
                            ShipmentReceiptDate = RcvDate.Value.ToString("dd.MM.yyyy"),
                            Signer = signer
                        };

                        GeneratedFile torg12XmlForBuyer = await Async((x) => Payload.Api.GenerateTorg12XmlForBuyer(
                                                                          x,
                                                                          inf,
                                                                          Payload.BoxId,
                                                                          Payload.Entity.DocumentInfo.MessageId,
                                                                          Payload.Entity.DocumentInfo.EntityId));

                        SignedContent signContent = new SignedContent();
                        signContent.Content = torg12XmlForBuyer.Content;
                        if (!TrySign(signContent))
                        {
                            throw new Exception("Ошибка подписи документа TrySign");
                        }

                        ReceiptAttachment receipt = new ReceiptAttachment {
                            ParentEntityId = Payload.Entity.DocumentInfo.EntityId,
                            SignedContent  = signContent
                        };
                        patch = Payload.PatchTorg12(receipt);
                        await Async(x => Payload.Api.PostMessagePatch(x, patch));

                        Log.Info($"Документ {patch.MessageId} успешно подписан");
                    }
                    else if (Payload.Entity.AttachmentType == AttachmentType.Invoice)
                    {
                        Entity invoice = Payload.Message.Entities.First(i => i.AttachmentTypeValue == Diadoc.Api.Com.AttachmentType.Invoice);

                        GeneratedFile invoiceReceipt = await Async((x) => Payload.Api.GenerateInvoiceDocumentReceiptXml(
                                                                       x,
                                                                       Payload.BoxId,
                                                                       Payload.Entity.DocumentInfo.MessageId,
                                                                       invoice.EntityId,
                                                                       signer));

                        SignedContent signContentInvoiceReciept = new SignedContent();
                        signContentInvoiceReciept.Content = invoiceReceipt.Content;
                        if (!TrySign(signContentInvoiceReciept))
                        {
                            throw new Exception("Ошибка подписи документа TrySign");
                        }

                        ReceiptAttachment receiptInvoice = new ReceiptAttachment {
                            ParentEntityId = invoice.EntityId,
                            SignedContent  = signContentInvoiceReciept
                        };

                        Entity        invoiceConfirmation        = Payload.Message.Entities.OrderBy(x => x.CreationTime).First(i => i.AttachmentTypeValue == Diadoc.Api.Com.AttachmentType.InvoiceConfirmation);
                        GeneratedFile invoiceConfirmationReceipt = await Async((x) => Payload.Api.GenerateInvoiceDocumentReceiptXml(
                                                                                   x,
                                                                                   Payload.BoxId,
                                                                                   Payload.Entity.DocumentInfo.MessageId,
                                                                                   invoiceConfirmation.EntityId,
                                                                                   signer));

                        SignedContent signContentInvoiceConfirmationReciept = new SignedContent();
                        signContentInvoiceConfirmationReciept.Content = invoiceReceipt.Content;

                        if (!TrySign(signContentInvoiceConfirmationReciept))
                        {
                            throw new Exception("Ошибка подписи документа TrySign");
                        }

                        ReceiptAttachment invoiceConfirmationreceipt = new ReceiptAttachment {
                            ParentEntityId = invoiceConfirmation.EntityId,
                            SignedContent  = signContentInvoiceConfirmationReciept
                        };

                        patch = Payload.Patch(receiptInvoice, invoiceConfirmationreceipt);

                        await Async(x => Payload.Api.PostMessagePatch(x, patch));

                        Log.Info($"Документ {patch.MessageId} receiptInvoice, invoiceConfirmationreceipt отправлены");

                        Entity invoiceDateConfirmation = await Async((x) => {
                            Message msg        = null;
                            Entity dateConfirm = null;
                            int breaker        = 0;
                            do
                            {
                                msg = Payload.Api.GetMessage(Payload.Token,
                                                             Payload.BoxId,
                                                             Payload.Entity.DocumentInfo.MessageId,
                                                             Payload.Entity.EntityId);
                                dateConfirm = GetDateConfirmationStep7(msg);
                                breaker++;
                                TaskEx.Delay(500).Wait();
                            }while (dateConfirm == null && breaker < 10);
                            if (dateConfirm == null)
                            {
                                throw new TimeoutException("Превышено время ожидания ответа, попробуйте повторить позднее.");
                            }
                            LastPatchStamp = msg.LastPatchTimestamp;
                            return(dateConfirm);
                        });

                        GeneratedFile invoiceOperConfirmationReceipt = await Async((x) => Payload.Api.GenerateInvoiceDocumentReceiptXml(
                                                                                       x,
                                                                                       Payload.BoxId,
                                                                                       Payload.Entity.DocumentInfo.MessageId,
                                                                                       invoiceDateConfirmation.EntityId,
                                                                                       signer));

                        SignedContent signContentOperInvoiceConfrmReciept = new SignedContent();
                        signContentOperInvoiceConfrmReciept.Content = invoiceOperConfirmationReceipt.Content;

                        if (!TrySign(signContentOperInvoiceConfrmReciept))
                        {
                            throw new Exception("Ошибка подписи документа TrySign");
                        }

                        ReceiptAttachment receipt = new ReceiptAttachment {
                            ParentEntityId = invoiceDateConfirmation.EntityId,
                            SignedContent  = signContentOperInvoiceConfrmReciept
                        };
                        patch = Payload.Patch(receipt);
                        await Async(x => Payload.Api.PostMessagePatch(x, patch));

                        Log.Info($"Документ {patch.MessageId} invoiceDateConfirmation отправлен");
                    }
                }
                await EndAction();
            }
            catch (Exception e) {
                var error = ErrorHelper.TranslateException(e)
                            ?? "Не удалось выполнить операцию, попробуйте повторить позднее.";
                Manager.Warning(error);
                Log.Error(error, e);
                await EndAction(false);
            }
        }
示例#21
0
        /// <summary>
        /// Requests the JSON string with retry.
        /// </summary>
        /// <param name="host">The host.</param>
        /// <param name="routeName">Name of the route.</param>
        /// <param name="routeStyle">The route style.</param>
        /// <param name="requestArg">The request argument.</param>
        /// <param name="body">The body to upload if <paramref name="routeStyle"/>
        /// is <see cref="RouteStyle.Upload"/>.</param>
        /// <returns>The asynchronous task with the result.</returns>
        private async Task <Result> RequestJsonStringWithRetry(
            string host,
            string routeName,
            RouteStyle routeStyle,
            string requestArg,
            Stream body = null)
        {
            var attempt    = 0;
            var maxRetries = this.maxClientRetries;
            var r          = new Random();

            byte[] cachedBody        = null;
            long   cachedStreamStart = 0;

            if (routeStyle == RouteStyle.Upload)
            {
                // to support retry logic, the body stream must be seekable
                // if it isn't we won't retry
                if (!body.CanSeek)
                {
                    maxRetries = 0;
                }
                else if (body is MemoryStream)
                {
                    cachedStreamStart = body.Position;
                    cachedBody        = ((MemoryStream)body).ToArray();
                }
                else
                {
                    cachedStreamStart = body.Position;
                    using (var mem = new MemoryStream())
                    {
                        await body.CopyToAsync(mem);

                        cachedBody = mem.ToArray();
                    }
                }
            }

            while (true)
            {
                try
                {
                    if (cachedBody == null)
                    {
                        return(await this.RequestJsonString(host, routeName, routeStyle, requestArg, body));
                    }
                    else
                    {
                        using (var mem = new MemoryStream(cachedBody, writable: false))
                        {
                            mem.Position = cachedStreamStart;
                            return(await this.RequestJsonString(host, routeName, routeStyle, requestArg, mem));
                        }
                    }
                }
                catch (RetryException re)
                {
                    if (!re.IsRateLimit)
                    {
                        // dropbox maps 503 - ServiceUnavailable to be a rate limiting error.
                        // do not count a rate limiting error as an attempt
                        attempt++;
                    }

                    if (attempt > maxRetries)
                    {
                        throw;
                    }
                }

                // use exponential backoff
                var backoff = TimeSpan.FromSeconds(Math.Pow(2, attempt) * r.NextDouble());
#if DOCUMENTATION_BUILD
                await Task.Delay(backoff);
#else
                await TaskEx.Delay(backoff);
#endif
            }
        }
        private async void ClickSwitch(Object obj)
        {
            switch (obj.ToString())
            {
            case "buscar":
                PopulateListado();
                break;

            case "menu_editar":
                if (SelectedItem != null)
                {
                    EditarVisible       = true;
                    NuevoVisible        = false;
                    GuardarMenuEnabled  = true;
                    AgregarMenuEnabled  = false;
                    EliminarMenuEnabled = false;
                    EditarMenuEnabled   = false;
                    CancelarMenuEnabled = true;
                    AyudaMenuEnabled    = true;
                    SalirMenuEnabled    = true;
                    ExportarMenuEnabled = false;
                    AgregarVisible      = true;
                    bandera_editar      = true;
                    FocusText           = true;
                    #region Obtener Valores
                    PopulateDetalle();
                    #endregion Obtener Valores
                }
                else
                {
                    bandera_editar = false;
                    var met = Application.Current.Windows[0] as MetroWindow;
                    await met.ShowMessageAsync("Validación", "Debe seleccionar una opción.");
                }
                break;

            case "menu_agregar":
                EditarVisible       = false;
                NuevoVisible        = true;
                GuardarMenuEnabled  = true;
                AgregarMenuEnabled  = false;
                EliminarMenuEnabled = false;
                EditarMenuEnabled   = false;
                CancelarMenuEnabled = true;
                AyudaMenuEnabled    = true;
                SalirMenuEnabled    = true;
                ExportarMenuEnabled = false;
                AgregarVisible      = true;
                bandera_editar      = false;
                FocusText           = true;
                /********************************/
                Limpiar();
                SelectedEstatus    = ListEstatus.LISTA_ESTATUS.Where(w => w.CLAVE == "S").FirstOrDefault();
                Rol                = -1;
                LstMensajeRol      = new ObservableCollection <MENSAJE_ROL>();
                SelectedMensajeRol = null;
                setValidationRules();
                /********************************/
                break;

            case "menu_guardar":
                if (!base.HasErrors)
                {
                    EditarVisible       = false;
                    NuevoVisible        = false;
                    GuardarMenuEnabled  = false;
                    AgregarMenuEnabled  = true;
                    EliminarMenuEnabled = false;
                    EditarMenuEnabled   = false;
                    CancelarMenuEnabled = false;
                    AyudaMenuEnabled    = true;
                    SalirMenuEnabled    = true;
                    ExportarMenuEnabled = true;
                    AgregarVisible      = false;
                    /**********************************/
                    if (Guardar())
                    {
                        PopulateListado();
                    }
                    else
                    {
                        new Dialogos().NotificacionDialog("Error", "Al guardar información");
                    }
                    /**********************************/
                }
                else
                {
                    FocusText = true;
                }
                break;

            case "menu_cancelar":
                NuevoVisible        = false;
                GuardarMenuEnabled  = false;
                AgregarMenuEnabled  = true;
                EliminarMenuEnabled = false;
                EditarMenuEnabled   = false;
                CancelarMenuEnabled = false;
                AyudaMenuEnabled    = true;
                SalirMenuEnabled    = true;
                ExportarMenuEnabled = true;
                AgregarVisible      = false;
                /****************************************/
                Limpiar();
                /****************************************/
                break;

            case "menu_eliminar":
                var metro = Application.Current.Windows[0] as MetroWindow;
                if (SelectedItem != null)
                {
                    var mySettings = new MetroDialogSettings()
                    {
                        AffirmativeButtonText = "Aceptar",
                        NegativeButtonText    = "Cancelar",
                        AnimateShow           = true,
                        AnimateHide           = false
                    };
                    var result = await metro.ShowMessageAsync("Borrar", "¿Está seguro que desea borrar esto? [ " + SelectedItem.DESCR.Trim() + " ]", MessageDialogStyle.AffirmativeAndNegative, mySettings);

                    if (result == MessageDialogResult.Affirmative)
                    {
                        if (Eliminar())
                        {
                            PopulateListado();
                        }
                        var dialog = (BaseMetroDialog)metro.Resources["ConfirmacionDialog"];
                        await metro.ShowMetroDialogAsync(dialog);

                        await TaskEx.Delay(1500);

                        await metro.HideMetroDialogAsync(dialog);
                    }
                }
                else
                {
                    await metro.ShowMessageAsync("Validación", "Debe seleccionar una opción");
                }
                SeleccionIndice = -1;
                break;

            case "menu_exportar":
                SeleccionIndice = -1;
                Cambio          = string.Empty;
                break;

            case "menu_ayuda":
                SeleccionIndice = -1;
                Cambio          = string.Empty;
                break;

            case "menu_salir":
                SeleccionIndice = -1;
                Cambio          = string.Empty;
                PrincipalViewModel.SalirMenu();
                break;

            case "cambiar_color":
                TipoColor  = 1;   //BACKGROUND
                ColorPopUp = Color;
                PopUpsViewModels.ShowPopUp(this, PopUpsViewModels.TipoPopUp.SELECCIONA_COLOR);
                break;

            case "seleccionar_color":
                Color = ColorPopUp;
                PopUpsViewModels.ClosePopUp(PopUpsViewModels.TipoPopUp.SELECCIONA_COLOR);
                break;

            case "cancelar_color":
                PopUpsViewModels.ClosePopUp(PopUpsViewModels.TipoPopUp.SELECCIONA_COLOR);
                break;

            case "addRol":
                AgregarRol();
                break;

            case "delRol":
                EliminarMensajeRol();
                break;
            }
        }
示例#23
0
            public async Task <bool> MoveNextAsync()
            {
                ISegment[] segments;
                while (true)
                {
                    ConfiguredTaskAwaitable configuredTaskAwaitable = _segmentManager.CheckReload(_index).ConfigureAwait(false);
                    await configuredTaskAwaitable;
                    bool  isDynamicPlaylist;
                    int   startIndex;
                    lock (_segmentManager._segmentLock)
                    {
                        isDynamicPlaylist = _segmentManager._isDynamicPlaylist;
                        segments          = _segmentManager._segments;
                        startIndex        = _segmentManager._startSegmentIndex;
                    }

                    if (null != segments)
                    {
                        if (!ReferenceEquals(segments, _segments))
                        {
                            if (null != _segments)
                            {
                                _index = FindNewIndex(_segments, segments, _index);
                            }
                            else if (-1 == _index)
                            {
                                _index = startIndex;
                            }
                            _segments = segments;
                        }
                        if (_index + 1 >= segments.Length)
                        {
                            if (isDynamicPlaylist)
                            {
                                int delay = 5000;
                                if (0 < segments.Length)
                                {
                                    ISegment segment  = segments[segments.Length - 1];
                                    TimeSpan?duration = segment.Duration;
                                    if (duration.HasValue)
                                    {
                                        duration = segment.Duration;
                                        if (duration != null)
                                        {
                                            delay = (int)(duration.Value.TotalMilliseconds / 2.0);
                                        }
                                    }
                                }
                                configuredTaskAwaitable = TaskEx.Delay(delay, _segmentManager.CancellationToken).ConfigureAwait(false);
                                await configuredTaskAwaitable;
                            }
                            else
                            {
                                return(false);
                            }
                        }
                        else
                        {
                            Current = segments[++_index];
                            return(true);
                        }
                    }
                    else
                    {
                        break;
                    }
                }

                return(false);
            }
示例#24
0
        private async void OnBuscarPorHuella(string obj = "")
        {
            await Task.Factory.StartNew(() => PopUpsViewModels.ShowPopUp(this, PopUpsViewModels.TipoPopUp.OSCURECER_FONDO));

            await TaskEx.Delay(400);

            var nRet    = -1;
            var bandera = true;
            var requiereGuardarHuellas = Parametro.GuardarHuellaEnBusquedaEstatusAdministrativo;

            if (requiereGuardarHuellas)
            {
                try
                {
                    nRet = CLSFPCaptureDllWrapper.CLS_Initialize();
                }
                catch
                {
                    bandera = false;
                }
            }
            else
            {
                bandera = false;
            }

            var windowBusqueda = new BusquedaHuella();

            windowBusqueda.DataContext = new BusquedaHuellaViewModel(enumTipoPersona.IMPUTADO, nRet == 0, requiereGuardarHuellas);

            if (nRet != 0 ? ((ControlPenales.Clases.FingerPrintScanner)(windowBusqueda.DataContext)).Readers.Count == 0 : false)
            {
                PopUpsViewModels.ClosePopUp(PopUpsViewModels.TipoPopUp.OSCURECER_FONDO);
                PopUpsViewModels.ClosePopUp(PopUpsViewModels.TipoPopUp.HUELLAS);
                StaticSourcesViewModel.Mensaje("ADVERTENCIA", "ASEGURESE DE CONECTAR SU LECTOR DE HUELLA DIGITAL", StaticSourcesViewModel.enumTipoMensaje.MENSAJE_INFORMACION, 5);
                return;
            }

            windowBusqueda.Owner    = PopUpsViewModels.MainWindow;
            windowBusqueda.KeyDown += (s, e) =>
            {
                try
                {
                    if (e.Key == System.Windows.Input.Key.Escape)
                    {
                        windowBusqueda.Close();
                    }
                }
                catch (Exception ex)
                {
                    StaticSourcesViewModel.ShowMessageError("Algo pasó...", "Ocurrió un error al buscar", ex);
                }
            };
            windowBusqueda.Closed += (s, e) =>
            {
                try
                {
                    HuellasCapturadas = ((BusquedaHuellaViewModel)windowBusqueda.DataContext).HuellasCapturadas;
                    if (bandera == true)
                    {
                        CLSFPCaptureDllWrapper.CLS_Terminate();
                    }
                    PopUpsViewModels.ClosePopUp(PopUpsViewModels.TipoPopUp.OSCURECER_FONDO);

                    if (!((BusquedaHuellaViewModel)windowBusqueda.DataContext).IsSucceed)
                    {
                        return;
                    }

                    Imputado = ((BusquedaHuellaViewModel)windowBusqueda.DataContext).SelectRegistro != null ? ((BusquedaHuellaViewModel)windowBusqueda.DataContext).SelectRegistro.Imputado : null;

                    if (Imputado == null)
                    {
                        new Dialogos().ConfirmacionDialogo("Validación", "Favor de autentificar al interno por medio de huella");
                        return;
                    }
                    else
                    {
                        if (SelectedAtencionCita != null)
                        {
                            if (SelectedAtencionCita.INGRESO != null)
                            {
                                if (Imputado.ID_CENTRO == SelectedAtencionCita.INGRESO.ID_CENTRO && Imputado.ID_ANIO == SelectedAtencionCita.INGRESO.ID_ANIO && Imputado.ID_IMPUTADO == SelectedAtencionCita.ID_IMPUTADO)
                                {
                                    TabControlEnabled = MenuGuardarEnabled = true;
                                    BHuellasEnabled   = false;
                                }
                                else
                                {
                                    new Dialogos().ConfirmacionDialogo("Validación", "El interno no coincide con el solicitado");
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    StaticSourcesViewModel.ShowMessageError("Algo pasó...", "Ocurrió un error al cerrar busqueda", ex);
                }
            };
            windowBusqueda.ShowDialog();
            //AceptarBusquedaHuellaFocus = true;
        }
示例#25
0
        /// <summary>
        /// Creates a vault
        /// </summary>
        /// <param name='cloudServiceName'>
        /// Required. The name of the cloud service containing the job
        /// collection.
        /// </param>
        /// <param name='vaultName'>
        /// Required. The name of the vault to create.
        /// </param>
        /// <param name='vaultCreationInput'>
        /// Required. Vault object to be created
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The response body contains the status of the specified asynchronous
        /// operation, indicating whether it has succeeded, is inprogress, or
        /// has failed. Note that this status is distinct from the HTTP status
        /// code returned for the Get Operation Status operation itself.  If
        /// the asynchronous operation succeeded, the response body includes
        /// the HTTP status code for the successful request.  If the
        /// asynchronous operation failed, the response body includes the HTTP
        /// status code for the failed request, and also includes error
        /// information regarding the failure.
        /// </returns>
        public async Task <RecoveryServicesOperationStatusResponse> CreateAsync(string cloudServiceName, string vaultName, VaultCreateArgs vaultCreationInput, CancellationToken cancellationToken)
        {
            RecoveryServicesManagementClient client = this.Client;
            bool   shouldTrace  = TracingAdapter.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("cloudServiceName", cloudServiceName);
                tracingParameters.Add("vaultName", vaultName);
                tracingParameters.Add("vaultCreationInput", vaultCreationInput);
                TracingAdapter.Enter(invocationId, this, "CreateAsync", tracingParameters);
            }

            cancellationToken.ThrowIfCancellationRequested();
            VaultCreateResponse response = await client.Vaults.BeginCreatingAsync(cloudServiceName, vaultName, vaultCreationInput, cancellationToken).ConfigureAwait(false);

            cancellationToken.ThrowIfCancellationRequested();
            RecoveryServicesOperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);

            int delayInSeconds = 15;

            if (client.LongRunningOperationInitialTimeout >= 0)
            {
                delayInSeconds = client.LongRunningOperationInitialTimeout;
            }
            while ((result.Status != RecoveryServicesOperationStatus.InProgress) == false)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);

                cancellationToken.ThrowIfCancellationRequested();
                result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);

                delayInSeconds = 10;
                if (client.LongRunningOperationRetryTimeout >= 0)
                {
                    delayInSeconds = client.LongRunningOperationRetryTimeout;
                }
            }

            if (shouldTrace)
            {
                TracingAdapter.Exit(invocationId, result);
            }

            if (result.Status != RecoveryServicesOperationStatus.Succeeded)
            {
                if (result.Error != null)
                {
                    CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
                    ex.Error         = new CloudError();
                    ex.Error.Code    = result.Error.Code;
                    ex.Error.Message = result.Error.Message;
                    if (shouldTrace)
                    {
                        TracingAdapter.Error(invocationId, ex);
                    }
                    throw ex;
                }
                else
                {
                    CloudException ex = new CloudException("");
                    if (shouldTrace)
                    {
                        TracingAdapter.Error(invocationId, ex);
                    }
                    throw ex;
                }
            }

            result.ETag = response.ETag;
            return(result);
        }
        private async void ClickSwitch(Object obj)
        {
            switch (obj.ToString())
            {
            case "buscar":
                this.GetTiposVisitas();
                break;

            case "menu_editar":
                if (SelectedItem != null)
                {
                    HeaderAgregar = "Editar Tipo de Visita";
                    #region visiblePantalla
                    EditarVisible       = true;
                    NuevoVisible        = false;
                    GuardarMenuEnabled  = true;
                    AgregarMenuEnabled  = false;
                    EliminarMenuEnabled = false;
                    EditarMenuEnabled   = false;
                    CancelarMenuEnabled = true;
                    AyudaMenuEnabled    = true;
                    SalirMenuEnabled    = true;
                    ExportarMenuEnabled = false;
                    AgregarVisible      = true;
                    #endregion
                    bandera_editar = true;
                    FocusText      = true;
                    /*****************************************/
                    Clave           = SelectedItem.ID_TIPO_VISITA;
                    Descripcion     = SelectedItem.DESCR == null ? SelectedItem.DESCR : SelectedItem.DESCR.TrimEnd();
                    SelectedEstatus = Lista_Estatus.LISTA_ESTATUS.Where(w => w.CLAVE == SelectedItem.ESTATUS).SingleOrDefault();
                    //PopularEstatusCombo();
                    /*****************************************/
                }
                else
                {
                    bandera_editar = false;
                    var met = Application.Current.Windows[0] as MetroWindow;
                    await met.ShowMessageAsync("Validación", "Debe seleccionar una opción.");
                }
                break;

            case "menu_agregar":
                HeaderAgregar = "Agregar Nuevo Tipo de Visita";
                #region visiblePantalla
                EditarVisible       = false;
                NuevoVisible        = true;
                GuardarMenuEnabled  = true;
                AgregarMenuEnabled  = false;
                EliminarMenuEnabled = false;
                EditarMenuEnabled   = false;
                CancelarMenuEnabled = true;
                AyudaMenuEnabled    = true;
                SalirMenuEnabled    = true;
                ExportarMenuEnabled = false;
                AgregarVisible      = true;
                #endregion
                bandera_editar = false;
                FocusText      = true;
                /********************************/
                SeleccionIndice = -1;
                Clave           = 0;
                SelectedEstatus = Lista_Estatus.LISTA_ESTATUS.Where(w => w.CLAVE == "S").FirstOrDefault();
                //LimpiarTipoVisita();
                /********************************/
                break;

            case "menu_guardar":
                if (!string.IsNullOrEmpty(Descripcion))
                {
                    #region visiblePantalla
                    EditarVisible       = false;
                    NuevoVisible        = false;
                    GuardarMenuEnabled  = false;
                    AgregarMenuEnabled  = true;
                    EliminarMenuEnabled = false;
                    EditarMenuEnabled   = false;
                    CancelarMenuEnabled = false;
                    AyudaMenuEnabled    = true;
                    SalirMenuEnabled    = true;
                    ExportarMenuEnabled = true;
                    AgregarVisible      = false;
                    #endregion
                    /**********************************/
                    this.GuardarTipoVisita();
                    /**********************************/
                }
                else
                {
                    FocusText = true;
                }

                break;

            case "menu_cancelar":
                #region visiblePantalla
                NuevoVisible        = false;
                GuardarMenuEnabled  = false;
                AgregarMenuEnabled  = true;
                EliminarMenuEnabled = false;
                EditarMenuEnabled   = false;
                CancelarMenuEnabled = false;
                AyudaMenuEnabled    = true;
                SalirMenuEnabled    = true;
                ExportarMenuEnabled = true;
                AgregarVisible      = false;
                #endregion
                /****************************************/
                SeleccionIndice = -1;
                Clave           = 0;
                Descripcion     = string.Empty;
                Busqueda        = string.Empty;
                SelectedEstatus = null;
                this.GetTiposVisitas();
                /****************************************/
                break;

            case "menu_eliminar":
                var metro = Application.Current.Windows[0] as MetroWindow;
                if (SelectedItem != null)
                {
                    var mySettings = new MetroDialogSettings()
                    {
                        AffirmativeButtonText = "Aceptar",
                        NegativeButtonText    = "Cancelar",
                        AnimateShow           = true,
                        AnimateHide           = false
                    };
                    var result = await metro.ShowMessageAsync("Borrar", "¿Está seguro que desea borrar esto? [ " + SelectedItem.DESCR + " ]", MessageDialogStyle.AffirmativeAndNegative, mySettings);

                    if (result == MessageDialogResult.Affirmative)
                    {
                        BaseMetroDialog dialog;
                        if (this.EliminarTipoVisita())
                        {
                            dialog = (BaseMetroDialog)metro.Resources["ConfirmacionDialog"];
                        }
                        else
                        {
                            dialog = (BaseMetroDialog)metro.Resources["ErrorDialog"];
                        }
                        await metro.ShowMetroDialogAsync(dialog);

                        await TaskEx.Delay(1500);

                        await metro.HideMetroDialogAsync(dialog);
                    }
                }
                else
                {
                    await metro.ShowMessageAsync("Validación", "Debe seleccionar una opción");
                }
                SeleccionIndice = -1;
                break;

            case "menu_exportar":
                SeleccionIndice = -1;
                Cambio          = string.Empty;
                break;

            case "menu_ayuda":
                SeleccionIndice = -1;
                Cambio          = string.Empty;
                break;

            case "menu_salir":
                SeleccionIndice = -1;
                Cambio          = string.Empty;
                PrincipalViewModel.SalirMenu();
                break;
            }
        }
示例#27
0
 static async Task F() => await TaskEx.Delay(10000);
示例#28
0
        /// <summary>
        /// The New Dedicated Circuit Link operation creates a new dedicated
        /// circuit link.
        /// </summary>
        /// <param name='serviceKey'>
        /// Required.
        /// </param>
        /// <param name='vnetName'>
        /// Required.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The Get Dedicated Circuit Link operation response.
        /// </returns>
        public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.Management.ExpressRoute.Models.DedicatedCircuitLinkGetResponse> NewAsync(string serviceKey, string vnetName, CancellationToken cancellationToken)
        {
            ExpressRouteManagementClient client = this.Client;
            bool   shouldTrace  = CloudContext.Configuration.Tracing.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = Tracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("serviceKey", serviceKey);
                tracingParameters.Add("vnetName", vnetName);
                Tracing.Enter(invocationId, this, "NewAsync", tracingParameters);
            }
            try
            {
                if (shouldTrace)
                {
                    client = this.Client.WithHandler(new ClientRequestTrackingHandler(invocationId));
                }

                cancellationToken.ThrowIfCancellationRequested();
                ExpressRouteOperationResponse originalResponse = await client.DedicatedCircuitLinks.BeginNewAsync(serviceKey, vnetName, cancellationToken).ConfigureAwait(false);

                cancellationToken.ThrowIfCancellationRequested();
                ExpressRouteOperationStatusResponse result = await client.GetOperationStatusAsync(originalResponse.OperationId, cancellationToken).ConfigureAwait(false);

                int delayInSeconds = 30;
                while (result.Status == ExpressRouteOperationStatus.InProgress)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);

                    cancellationToken.ThrowIfCancellationRequested();
                    result = await client.GetOperationStatusAsync(originalResponse.OperationId, cancellationToken).ConfigureAwait(false);

                    delayInSeconds = 10;
                }

                if (result.Status == ExpressRouteOperationStatus.Failed)
                {
                    string exStr = "A new dedicated circuit link could not be created due to an internal server error.";
                    throw new ArgumentException(exStr);
                }
                cancellationToken.ThrowIfCancellationRequested();
                DedicatedCircuitLinkGetResponse getResult = await client.DedicatedCircuitLinks.GetAsync(serviceKey, vnetName, cancellationToken).ConfigureAwait(false);

                if (shouldTrace)
                {
                    Tracing.Exit(invocationId, result);
                }

                return(getResult);
            }
            finally
            {
                if (client != null && shouldTrace)
                {
                    client.Dispose();
                }
            }
        }
示例#29
0
        private async void ClickSwitch(Object obj)
        {
            switch (obj.ToString())
            {
            case "buscar":
                this.GetTipoAutoridad();
                break;

            case "menu_editar":
                if (SelectedItem != null)
                {
                    HeaderAgregar = "Editar Tipo de Autoridad";
                    #region visiblePantalla
                    EditarVisible       = true;
                    NuevoVisible        = false;
                    GuardarMenuEnabled  = true;
                    AgregarMenuEnabled  = false;
                    EliminarMenuEnabled = false;
                    EditarMenuEnabled   = false;
                    CancelarMenuEnabled = true;
                    AyudaMenuEnabled    = true;
                    SalirMenuEnabled    = true;
                    ExportarMenuEnabled = false;
                    AgregarVisible      = true;
                    #endregion
                    bandera_editar = true;
                    FocusText      = true;
                    /*****************************************/
                    Clave       = SelectedItem.ID_AUTORIDAD_INTERNA;
                    Descripcion = SelectedItem.DESCR;
                    /*****************************************/
                }
                else
                {
                    bandera_editar = false;
                    var met = Application.Current.Windows[0] as MetroWindow;
                    await met.ShowMessageAsync("Validación", "Debe seleccionar una opción.");
                }
                break;

            case "menu_agregar":
                HeaderAgregar = "Agregar Nuevo Tipo de Autoridad";
                #region visiblePantalla
                EditarVisible       = false;
                NuevoVisible        = true;
                GuardarMenuEnabled  = true;
                AgregarMenuEnabled  = false;
                EliminarMenuEnabled = false;
                EditarMenuEnabled   = false;
                CancelarMenuEnabled = true;
                AyudaMenuEnabled    = true;
                SalirMenuEnabled    = true;
                ExportarMenuEnabled = false;
                AgregarVisible      = true;
                #endregion
                bandera_editar = false;
                FocusText      = true;
                /********************************/
                SeleccionIndice = -1;
                Clave           = 0;
                /********************************/
                break;

            case "menu_guardar":
                if (!string.IsNullOrEmpty(Descripcion))
                {
                    #region visiblePantalla
                    EditarVisible       = false;
                    NuevoVisible        = false;
                    GuardarMenuEnabled  = false;
                    AgregarMenuEnabled  = true;
                    EliminarMenuEnabled = false;
                    EditarMenuEnabled   = false;
                    CancelarMenuEnabled = false;
                    AyudaMenuEnabled    = true;
                    SalirMenuEnabled    = true;
                    ExportarMenuEnabled = true;
                    AgregarVisible      = false;
                    #endregion
                    /**********************************/
                    this.Guardar();
                    /**********************************/
                }
                else
                {
                    FocusText = true;
                }
                break;

            case "menu_cancelar":
                #region visiblePantalla
                NuevoVisible        = false;
                GuardarMenuEnabled  = false;
                AgregarMenuEnabled  = true;
                EliminarMenuEnabled = false;
                EditarMenuEnabled   = false;
                CancelarMenuEnabled = false;
                AyudaMenuEnabled    = true;
                SalirMenuEnabled    = true;
                ExportarMenuEnabled = true;
                AgregarVisible      = false;
                #endregion
                /****************************************/
                SeleccionIndice = -1;
                Clave           = 0;
                Descripcion     = string.Empty;
                Busqueda        = string.Empty;
                this.GetTipoAutoridad();
                /****************************************/
                break;

            case "menu_eliminar":
                var metro = Application.Current.Windows[0] as MetroWindow;
                if (SelectedItem != null)
                {
                    var mySettings = new MetroDialogSettings()
                    {
                        AffirmativeButtonText = "Aceptar",
                        NegativeButtonText    = "Cancelar",
                        AnimateShow           = true,
                        AnimateHide           = false
                    };
                    var result = await metro.ShowMessageAsync("Eliminar", "¿Está seguro que desea eliminar... [ " + SelectedItem.DESCR + " ]?", MessageDialogStyle.AffirmativeAndNegative, mySettings);

                    if (result == MessageDialogResult.Affirmative)
                    {
                        BaseMetroDialog dialog;
                        if (this.Eliminar())
                        {
                            dialog = (BaseMetroDialog)metro.Resources["ConfirmacionDialog"];
                        }
                        else
                        {
                            dialog = (BaseMetroDialog)metro.Resources["ErrorDialog"];
                        }
                        await metro.ShowMetroDialogAsync(dialog);

                        await TaskEx.Delay(1500);

                        await metro.HideMetroDialogAsync(dialog);
                    }
                }
                else
                {
                    await metro.ShowMessageAsync("Validación", "Debe seleccionar una opción");
                }
                SeleccionIndice = -1;
                break;

            case "menu_exportar":
                SeleccionIndice = -1;
                Cambio          = string.Empty;
                break;

            case "menu_ayuda":
                SeleccionIndice = -1;
                Cambio          = string.Empty;
                break;

            case "menu_salir":
                SeleccionIndice = -1;
                Cambio          = string.Empty;
                PrincipalViewModel.SalirMenu();
                break;
            }
        }
        private async void clickSwitch(Object obj)
        {
            var metro = Application.Current.Windows[0] as MetroWindow;

            switch (obj.ToString())
            {
            case "menu_editar":
                if (_selectedItem != null)
                {
                    IngredientesVisible = true;
                    NuevaRecetaVisible  = true;
                    BotonesVisible      = false;

                    bandera_editar = true;
                    FocusText      = true;

                    Cambio = _selectedItem.Username;

                    GuardarMenuEnabled  = true;
                    AgregarMenuEnabled  = false;
                    EliminarMenuEnabled = false;
                    EditarMenuEnabled   = false;
                    CancelarMenuEnabled = true;
                    AyudaMenuEnabled    = true;
                    SalirMenuEnabled    = true;
                    ExportarMenuEnabled = true;
                    CheckVisible        = true;
                    int i = 0;
                    if (_selectedItem.Password == "12345")
                    {
                        foreach (var item in ListItems2)
                        {
                            if (i % 2 == 0)
                            {
                                item.IsSelected = true;
                            }
                            else
                            {
                                item.IsSelected = false;
                            }
                            i = i + 1;
                        }
                    }
                    else
                    {
                        foreach (var item in ListItems2)
                        {
                            if (i % 2 == 0)
                            {
                                item.IsSelected = false;
                            }
                            else
                            {
                                item.IsSelected = true;
                            }
                            i = i + 1;
                        }
                    }
                }
                else
                {
                    bandera_editar = false;
                    await metro.ShowMessageAsync("Validación", "Debe seleccionar una opcion.");
                }
                break;

            case "menu_agregar":
                IngredientesVisible = false;
                NuevaRecetaVisible  = true;
                BotonesVisible      = true;

                bandera_editar = false;
                FocusText      = true;

                Cambio = string.Empty;

                GuardarMenuEnabled  = true;
                AgregarMenuEnabled  = false;
                EliminarMenuEnabled = false;
                EditarMenuEnabled   = false;
                CancelarMenuEnabled = true;
                AyudaMenuEnabled    = true;
                SalirMenuEnabled    = true;
                ExportarMenuEnabled = true;
                //CheckVisible = false;
                break;

            case "boton_agregar_ingrediente":
                if (_ingredienteSeleccionado != null)
                {
                    IngredientesVisible = false;
                    NuevaRecetaVisible  = false;

                    bandera_editar = false;
                    FocusText      = false;

                    GuardarMenuEnabled  = false;
                    AgregarMenuEnabled  = true;
                    EliminarMenuEnabled = false;
                    EditarMenuEnabled   = false;
                    CancelarMenuEnabled = false;
                    AyudaMenuEnabled    = true;
                    SalirMenuEnabled    = true;
                    ExportarMenuEnabled = true;
                    CheckVisible        = false;
                    _ingredienteSeleccionado.Cantidad = Cantidad;
                }
                else
                {
                    await metro.ShowMessageAsync("Validación", "Debe seleccionar una opcion.");
                }
                break;

            case "boton_cancelar_ingrediente":
                IngredientesVisible = false;
                NuevaRecetaVisible  = false;

                bandera_editar = false;
                FocusText      = false;

                GuardarMenuEnabled  = false;
                AgregarMenuEnabled  = true;
                EliminarMenuEnabled = false;
                EditarMenuEnabled   = false;
                CancelarMenuEnabled = false;
                AyudaMenuEnabled    = true;
                SalirMenuEnabled    = true;
                ExportarMenuEnabled = true;
                CheckVisible        = false;
                break;

            case "menu_guardar":
                if (bandera_editar == false)
                {
                    _selectedItem = null;
                    _selectedItem = new Usuario()
                    {
                        Username = Cambio, Password = "******"
                    };
                    ListItems.Add(_selectedItem);
                    IngredientesVisible = true;
                    NuevaRecetaVisible  = false;
                    AgregarMenuEnabled  = false;
                    ListItems2.Clear();
                    if (_selectedItem.Password == "12345")
                    {
                        ListItems2.Add(new DetalleTraspaso()
                        {
                            Cantidad = "3", IsSelected = true, UnidadMedida = "KILOS", Producto = "TOMATE"
                        });
                        ListItems2.Add(new DetalleTraspaso()
                        {
                            Cantidad = "2", IsSelected = false, UnidadMedida = "KILOS", Producto = "CEBOLLA"
                        });
                        ListItems2.Add(new DetalleTraspaso()
                        {
                            Cantidad = "5", IsSelected = true, UnidadMedida = "KILOS", Producto = "CHILE"
                        });
                    }
                    else
                    {
                        ListItems2.Add(new DetalleTraspaso()
                        {
                            Cantidad = "4", IsSelected = true, UnidadMedida = "KILOS", Producto = "CARNE MOLIDA"
                        });
                        ListItems2.Add(new DetalleTraspaso()
                        {
                            Cantidad = "8", IsSelected = false, UnidadMedida = "KILOS", Producto = "TOMATE"
                        });
                        ListItems2.Add(new DetalleTraspaso()
                        {
                            Cantidad = "6", IsSelected = false, UnidadMedida = "KILOS", Producto = "CEBOLLA"
                        });
                    }
                }
                else
                {
                    SelectedItem.Username = Cambio;
                    IngredientesVisible   = false;
                    NuevaRecetaVisible    = false;
                }

                bandera_editar = false;
                FocusText      = false;

                SelectedItem    = null;
                SeleccionIndice = -1;
                Cambio          = string.Empty;

                GuardarMenuEnabled  = false;
                AgregarMenuEnabled  = true;
                EliminarMenuEnabled = false;
                EditarMenuEnabled   = false;
                CancelarMenuEnabled = false;
                AyudaMenuEnabled    = true;
                SalirMenuEnabled    = true;
                ExportarMenuEnabled = true;
                //CheckVisible = false;
                break;

            case "menu_cancelar":

                IngredientesVisible = false;
                NuevaRecetaVisible  = false;

                bandera_editar = false;
                FocusText      = false;

                SelectedItem    = null;
                SeleccionIndice = -1;
                Cambio          = string.Empty;

                GuardarMenuEnabled  = false;
                AgregarMenuEnabled  = true;
                EliminarMenuEnabled = false;
                EditarMenuEnabled   = false;
                CancelarMenuEnabled = false;
                AyudaMenuEnabled    = true;
                SalirMenuEnabled    = true;
                ExportarMenuEnabled = true;
                CheckVisible        = false;
                break;

            case "menu_eliminar":
                if (_selectedItem != null)
                {
                    var mySettings = new MetroDialogSettings()
                    {
                        AffirmativeButtonText = "Aceptar",
                        NegativeButtonText    = "Cancelar",
                        AnimateShow           = true,
                        AnimateHide           = false
                    };
                    //  SALTO DE LINEA
                    // string.Format("\n")
                    var result = await metro.ShowMessageAsync("Borrar", "¿Está seguro que desea borrar esto? [ " + SelectedItem.Username + " ]", MessageDialogStyle.AffirmativeAndNegative, mySettings);

                    if (result == MessageDialogResult.Affirmative)
                    {
                        var i = ListItems.IndexOf(_selectedItem);
                        if (i >= 0)
                        {
                            ListItems.RemoveAt(i);

                            var dialog = (BaseMetroDialog)metro.Resources["ConfirmacionDialog"];
                            await metro.ShowMetroDialogAsync(dialog);

                            await TaskEx.Delay(1500);

                            await metro.HideMetroDialogAsync(dialog);

                            //MENSAJE EXTERNO
                            //dialog = dialog.ShowDialogExternally();
                            //await TaskEx.Delay(1500);
                            //await dialog.RequestCloseAsync();
                        }
                    }
                }
                else
                {
                    await metro.ShowMessageAsync("Validación", "Debe seleccionar una opcion");
                }
                SelectedItem    = null;
                SeleccionIndice = -1;
                Cambio          = string.Empty;

                GuardarMenuEnabled  = false;
                AgregarMenuEnabled  = true;
                EliminarMenuEnabled = false;
                EditarMenuEnabled   = false;
                CancelarMenuEnabled = false;
                AyudaMenuEnabled    = true;
                SalirMenuEnabled    = true;
                ExportarMenuEnabled = true;
                CheckVisible        = false;
                break;

            case "menu_exportar":
                SelectedItem    = null;
                SeleccionIndice = -1;
                break;

            case "menu_ayuda":
                SelectedItem    = null;
                SeleccionIndice = -1;
                break;

            case "menu_salir":
                SelectedItem    = null;
                SeleccionIndice = -1;
                break;
            }
        }