Ejemplo n.º 1
0
        public JsonResult CreateTask(TaskEx task)
        {
            try
            {
                // Validation
                if (!ModelState.IsValid)
                {
                    return Json(new { Result = "ERROR", Message = "Form is not valid! Please correct it and try again." });
                }

                var taskRespo = new TaskRepository();
                TaskEx addedTask = taskRespo.AddTask(task);

                // Inform all connected clients
                var clientName = Request["clientName"];
                Task.Factory.StartNew(
                    () =>
                    {
                        // var clients = Hub.GetClients<TaskHub>();
                        _context.Clients.RecCreated(clientName, task);
                    });

                // Return result to current (caller) client
                return Json(new { Result = "OK", Record = addedTask });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = ex.Message });
            }
        }
Ejemplo n.º 2
0
        async Task <(ModuleSet current, DeploymentConfigInfo DeploymentConfigInfo, Exception ex)> GetReconcileData(CancellationToken token)
        {
            // we read the data from the config source and from the environment separately because
            // when doing something like TaskEx.WhenAll(t1, t2) if either of them throws then we get
            // nothing; so for example, if the environment is able to successfully retrieve the moduleset
            // but there's a corrupt deployment in IoT Hub then we end up not being able to report the
            // current state even though we have it
            ((ModuleSet current, Exception environmentException), (DeploymentConfigInfo deploymentConfigInfo, Exception configSourceException)) = await TaskEx.WhenAll(
                this.GetCurrentModuleSetAsync(token),
                this.GetDeploymentConfigInfoAsync());

            List <Exception> exceptions = new[]
            {
                environmentException,
                configSourceException,
                deploymentConfigInfo?.Exception.OrDefault()
            }
            .Where(e => e != null)
            .ToList();

            Exception exception = null;

            if (exceptions.Any())
            {
                exception = exceptions.Count > 1 ? new AggregateException(exceptions) : exceptions[0];
            }

            return(current, deploymentConfigInfo, exception);
        }
Ejemplo n.º 3
0
 public static async Task InvokeAsync(this Dispatcher dispatcher, Action d, DispatcherPriority dispatcherPriority)
 {
     await TaskEx.Run(() => dispatcher.Invoke(d, dispatcherPriority));
 }
Ejemplo n.º 4
0
        public static async Task <T> InvokeAsync <T>(this Dispatcher dispatcher, Func <T> d)
        {
            var result = await TaskEx.Run(() => (T)dispatcher.Invoke(d));

            return(result);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// The Set Network Configuration operation asynchronously configures
        /// the virtual network.  (see
        /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157181.aspx
        /// for more information)
        /// </summary>
        /// <param name='parameters'>
        /// Required. Parameters supplied to the Set Network Configuration
        /// 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 also includes error
        /// information regarding the failure.
        /// </returns>
        public async System.Threading.Tasks.Task <OperationStatusResponse> SetConfigurationAsync(NetworkSetConfigurationParameters parameters, CancellationToken cancellationToken)
        {
            NetworkManagementClient 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, "SetConfigurationAsync", tracingParameters);
            }
            try
            {
                if (shouldTrace)
                {
                    client = this.Client.WithHandler(new ClientRequestTrackingHandler(invocationId));
                }

                cancellationToken.ThrowIfCancellationRequested();
                OperationResponse response = await client.Networks.BeginSettingConfigurationAsync(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)
                {
                    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();
                }
            }
        }
Ejemplo n.º 6
0
        private async void clickSwitch(Object obj)
        {
            switch (obj.ToString())
            {
            case "buscar":
                this.GetTipoObjetosTipos();
                break;

            case "menu_editar":
                if (SelectedItem != null)
                {
                    HeaderAgregar = "Editar Tipo Objeto";
                    #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_OBJETO_TIPO;
                    Descripcion   = SelectedItem.DESCR;
                    Configuracion = SelectedItem.CONFIGURACION;
                    Permitido     = SelectedItem.PERMITIDO;
                    /*****************************************/
                    PopularEstatusCombo();
                    var EstatusSeleccionado = SelectedItem.ESTATUS == null ? "N" : SelectedItem.ESTATUS;
                    SelectedEstatus = Lista_Estatus.LISTA_ESTATUS.Where(w => w.CLAVE == EstatusSeleccionado).SingleOrDefault();
                    setValidationRules();
                    //TODO:Falta Agregar campo estatus
                    //SelectedEstatus=ListEstatus.Where(w=>w.CLAVE==selectedItem.Id_Estatus)
                }
                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 Objeto";
                #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 = null;
                SelectedEstatus = Lista_Estatus.LISTA_ESTATUS.Where(w => w.CLAVE == "S").FirstOrDefault();
                SelectedItem    = null;
                Descripcion     = string.Empty;
                Permitido       = "N";
                Configuracion   = null;
                PopularEstatusCombo();
                setValidationRules();
                /********************************/
                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.GuardarObjetoTipo();
                    /**********************************/
                }
                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;
                Permitido       = "N";
                this.GetTipoObjetosTipos();
                /****************************************/
                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 (EliminarTipoObjeto())
                        {
                            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;
            }
        }
Ejemplo n.º 7
0
        private async Task <bool> DelayedOtherTask(string resource, CancellationToken cancelToken)
        {
            await TaskEx.Delay(1000 * 5);

            return(await OtherTask(resource, cancelToken));
        }
Ejemplo n.º 8
0
    public static async Task <String> NcbiSomeProteinAsync(params String[] ids)
    {
        IEnumerable <Task <String> > tasks = from id in ids select NcbiProteinAsync(id);

        return(await TaskEx.WhenAny(tasks).Result);
    }
Ejemplo n.º 9
0
        /// <summary>
        /// Deletes a vault
        /// </summary>
        /// <param name='resourceGroupName'>
        /// Required. The name of the (Resource Group) cloud service containing
        /// the job collection.
        /// </param>
        /// <param name='vaultName'>
        /// Required. The name of the vault to delete.
        /// </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> DeleteAsync(string resourceGroupName, string vaultName, CancellationToken cancellationToken)
        {
            SiteRecoveryVaultManagementClient 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("resourceGroupName", resourceGroupName);
                tracingParameters.Add("vaultName", vaultName);
                TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
            }

            cancellationToken.ThrowIfCancellationRequested();
            RecoveryServicesOperationStatusResponse response = await client.Vaults.BeginDeletingAsync(resourceGroupName, vaultName, cancellationToken).ConfigureAwait(false);

            if (response.Status == RecoveryServicesOperationStatus.Succeeded)
            {
                return(response);
            }
            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)
            {
                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;
                }
            }

            return(result);
        }
Ejemplo n.º 10
0
        private async void OnStartClick(object sender, RoutedEventArgs e)
        {
            string svgPath = txtSvgSource.Text;

            if (string.IsNullOrWhiteSpace(svgPath) || Directory.Exists(svgPath) == false)
            {
                return;
            }

            txtDebug.Clear();
            _imageList.Clear();

            _columnCount = 0;
            _imageCount  = 0;
            _isVerbose   = (chkVerbose.IsChecked != null && chkVerbose.IsChecked.Value);

            btnStart.IsEnabled   = false;
            chkVerbose.IsEnabled = false;

            var queue = new ConcurrentQueue <string>();

            int imageCount = 0;

            foreach (var svgFilePath in Directory.EnumerateFiles(svgPath, "*.svg"))
            {
                // Eliminate any compressed file, not supported in this test...
                if (svgFilePath.EndsWith(".svgz", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                queue.Enqueue(svgFilePath);

                imageCount++;
                if (imageCount >= NumberOfImages)
                {
                    break;
                }
            }

            AppendLine("Starting Tests ****");
            if (_isVerbose)
            {
                AppendLine("");
            }

            var allTasks = new List <Task>();

            for (int i = 0; i < NumberOfConsumers; ++i)
            {
#if DOTNET40
                allTasks.Add(TaskEx.Run(() =>
                {
                    while (queue.TryDequeue(out string imageData))
                    {
                        UpdateDrawing(imageData);
                    }
                }));
#else
                allTasks.Add(Task.Run(() =>
                {
                    while (queue.TryDequeue(out string imageData))
                    {
                        UpdateDrawing(imageData);
                    }
                }));
#endif
            }

#if DOTNET40
            await TaskEx.WhenAll(allTasks);
#else
            await Task.WhenAll(allTasks);
#endif

            AppendLine("");
            AppendLine("**** Completed Tests");

            btnStart.IsEnabled   = true;
            chkVerbose.IsEnabled = true;
        }
Ejemplo n.º 11
0
 public Task InterceptAsync(HttpRequestMessage request, CancellationToken token)
 {
     ++Calls;
     request.Headers.Add(InjectedHeader, InjectedValue);
     return(TaskEx.Delay(0));
 }
Ejemplo n.º 12
0
        public Task <bool> LoadDocumentAsync(string svgFilePath)
        {
            if (_isLoadingDrawing || string.IsNullOrWhiteSpace(svgFilePath) || !File.Exists(svgFilePath))
            {
#if DOTNET40
                return(TaskEx.FromResult <bool>(false));
#else
                return(Task.FromResult <bool>(false));
#endif
            }

            string fileExt = Path.GetExtension(svgFilePath);

            if (!(string.Equals(fileExt, SvgConverter.SvgExt, StringComparison.OrdinalIgnoreCase) ||
                  string.Equals(fileExt, SvgConverter.CompressedSvgExt, StringComparison.OrdinalIgnoreCase)))
            {
                _svgFilePath = null;
#if DOTNET40
                return(TaskEx.FromResult <bool>(false));
#else
                return(Task.FromResult <bool>(false));
#endif
            }

            _isLoadingDrawing = true;

            this.UnloadDocument(true);

            DirectoryInfo workingDir = _workingDir;
            if (_directoryInfo != null)
            {
                workingDir = _directoryInfo;
            }

            _svgFilePath = svgFilePath;
            _saveXaml    = _optionSettings.ShowOutputFile;

            _embeddedImageVisitor.SaveImages    = !_wpfSettings.IncludeRuntime;
            _embeddedImageVisitor.SaveDirectory = _drawingDir;
            _wpfSettings.Visitors.ImageVisitor  = _embeddedImageVisitor;

            if (_fileReader == null)
            {
                _fileReader          = new FileSvgReader(_wpfSettings);
                _fileReader.SaveXaml = _saveXaml;
                _fileReader.SaveZaml = false;
            }

            var drawingStream = new MemoryStream();

            // Get the UI thread's context
            var context = TaskScheduler.FromCurrentSynchronizationContext();

            return(Task <bool> .Factory.StartNew(() =>
            {
                //                var saveXaml = _fileReader.SaveXaml;
                //                _fileReader.SaveXaml = true; // For threaded, we will save to avoid loading issue later...

                //Stopwatch stopwatch = new Stopwatch();

                //stopwatch.Start();

                //DrawingGroup drawing = _fileReader.Read(svgFilePath, workingDir);

                //stopwatch.Stop();

                //Trace.WriteLine(string.Format("FileName={0}, Time={1}",
                //    Path.GetFileName(svgFilePath), stopwatch.ElapsedMilliseconds));

                Stopwatch watch = new Stopwatch();
                watch.Start();

                DrawingGroup drawing = _fileReader.Read(svgFilePath, workingDir);

                watch.Stop();

                Debug.WriteLine("{0}: {1}", Path.GetFileName(svgFilePath), watch.ElapsedMilliseconds);

                //                _fileReader.SaveXaml = saveXaml;
                _drawingDocument = _fileReader.DrawingDocument;
                if (drawing != null)
                {
                    XamlWriter.Save(drawing, drawingStream);
                    drawingStream.Seek(0, SeekOrigin.Begin);

                    return true;
                }
                _svgFilePath = null;
                return false;
            }).ContinueWith((t) => {
                try
                {
                    if (!t.Result)
                    {
                        _isLoadingDrawing = false;
                        _svgFilePath = null;
                        return false;
                    }
                    if (drawingStream.Length != 0)
                    {
                        DrawingGroup drawing = (DrawingGroup)XamlReader.Load(drawingStream);

                        svgViewer.UnloadDiagrams();
                        svgViewer.RenderDiagrams(drawing);

                        Rect bounds = svgViewer.Bounds;

                        if (bounds.IsEmpty)
                        {
                            bounds = new Rect(0, 0, svgViewer.ActualWidth, svgViewer.ActualHeight);
                        }

                        zoomPanControl.AnimatedZoomTo(bounds);
                        CommandManager.InvalidateRequerySuggested();

                        // The drawing changed, update the source...
                        _fileReader.Drawing = drawing;
                    }

                    _isLoadingDrawing = false;

                    return true;
                }
                catch
                {
                    _isLoadingDrawing = false;
                    throw;
                }
            }, context));
        }
Ejemplo n.º 13
0
        async Task Reader()
        {
            var readCancelToken = new CancellationTokenSource();

            // We are going to read from the stream, but the stream *may* not ever have any data for us to
            // read (in the case that all the messages sent successfully, apple will send us nothing
            // So, let's make our read timeout after a reasonable amount of time to wait for apple to tell
            // us of any errors that happened.
            readCancelToken.CancelAfter(750);

            int len = -1;

            while (!readCancelToken.IsCancellationRequested)
            {
                // See if there's data to read
                if (client.Client.Available > 0)
                {
                    Log.Info("APNS-Client[{0}]: Data Available...", id);
                    len = await networkStream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false);

                    Log.Info("APNS-Client[{0}]: Finished Read.", id);
                    break;
                }

                // Let's not tie up too much CPU waiting...
                await TaskEx.Delay(50).ConfigureAwait(false);
            }

            Log.Info("APNS-Client[{0}]: Received {1} bytes response...", id, len);

            // If we got no data back, and we didn't end up canceling, the connection must have closed
            if (len == 0)
            {
                Log.Info("APNS-Client[{0}]: Server Closed Connection...", id);

                // Connection was closed
                disconnect();
                return;
            }
            else if (len < 0)     //If we timed out waiting, but got no data to read, everything must be ok!

            {
                Log.Info("APNS-Client[{0}]: Batch (ID={1}) completed with no error response...", id, batchId);

                //Everything was ok, let's assume all 'sent' succeeded
                foreach (var s in sent)
                {
                    s.Notification.CompleteSuccessfully();
                }

                sent.Clear();
                return;
            }

            // If we make it here, we did get data back, so we have errors

            Log.Info("APNS-Client[{0}]: Batch (ID={1}) completed with error response...", id, batchId);

            // If we made it here, we did receive some data, so let's parse the error
            var status     = buffer [1];
            var identifier = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(buffer, 2));

            // Let's handle the failure
            //Get the index of our failed notification (by identifier)
            var failedIndex = sent.FindIndex(n => n.Identifier == identifier);

            // If we didn't find an index for the failed notification, something is wrong
            // Let's just return
            if (failedIndex < 0)
            {
                return;
            }

            // Get all the notifications before the failed one and mark them as sent!
            if (failedIndex > 0)
            {
                // Get all the notifications sent before the one that failed
                // We can assume that these all succeeded
                var successful = sent.GetRange(0, failedIndex);  //TODO: Should it be failedIndex - 1?

                // Complete all the successfully sent notifications
                foreach (var s in successful)
                {
                    s.Notification.CompleteSuccessfully();
                }

                // Remove all the successful notifications from the sent list
                // This should mean the failed notification is now at index 0
                sent.RemoveRange(0, failedIndex);
            }

            //Get the failed notification itself
            var failedNotification = sent [0];

            //Fail and remove the failed index from the list
            Log.Info("APNS-Client[{0}]: Failing Notification {1}", id, failedNotification.Identifier);
            failedNotification.Notification.CompleteFailed(
                new ApnsNotificationException(status, failedNotification.Notification.Notification));

            // Now remove the failed notification from the sent list
            sent.RemoveAt(0);

            // The remaining items in the list were sent after the failed notification
            // we can assume these were ignored by apple so we need to send them again
            // Requeue the remaining notifications
            foreach (var s in sent)
            {
                notifications.Enqueue(s.Notification);
            }

            // Clear our sent list
            sent.Clear();

            // Apple will close our connection after this anyway
            disconnect();
        }
Ejemplo n.º 14
0
 public Task <bool> HasTrack()
 {
     return(TaskEx.FromResult(Player.Track != null));
 }
Ejemplo n.º 15
0
 public Task <bool> IsPlaying()
 {
     return(TaskEx.FromResult(Player.PlayerState == PlayState.Playing));
 }
Ejemplo n.º 16
0
    public static async Task <String[]> NcbiProteinParallelAsync(params String[] ids)
    {
        IEnumerable <Task <String> > tasks = from id in ids select NcbiProteinAsync(id);

        return(await TaskEx.WhenAll(tasks));
    }
Ejemplo n.º 17
0
        //------------------------------------------------------------------------------------------------------------------------
        protected override void onClose(string Message)
        {
            try
            {
                base.onClose(Message);

                //close all
                try
                {
                    if (streamIn != null)
                    {
#if NETFX
                        TaskEx.RunSafe(streamIn.Close, AssertException: false)?.Wait(1000);
#endif
                        TaskEx.RunSafe(streamIn.Dispose, AssertException: false)?.Wait(1000);
                    }
                }
                catch { }

                try
                {
                    if (streamOut != null)
                    {
#if NETFX
                        TaskEx.RunSafe(streamOut.Close, AssertException: false)?.Wait(1000);
#endif
                        TaskEx.RunSafe(streamOut.Dispose, AssertException: false)?.Wait(1000);
                    }
                }
                catch { }

#if NETFX
                try
                {
                    if (netstream != null)
                    {
                        TaskEx.RunSafe(netstream.Close, AssertException: false)?.Wait(1000);
                        TaskEx.RunSafe(netstream.Dispose, AssertException: false)?.Wait(1000);
                    }
                }
                catch { }
#endif
                try
                {
#if NETFX
                    if (_sock?.Connected == true)
                    {
                        TaskEx.RunSafe(() => _sock?.Disconnect(false), AssertException: false)?.Wait(1000);
                    }

                    TaskEx.RunSafe(() => _sock?.Close(3), AssertException: false)?.Wait(5000);
#endif
                    TaskEx.RunSafe(() => _sock?.Dispose(), AssertException: false)?.Wait(1000);
                }
                catch { }

                //null them
                streamIn  = null;
                streamOut = null;
#if NETFX
                netstream = null;
#endif
                _sock = null;
            }
            catch (Exception ex) { DebugEx.Assert(ex, "YPC (" + Name + ") Exception while disconnecting"); }
        }
        /// <summary>
        /// The Update Cross Connection operation updates an existing cross
        /// connection.
        /// </summary>
        /// <param name='serviceKey'>
        /// Required. The service key representing the relationship between
        /// Azure and the customer.
        /// </param>
        /// <param name='parameters'>
        /// Required. Parameters supplied to the Update Bgp Peering operation.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The Get Cross Connection Operation Response.
        /// </returns>
        public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.Management.ExpressRoute.Models.CrossConnectionGetResponse> UpdateAsync(string serviceKey, CrossConnectionUpdateParameters parameters, 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("parameters", parameters);
                Tracing.Enter(invocationId, this, "UpdateAsync", tracingParameters);
            }
            try
            {
                if (shouldTrace)
                {
                    client = this.Client.WithHandler(new ClientRequestTrackingHandler(invocationId));
                }

                cancellationToken.ThrowIfCancellationRequested();
                ExpressRouteOperationResponse originalResponse = await client.CrossConnections.BeginUpdateAsync(serviceKey, parameters, 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 = "The cross connection could not be updated due to an internal server error.";
                    throw new ArgumentException(exStr);
                }
                cancellationToken.ThrowIfCancellationRequested();
                CrossConnectionGetResponse getResult = await client.CrossConnections.GetAsync(serviceKey, cancellationToken).ConfigureAwait(false);

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

                return(getResult);
            }
            finally
            {
                if (client != null && shouldTrace)
                {
                    client.Dispose();
                }
            }
        }
Ejemplo n.º 19
0
        public void StartRecording(TaskSettings taskSettings, bool skipRegionSelection = false)
        {
            if (taskSettings.CaptureSettings.RunScreencastCLI)
            {
                if (!Program.Settings.VideoEncoders.IsValidIndex(taskSettings.CaptureSettings.VideoEncoderSelected))
                {
                    MessageBox.Show(Resources.ScreenRecordForm_StartRecording_There_is_no_valid_CLI_video_encoder_selected_,
                                    "ShareX", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (!Program.Settings.VideoEncoders[taskSettings.CaptureSettings.VideoEncoderSelected].IsValid())
                {
                    MessageBox.Show(Resources.ScreenRecordForm_StartRecording_CLI_video_encoder_file_does_not_exist__ +
                                    Program.Settings.VideoEncoders[taskSettings.CaptureSettings.VideoEncoderSelected].Path,
                                    "ShareX", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }

            if (taskSettings.CaptureSettings.ScreenRecordOutput == ScreenRecordOutput.FFmpeg)
            {
                if (!File.Exists(taskSettings.CaptureSettings.FFmpegOptions.CLIPath))
                {
                    string ffmpegText = string.IsNullOrEmpty(taskSettings.CaptureSettings.FFmpegOptions.CLIPath) ? "ffmpeg.exe" : taskSettings.CaptureSettings.FFmpegOptions.CLIPath;

                    if (MessageBox.Show(string.Format(Resources.ScreenRecordForm_StartRecording_does_not_exist, ffmpegText),
                                        "ShareX - " + Resources.ScreenRecordForm_StartRecording_Missing + " ffmpeg.exe", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                    {
                        if (FFmpegDownloader.DownloadFFmpeg(false, DownloaderForm_InstallRequested) == DialogResult.OK)
                        {
                            Program.DefaultTaskSettings.CaptureSettings.FFmpegOptions.CLIPath = taskSettings.TaskSettingsReference.CaptureSettings.FFmpegOptions.CLIPath =
                                taskSettings.CaptureSettings.FFmpegOptions.CLIPath            = Path.Combine(Program.ToolsFolder, "ffmpeg.exe");
                        }
                    }
                    else
                    {
                        return;
                    }
                }

                if (!taskSettings.CaptureSettings.FFmpegOptions.IsSourceSelected)
                {
                    MessageBox.Show(Resources.ScreenRecordForm_StartRecording_FFmpeg_video_and_audio_source_both_can_t_be__None__,
                                    "ShareX - " + Resources.ScreenRecordForm_StartRecording_FFmpeg_error, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }

            Rectangle captureRectangle;

            if (skipRegionSelection)
            {
                captureRectangle = Program.Settings.ScreenRecordRegion;
            }
            else
            {
                TaskHelpers.SelectRegion(out captureRectangle, taskSettings);
                captureRectangle = CaptureHelpers.EvenRectangleSize(captureRectangle);
            }

            if (IsRecording || !captureRectangle.IsValid() || screenRecorder != null)
            {
                return;
            }

            Program.Settings.ScreenRecordRegion = captureRectangle;

            IsRecording = true;
            Screenshot.CaptureCursor = taskSettings.CaptureSettings.ShowCursor;

            string trayText = "ShareX - " + Resources.ScreenRecordForm_StartRecording_Waiting___;

            TrayIcon.Text    = trayText.Truncate(63);
            TrayIcon.Icon    = Resources.control_record_yellow.ToIcon();
            TrayIcon.Visible = true;

            string path = "";

            float duration = taskSettings.CaptureSettings.ScreenRecordFixedDuration ? taskSettings.CaptureSettings.ScreenRecordDuration : 0;

            regionForm = ScreenRegionForm.Show(captureRectangle, StopRecording, duration);
            regionForm.RecordResetEvent = new ManualResetEvent(false);

            TaskEx.Run(() =>
            {
                try
                {
                    if (taskSettings.CaptureSettings.ScreenRecordAutoDisableAero)
                    {
                        dwmManager = new DWMManager();
                        dwmManager.AutoDisable();
                    }

                    if (taskSettings.CaptureSettings.ScreenRecordOutput == ScreenRecordOutput.AVI)
                    {
                        path = Path.Combine(taskSettings.CaptureFolder, TaskHelpers.GetFilename(taskSettings, "avi"));
                    }
                    else if (taskSettings.CaptureSettings.ScreenRecordOutput == ScreenRecordOutput.FFmpeg)
                    {
                        path = Path.Combine(taskSettings.CaptureFolder, TaskHelpers.GetFilename(taskSettings, taskSettings.CaptureSettings.FFmpegOptions.Extension));
                    }
                    else
                    {
                        path = Program.ScreenRecorderCacheFilePath;
                    }

                    ScreencastOptions options = new ScreencastOptions()
                    {
                        FFmpeg          = taskSettings.CaptureSettings.FFmpegOptions,
                        AVI             = taskSettings.CaptureSettings.AVIOptions,
                        ScreenRecordFPS = taskSettings.CaptureSettings.ScreenRecordFPS,
                        GIFFPS          = taskSettings.CaptureSettings.GIFFPS,
                        Duration        = duration,
                        OutputPath      = path,
                        CaptureArea     = captureRectangle,
                        DrawCursor      = taskSettings.CaptureSettings.ShowCursor
                    };

                    screenRecorder = new ScreenRecorder(options, captureRectangle, taskSettings.CaptureSettings.ScreenRecordOutput);

                    if (regionForm != null && regionForm.RecordResetEvent != null)
                    {
                        trayText      = "ShareX - " + Resources.ScreenRecordForm_StartRecording_Click_tray_icon_to_start_recording_;
                        TrayIcon.Text = trayText.Truncate(63);

                        if (taskSettings.CaptureSettings.ScreenRecordAutoStart)
                        {
                            int delay = (int)(taskSettings.CaptureSettings.ScreenRecordStartDelay * 1000);

                            if (delay > 0)
                            {
                                regionForm.RecordResetEvent.WaitOne(delay);
                            }
                        }
                        else
                        {
                            regionForm.RecordResetEvent.WaitOne();
                        }

                        if (regionForm.AbortRequested)
                        {
                            abortRequested = true;
                        }
                    }

                    if (!abortRequested)
                    {
                        trayText      = "ShareX - " + Resources.ScreenRecordForm_StartRecording_Click_tray_icon_to_stop_recording_;
                        TrayIcon.Text = trayText.Truncate(63);
                        TrayIcon.Icon = Resources.control_record.ToIcon();

                        if (regionForm != null)
                        {
                            this.InvokeSafe(() => regionForm.StartTimer());
                        }

                        screenRecorder.StartRecording();

                        if (regionForm != null && regionForm.AbortRequested)
                        {
                            abortRequested = true;
                        }
                    }
                }
                catch (Exception e)
                {
                    DebugHelper.WriteException(e);
                }
                finally
                {
                    if (dwmManager != null)
                    {
                        dwmManager.Dispose();
                        dwmManager = null;
                    }

                    if (regionForm != null)
                    {
                        if (regionForm.RecordResetEvent != null)
                        {
                            regionForm.RecordResetEvent.Dispose();
                        }

                        this.InvokeSafe(() => regionForm.Close());
                        regionForm = null;
                    }
                }

                try
                {
                    if (!abortRequested && screenRecorder != null)
                    {
                        trayText      = "ShareX - " + Resources.ScreenRecordForm_StartRecording_Encoding___;
                        TrayIcon.Text = trayText.Truncate(63);
                        TrayIcon.Icon = Resources.camcorder_pencil.ToIcon();

                        string sourceFilePath = path;

                        if (taskSettings.CaptureSettings.ScreenRecordOutput == ScreenRecordOutput.GIF)
                        {
                            if (taskSettings.CaptureSettings.RunScreencastCLI)
                            {
                                sourceFilePath = Path.ChangeExtension(Program.ScreenRecorderCacheFilePath, "gif");
                            }
                            else
                            {
                                sourceFilePath = path = Path.Combine(taskSettings.CaptureFolder, TaskHelpers.GetFilename(taskSettings, "gif"));
                            }

                            Helpers.CreateDirectoryIfNotExist(sourceFilePath);
                            screenRecorder.SaveAsGIF(sourceFilePath, taskSettings.ImageSettings.ImageGIFQuality);
                        }

                        if (taskSettings.CaptureSettings.RunScreencastCLI)
                        {
                            VideoEncoder encoder = Program.Settings.VideoEncoders[taskSettings.CaptureSettings.VideoEncoderSelected];
                            path = Path.Combine(taskSettings.CaptureFolder, TaskHelpers.GetFilename(taskSettings, encoder.OutputExtension));
                            screenRecorder.EncodeUsingCommandLine(encoder, sourceFilePath, path);
                        }
                    }
                }
                finally
                {
                    if (screenRecorder != null)
                    {
                        if (taskSettings.CaptureSettings.RunScreencastCLI && !string.IsNullOrEmpty(screenRecorder.CachePath) && File.Exists(screenRecorder.CachePath))
                        {
                            File.Delete(screenRecorder.CachePath);
                        }

                        screenRecorder.Dispose();
                        screenRecorder = null;

                        if (abortRequested && !string.IsNullOrEmpty(path) && File.Exists(path))
                        {
                            File.Delete(path);
                        }
                    }
                }
            },
                       () =>
            {
                if (TrayIcon.Visible)
                {
                    TrayIcon.Visible = false;
                }

                if (!abortRequested && !string.IsNullOrEmpty(path) && File.Exists(path) && TaskHelpers.ShowAfterCaptureForm(taskSettings))
                {
                    UploadTask task = UploadTask.CreateFileJobTask(path, taskSettings);
                    TaskManager.Start(task);
                }

                abortRequested = false;
                IsRecording    = false;
            });
        }
        private async void clickSwitch(Object obj)
        {
            switch (obj.ToString())
            {
            case "buscar_articulo_medicamento":
                SelectedItem    = null;
                SeleccionIndice = -1;
                Cambio          = string.Empty;
                break;

            case "menu_editar":
                if (_selectedItem != null)
                {
                    EditarVisible = true;
                    NuevoVisible  = false;
                    Cambio        = SelectedItem.Username;

                    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 Usuario()
                    {
                        Username = Cambio, Password = "******"
                    });
                }
                else
                {
                    SelectedItem.Username = Cambio;
                }

                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;
                Cambio          = 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;
                Cambio          = 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.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;
                break;

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

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

            case "menu_salir":
                PrincipalViewModel.SalirMenu();
                break;
            }
            if (_selectedItem == null)
            {
                EliminarMenuEnabled = false;
                EditarMenuEnabled   = false;
            }
        }
Ejemplo n.º 21
0
 public override Task DownloadAsync(CloudFile sourceFile, string destFilePath, DownloadOptions options, SingleTransferContext context, CancellationToken cancellationToken)
 {
     validateAction(sourceFile, destFilePath);
     return(TaskEx.FromResult(true));
 }
        private async void ClickSwitch(Object obj)
        {
            switch (obj.ToString())
            {
            case "buscar":
                this.GetModalidadDelito();
                break;

            case "menu_editar":
                if (SelectedItem != null)
                {
                    HeaderAgregar = "Editar Modalidad Delito";
                    #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_MODALIDAD;
                    Descripcion = SelectedItem.DESCR;
                    //Tipo = SelectedItem.ID_TIPO_DELITO;
                    // SelectedTipo = ListTipos.Where(w=>w.ID_TIPO_DELITO == SelectedItem.ID_TIPO_DELITO).FirstOrDefault();
                    /*****************************************/
                }
                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 Modalidad Delito";
                #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;
                Descripcion     = "";
                Tipo            = 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;
                Tipo            = 0;
                this.GetModalidadDelito();
                /****************************************/
                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;
                break;

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

            case "menu_salir":
                SeleccionIndice = -1;
                PrincipalViewModel.SalirMenu();
                break;
            }
        }
 public Task <IMediaParser> CreateAsync(IMediaParserParameters parameter, ContentType contentType, CancellationToken cancellationToken)
 {
     return(TaskEx.FromResult <IMediaParser>((IMediaParser)this._parserFactory()));
 }
Ejemplo n.º 24
0
        private async void clickSwitch(Object obj)
        {
            var metro = Application.Current.Windows[0] as MetroWindow;

            switch (obj.ToString())
            {
            case "boton_quitar_pedido_traspaso":
                //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 esta entrada? [ " + _selectedItem.Pedido +
                                                              ", " + _selectedItem.Almacen + ", " + _selectedItem.Fecha + " ]", MessageDialogStyle.AffirmativeAndNegative, mySettings);

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

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

                            await TaskEx.Delay(1500);

                            await metro.HideMetroDialogAsync(dialog);

                            DetallePedidoVisible = false;
                            FiltrarVisible       = true;
                            BotonesVisible       = false;
                            SeleccionIndice      = -1;

                            //MENSAJE EXTERNO
                            //dialog = dialog.ShowDialogExternally();
                            //await TaskEx.Delay(1500);
                            //await dialog.RequestCloseAsync();
                        }
                    }
                }
                else
                {
                    await metro.ShowMessageAsync("Validación", "Debe seleccionar una opcion");
                }
                break;

            case "boton_aceptar_pedido_traspaso":
                if (_selectedItem != null)
                {
                    var mySettings = new MetroDialogSettings()
                    {
                        AffirmativeButtonText = "Aceptar",
                        NegativeButtonText    = "Cancelar",
                        AnimateShow           = true,
                        AnimateHide           = false
                    };
                    var result = await metro.ShowMessageAsync("Aceptar Traspaso", "¿Está seguro que desea aceptar esta entrada? [ " + _selectedItem.Pedido +
                                                              ", " + _selectedItem.Almacen + ", " + _selectedItem.Fecha + " ]", MessageDialogStyle.AffirmativeAndNegative, mySettings);

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

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

                            await TaskEx.Delay(1500);

                            await metro.HideMetroDialogAsync(dialog);

                            DetallePedidoVisible = false;
                            FiltrarVisible       = true;
                            BotonesVisible       = false;
                            SeleccionIndice      = -1;

                            //MENSAJE EXTERNO
                            //dialog = dialog.ShowDialogExternally();
                            //await TaskEx.Delay(1500);
                            //await dialog.RequestCloseAsync();
                        }
                    }
                }
                else
                {
                    await metro.ShowMessageAsync("Validación", "Debe seleccionar una opcion");
                }
                break;

            case "boton_filtrar_traspasos":
                DetallePedidoVisible = false;
                FiltrarVisible       = true;
                BotonesVisible       = false;
                SeleccionIndice      = -1;
                break;

            case "click_doble":
                DetallePedidoVisible = true;
                FiltrarVisible       = true;
                if (_selectedItem.Pedido == "4023")
                {
                    Lista2.Clear();
                    Lista2.Add(new DetalleTraspaso()
                    {
                        Cantidad = "35", Producto = "Chicle", UnidadMedida = "Pieza"
                    });
                    Lista2.Add(new DetalleTraspaso()
                    {
                        Cantidad = "5", Producto = "Dulce", UnidadMedida = "Kilo"
                    });
                }
                else
                {
                    Lista2.Clear();
                    Lista2.Add(new DetalleTraspaso()
                    {
                        Cantidad = "21", Producto = "Paracetamol", UnidadMedida = "Pastilla"
                    });
                    Lista2.Add(new DetalleTraspaso()
                    {
                        Cantidad = "50", Producto = "Diclofenaco", UnidadMedida = "Capsula"
                    });
                }
                break;
            }
        }
Ejemplo n.º 25
0
        private async void ClickSwitch(Object obj)
        {
            switch (obj.ToString())
            {
            case "buscar":
                this.GetAgencias();
                break;

            case "menu_editar":
                if (SelectedItem != null)
                {
                    HeaderAgregar = "Editar Agencias";
                    #region visiblePantalla
                    EditarVisible       = true;
                    NuevoVisible        = false;
                    GuardarMenuEnabled  = true;
                    EliminarMenuEnabled = false;
                    EditarMenuEnabled   = false;
                    CancelarMenuEnabled = true;
                    AyudaMenuEnabled    = true;
                    SalirMenuEnabled    = true;
                    ExportarMenuEnabled = false;
                    AgregarVisible      = true;
                    #endregion
                    bandera_editar = true;
                    FocusText      = true;
                    /*****************************************/
                    Clave           = SelectedItem.ID_AGENCIA;
                    Descripcion     = SelectedItem.DESCR == null ? SelectedItem.DESCR : SelectedItem.DESCR.TrimEnd();
                    Domicilio       = SelectedItem.DOMICILIO == null ? SelectedItem.DOMICILIO : SelectedItem.DOMICILIO.TrimEnd();
                    Entidad         = 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();
                    string TipoAgencia        = SelectedItem.TIPO_AGENCIA == "E" ? "ESTATAL" : "FEDERAL";
                    var    _SelectAgenciaTipo = ListaAgenciasTipo.Where(w => w.Tipoagencia == TipoAgencia).SingleOrDefault();
                    SelectTipoAgenciaIndex = _SelectAgenciaTipo.Id_tipo_agencia;

                    setValidationRules();
                    //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 Nueva Agencia";
                #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;
                Descripcion       = string.Empty;
                Domicilio         = string.Empty;
                SelectMunicipio   = null;
                SelectedItem      = null;
                SelectedEstatus   = null;
                SelectedEstatus   = Lista_Estatus.LISTA_ESTATUS.Where(w => w.CLAVE == "S").FirstOrDefault();
                SelectAgenciaTipo = null;
                SelectMunicipio   = null;
                setValidationRules();
                //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.Guardar();
                    GuardarAgencia();
                    /**********************************/
                }
                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.GetAgencias();
                /****************************************/
                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.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;
            }
        }
Ejemplo n.º 26
0
 public static async Task InvokeAsync(this Dispatcher dispatcher, Action d)
 {
     await TaskEx.Run(() => dispatcher.Invoke(d));
 }
        /// <summary>
        ///     Receives the messages in an asynchronous loop and closes the session once there are no more messages.
        /// </summary>
        private void ReceiveMessagesAndCloseSession(MessageSession session, CancellationToken cancellationToken)
        {
            var unreleasedMessages = new CountdownEvent(1);

            Action <bool> closeSession = success => {
                Action doClose = () => {
                    try {
                        unreleasedMessages.Signal();
                        if (!unreleasedMessages.Wait(15000, cancellationToken))
                        {
                            Trace.TraceWarning("Waited for pending unreleased messages before closing session in subscription {0} but they did not complete in time", subscription);
                        }
                    } catch (OperationCanceledException) { } finally {
                        unreleasedMessages.Dispose();
                    }

                    receiveRetryPolicy.ExecuteAction(
                        cb => session.BeginClose(cb, null),
                        session.EndClose,
                        () => {
                        instrumentation.SessionEnded();
                        if (success)
                        {
                            dynamicThrottling.NotifyWorkCompleted();
                        }
                        else
                        {
                            dynamicThrottling.NotifyWorkCompletedWithError();
                        }
                    },
                        ex => {
                        instrumentation.SessionEnded();
                        Trace.TraceError("An unrecoverable error occurred while trying to close a session in subscription {1}:\r\n{0}", ex, subscription);
                        dynamicThrottling.NotifyWorkCompletedWithError();
                    });
                };

                if (requiresSequentialProcessing)
                {
                    doClose.Invoke();
                }
                else
                {
                    // Allow some time for releasing the messages before closing. Also, continue in a non I/O completion thread in order to block.
                    TaskEx.Delay(200).ContinueWith(t => doClose());
                }
            };

            // Declare an action to receive the next message in the queue or closes the session if cancelled.
            Action receiveNext = null;

            // Declare an action acting as a callback whenever a non-transient exception occurs while receiving or processing messages.
            Action <Exception> recoverReceive = null;

            // Declare an action responsible for the core operations in the message receive loop.
            Action receiveMessage = () => {
                // Use a retry policy to execute the Receive action in an asynchronous and reliable fashion.
                receiveRetryPolicy.ExecuteAction
                (
                    cb => {
                    // Start receiving a new message asynchronously.
                    // Does not wait for new messages to arrive in a session. If no further messages we will just close the session.
                    session.BeginReceive(TimeSpan.Zero, cb, null);
                },
                    // Complete the asynchronous operation. This may throw an exception that will be handled internally by retry policy.
                    session.EndReceive,
                    msg => {
                    // Process the message once it was successfully received
                    // Check if we actually received any messages.
                    if (msg != null)
                    {
                        var roundtripStopwatch             = Stopwatch.StartNew();
                        long schedulingElapsedMilliseconds = 0;
                        long processingElapsedMilliseconds = 0;

                        unreleasedMessages.AddCount();

                        Task.Factory.StartNew(() => {
                            var releaseAction = MessageReleaseAction.AbandonMessage;

                            try {
                                instrumentation.MessageReceived();

                                schedulingElapsedMilliseconds = roundtripStopwatch.ElapsedMilliseconds;

                                // Make sure the process was told to stop receiving while it was waiting for a new message.
                                if (!cancellationToken.IsCancellationRequested)
                                {
                                    try {
                                        try {
                                            // Process the received message.
                                            releaseAction = InvokeMessageHandler(msg);

                                            processingElapsedMilliseconds = roundtripStopwatch.ElapsedMilliseconds - schedulingElapsedMilliseconds;
                                            instrumentation.MessageProcessed(releaseAction.Kind == MessageReleaseActionKind.Complete, processingElapsedMilliseconds);
                                        } catch {
                                            processingElapsedMilliseconds = roundtripStopwatch.ElapsedMilliseconds - schedulingElapsedMilliseconds;
                                            instrumentation.MessageProcessed(false, processingElapsedMilliseconds);

                                            throw;
                                        }
                                    } finally {
                                        if (roundtripStopwatch.Elapsed > TimeSpan.FromSeconds(45))
                                        {
                                            dynamicThrottling.Penalize();
                                        }
                                    }
                                }
                            } finally {
                                // Ensure that any resources allocated by a BrokeredMessage instance are released.
                                if (requiresSequentialProcessing)
                                {
                                    ReleaseMessage(msg, releaseAction, () => { receiveNext(); }, () => { closeSession(false); }, unreleasedMessages, processingElapsedMilliseconds,
                                                   schedulingElapsedMilliseconds, roundtripStopwatch);
                                }
                                else
                                {
                                    // Receives next without waiting for the message to be released.
                                    ReleaseMessage(msg, releaseAction, () => { }, () => { dynamicThrottling.Penalize(); }, unreleasedMessages, processingElapsedMilliseconds,
                                                   schedulingElapsedMilliseconds, roundtripStopwatch);
                                    receiveNext.Invoke();
                                }
                            }
                        });
                    }
                    else
                    {
                        // no more messages in the session, close it and do not continue receiving
                        closeSession(true);
                    }
                },
                    ex => {
                    // Invoke a custom action to indicate that we have encountered an exception and
                    // need further decision as to whether to continue receiving messages.
                    recoverReceive.Invoke(ex);
                });
            };

            // Initialize an action to receive the next message in the queue or closes the session if cancelled.
            receiveNext = () => {
                if (!cancellationToken.IsCancellationRequested)
                {
                    // Continue receiving and processing new messages until told to stop.
                    receiveMessage.Invoke();
                }
                else
                {
                    closeSession(true);
                }
            };

            // Initialize a custom action acting as a callback whenever a non-transient exception occurs while receiving or processing messages.
            recoverReceive = ex => {
                // Just log an exception. Do not allow an unhandled exception to terminate the message receive loop abnormally.
                Trace.TraceError("An unrecoverable error occurred while trying to receive a new message from subscription {1}:\r\n{0}", ex, subscription);

                // Cannot continue to receive messages from this session.
                closeSession(false);
            };

            // Start receiving messages asynchronously for the session.
            receiveNext.Invoke();
        }
        /// <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);
        }
Ejemplo n.º 29
0
    public static async Task <String[]> NcbiPubmedParallelAsync(params String[] terms)
    {
        IEnumerable <Task <String> > tasks = from term in terms select NcbiPubmedAsync(term);

        return(await TaskEx.WhenAll(tasks));
    }
Ejemplo n.º 30
0
    public static Task <String[]> NcbiProteinParallelTasks(params String[] ids)
    {
        IEnumerable <Task <String> > tasks = from id in ids select NcbiProteinTask(id);

        return(TaskEx.WhenAll(tasks));
    }
        /// <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 hasRefreshed = false;
            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;
                }
            }
            await CheckAndRefreshAccessToken();

            try
            {
                while (true)
                {
                    try
                    {
                        return(await this.RequestJsonString(host, routeName, auth, routeStyle, requestArg, body)
                               .ConfigureAwait(false));
                    }
                    catch (AuthException e)
                    {
                        if (e.Message == "expired_access_token")
                        {
                            if (hasRefreshed)
                            {
                                throw;
                            }
                            else
                            {
                                await RefreshAccessToken();

                                hasRefreshed = true;
                            }
                        }
                        else
                        {
                            // dropbox maps 503 - ServiceUnavailable to be a rate limiting error.
                            // do not count a rate limiting error as an attempt
                            if (++attempt > maxRetries)
                            {
                                throw;
                            }
                        }
                    }
                    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();
                }
            }
        }