public static Task <TResult> LogIfErrorOccured <TResult>(this Task <TResult> task)
        {
            task.ThrowIfNull(nameof(task));

            return(task.ContinueWith(
                       task =>
            {
                switch (task.Status)
                {
                case TaskStatus.RanToCompletion:
                    {
                        return task.Result;
                    }

                case TaskStatus.Faulted:
                    {
                        Exception exception =
                            ExceptionsHelper.UnwrapAggregateExceptionIfSingle(task.Exception);

                        _logger.Error(exception, "Task is in the faulted state.");

                        throw new TaskFaultedException(
                            "Rethrow exception because a task is in the faulted state.",
                            exception
                            );
                    }

                default:
                    {
                        return default !;
                    }
                }
            }
Exemple #2
0
        public virtual void Test4()
        {
            var s = "ola $1 ola $2";

            s = ExceptionsHelper.ReplaceToken(s, "$", "param", 1);
            AssertEquals("ola param1 ola $2", s);
        }
 /// <inheritdoc />
 public void Add(TForward key, TReverse value)
 {
     if (!TryAdd(key, value))
     {
         throw ExceptionsHelper.NewDuplicateKeyException(key, nameof(Add));
     }
 }
        public string DoAuthentication()
        {
            var privateKey = salesforceSettings.GetPrivateKey();

            try
            {
                var authClient = new JwtAuthenticationClient(salesforceSettings.ApiVersion, salesforceSettings.IsProduction);
                authClient.JwtPrivateKeyAsync(
                    salesforceSettings.ClientId,
                    privateKey,
                    salesforceSettings.Passphrase,
                    salesforceSettings.Username,
                    salesforceSettings.TokenEndpoint
                    ).Wait();

                return(authClient.AccessToken);
            }
            catch (Exception ex)
            {
                var exceptions          = ExceptionsHelper.GetExceptionDetailsAsString(ex);
                var errorMessageBuilder = new StringBuilder();
                errorMessageBuilder.AppendLine("Authentication to Salesforce failed.");
                // TODO
                // Do more parsing and handling of exceptions here.
                errorMessageBuilder.Append(exceptions);

                throw new AuthenticationFailedException(errorMessageBuilder.ToString());
            }
        }
Exemple #5
0
        public virtual void Test6()
        {
            var s = "ola $1 ola $2 ola $3 ola $4";

            s = ExceptionsHelper.ReplaceToken(s, "$", "param", 2);
            AssertEquals("ola param1 ola param2 ola $3 ola $4", s);
        }
Exemple #6
0
    /// <summary>
    /// Gets the details for all applications or for a specific application created in the system.
    /// Also takes in timeout interval, which is the maximum of time the system will allow this operation to continue before returning.
    /// </summary>
    public async Task <IEnumerable <ApplicationWrapper> > GetApplicationListAsync(Uri applicationNameFilter, TimeSpan timeout, CancellationToken cancellationToken)
    {
        var             applicationList = new List <ApplicationWrapper>();
        ApplicationList previousResult  = null;

        // Set up the counter that record the time lapse.
        var stopWatch = ValueStopwatch.StartNew();

        do
        {
            cancellationToken.ThrowIfCancellationRequested();
            var remaining = timeout - stopWatch.Elapsed;
            if (remaining.Ticks < 0)
            {
                // If the passing time is longer than the timeout duration.
                throw new TimeoutException($"Unable to enumerate all application pages in the allotted time budget of {timeout.TotalSeconds} seconds");
            }

            previousResult = await ExceptionsHelper.TranslateCancellations(
                () => _queryClient.GetApplicationListAsync(
                    applicationNameFilter: applicationNameFilter,
                    continuationToken: previousResult?.ContinuationToken,
                    timeout: remaining,
                    cancellationToken: cancellationToken),
                cancellationToken);

            applicationList.AddRange(previousResult.Select(MapApp));
        }while (!string.IsNullOrEmpty(previousResult?.ContinuationToken));

        return(applicationList);

        ApplicationWrapper MapApp(Application app) =>
        new ApplicationWrapper
        {
            ApplicationName        = app.ApplicationName,
            ApplicationTypeName    = app.ApplicationTypeName,
            ApplicationTypeVersion = app.ApplicationTypeVersion,
            ApplicationParameters  = MapAppParameters(app),
        };

        IDictionary <string, string> MapAppParameters(Application app)
        {
            // NOTE: App Params in Service Fabric are case insensitive (verified on version 7.0.457.9590).
            // Since this is not documented behavior, the code below tries to play it safe by ignoring
            // duplicated app params instead of throwing and preventing such service from working at all
            // behind the Proxy.
            var result = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            foreach (var param in app.ApplicationParameters)
            {
                if (!result.TryAdd(param.Name, param.Value))
                {
                    Log.DuplicateAppParameter(_logger, param.Name, app.ApplicationName);
                }
            }

            return(result);
        }
    }
Exemple #7
0
 public static void MaxFileSizeNotExceeded <T>(T actualSize, T maxSize, string argName)
     where T : struct, IConvertible, IComparable, IComparable <T>
 {
     if (actualSize.CompareTo(maxSize) > 0)
     {
         throw ExceptionsHelper.MaxFileSizeExceeded(actualSize, maxSize, argName);
     }
 }
Exemple #8
0
        public void It_should_replace_in_any_string_any_token_given_number_times()
        {
            const string input = "val%val%";

            var result = ExceptionsHelper.ReplaceToken(input, "%", "(.)*", 1);

            Assert.That(result, Is.EqualTo("val(.)*val%"));
        }
        /// <summary>
        /// Determines whether a path string includes an extension.
        /// </summary>
        /// <param name="path">The path to search for an extension.</param>
        /// <returns>
        /// <see langword="true" />. if the characters that follow the last
        /// directory separator or volume separator in the <paramref name="path" />
        /// include a period (.) followed by one or more characters;
        /// otherwise, <see langword="false" />.
        /// </returns>
        /// <exception cref="System.ArgumentException"><paramref name="path" /> contains one or more invalid characters.</exception>
        public static bool HasExtension(string path)
        {
#if DESKTOP || MAC || ANDROID || __IOS__
            return(System.IO.Path.HasExtension(path));
#endif

            throw ExceptionsHelper.NotImplementedInReferenceAssembly();
        }
        public void ErrorMessage_DoesMatchDefaultMessage()
        {
            var defaultMessage = ErrorMessages.ResourceManager
                                 .GetString(nameof(ErrorMessages.DuplicateKeyFound), CultureInfo.InvariantCulture);

            defaultMessage = string.Format(defaultMessage, "key", nameof(ErrorMessage_DoesMatchDefaultMessage));
            Assert.AreEqual(defaultMessage, ExceptionsHelper.NewDuplicateKeyException("key", nameof(ErrorMessage_DoesMatchDefaultMessage)).Message);
        }
        /// <summary>
        /// Combines multiple strings into a path.
        /// </summary>
        /// <param name="paths">Path elements to combine.</param>
        /// <returns>A combined path.</returns>
        public static string Combine(params string[] paths)
        {
#if DESKTOP || MAC || ANDROID || __IOS__
            return(System.IO.Path.Combine(paths));
#endif

            throw ExceptionsHelper.NotImplementedInReferenceAssembly();
        }
        /// <summary>
        /// Returns the filename for the specified path string.
        /// </summary>
        /// <param name="path">The path string from which to obtain the file name and extension.</param>
        /// <returns>
        /// <para>
        /// A <see cref="string" /> consisting of the characters after the last
        /// directory character in path.
        /// </para>
        /// <para>
        /// If the last character of <paramref name="path" /> is a directory or
        /// volume separator character, an empty <see cref="string" /> is returned.
        /// </para>
        /// </returns>
        /// <exception cref="System.ArgumentException"><paramref name="path" /> contains one or more invalid characters.</exception>
        public static string GetFileName(string path)
        {
#if DESKTOP || MAC || ANDROID || __IOS__
            return(System.IO.Path.GetFileName(path));
#endif

            throw ExceptionsHelper.NotImplementedInReferenceAssembly();
        }
        public static T GetOrThrowIfDefault <T>([NotNull, NotNullIfNotNull("source")] this T source, string argName, string?customErrorText = null) where T : struct
        {
            if (Equals(source, default(T)))
            {
                throw ExceptionsHelper.ArgumentNotTypeDefault(argName, customErrorText);
            }

            return(source);
        }
Exemple #14
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public QueryData <object> Retrieves()
        {
            var data = ExceptionsHelper.RetrievePages(this, StartTime, EndTime);
            var ret  = new QueryData <object>();

            ret.total = (int)data.TotalItems;
            ret.rows  = data.Items.Select(ex => new { ex.UserId, ex.UserIp, ex.LogTime, ex.Message, ex.ErrorPage, ex.ExceptionType });
            return(ret);
        }
        public PluginSettingsDialog(WebBrowserParameters parameters)
        {
            ExceptionsHelper.CheckIsNull(parameters, "parameters");

            this.Parameters = parameters;
            this.InitializeComponent();
            this.titleTextBox.Text = this.Parameters.Title;
            this.urlTextBox.Text   = this.Parameters.URL;
            this.DataContext       = this.parameters;
        }
 public async Task <IActionResult> GetAllEmployees()
 {
     try
     {
         return(new OkObjectResult(await EmployeeLogic.GetAllEmployees()));
     } catch (Exception ex)
     {
         return(ExceptionsHelper.HandleException(ex));
     }
 }
Exemple #17
0
 /// <summary></summary>
 /// <param name="testResultsInfo">TestResultInfo</param>
 public void Persist(object testResultsInfo)
 {
     if (testResultsInfo is TestResultInfo)
     {
         XmlLog.CurrentTest.Result = new XmlTestResult((TestResultInfo)testResultsInfo);
     }
     else
     {
         ExceptionsHelper.ThrowObjectLoggerDoesNotSupportThisObjectType(testResultsInfo, typeof(TestResultInfo));
     }
 }
 public async Task <IActionResult> AddEmployee([FromBody] AddEmployeeVm vm)
 {
     try
     {
         return(new OkObjectResult(await EmployeeLogic.AddEmployee(vm)));
     }
     catch (Exception ex)
     {
         return(ExceptionsHelper.HandleException(ex));
     }
 }
 public async Task <IActionResult> UpdateEmployee(Guid id, [FromBody] UpdateEmployeeVm vm)
 {
     try
     {
         return(new OkObjectResult(await EmployeeLogic.UpdateEmployee(id, vm)));
     }
     catch (Exception ex)
     {
         return(ExceptionsHelper.HandleException(ex));
     }
 }
 public void Persist(object Object)
 {
     if (Object is ExceptionInfo)
     {
         XmlLog.CurrentTest.AddException(new XmlExceptionInfo((ExceptionInfo)Object));
     }
     else
     {
         ExceptionsHelper.ThrowObjectLoggerDoesNotSupportThisObjectType(Object, typeof(ExceptionInfo));
     }
 }
Exemple #21
0
        public static TValue GetOrThrowIfDefault <TValue>([NotNull, NotNullIfNotNull("source")] this IDictionary <string, object> source, string argName, string?customErrorText = null) where TValue : struct
        {
            var value = (TValue?)source.GetValueOrDefault(argName);

            if (value is null || Equals(value, default(TValue)))
            {
                throw ExceptionsHelper.ArgumentDefault(argName, customErrorText);
            }

            return((TValue)value);
        }
 public async Task <IActionResult> GetEmployeeById(Guid id)
 {
     try
     {
         return(new OkObjectResult(await EmployeeLogic.FindEmployeeById(id)));
     }
     catch (Exception ex)
     {
         return(ExceptionsHelper.HandleException(ex));
     }
 }
Exemple #23
0
        public static IDataAccessBuilder UseEntityFramework <T>(this IDataAccessBuilder builder)
            where T : EFDataAccessContext
        {
            if (builder == null)
            {
                ExceptionsHelper.ArgumentNullException(nameof(builder));
            }

            builder.Services.AddScoped <IDbContext, T>();
            return(builder);
        }
Exemple #24
0
        public void Retrieves_Ok()
        {
            ExceptionsHelper.Log(new Exception("UnitTest", new SqliteException("UnitTest", 1001)), null);
            Assert.NotEmpty(ExceptionsHelper.Retrieves());

            var ex = new Exceptions()
            {
                Period = "1"
            };

            Assert.Equal("1", ex.Period);
        }
        public async Task <IActionResult> RemoveEmployee(Guid id)
        {
            try
            {
                await EmployeeLogic.RemoveEmployee(id);

                return(new OkResult());
            }
            catch (Exception ex)
            {
                return(ExceptionsHelper.HandleException(ex));
            }
        }
Exemple #26
0
        /// <summary>
        /// This extension method injects all modules dependencies to <see cref="IServiceCollection"/> by dynamically module instantiation
        /// </summary>
        /// <typeparam name="TModule">Realization type of <see cref="IModule"/></typeparam>
        /// <param name="serviceCollection">Collections of DI services</param>
        /// <returns>Collections of DI services <see cref="IServiceCollection"/></returns>
        public static IServiceCollection AddModule <TModule>(this IServiceCollection serviceCollection)
            where TModule : IModule
        {
            var moduleType = typeof(TModule);

            ExceptionsHelper.ThrowIfNotRelevantConstructor(moduleType);

            var module = (IModule)Activator.CreateInstance(moduleType);

            module.Load(serviceCollection);

            return(serviceCollection);
        }
Exemple #27
0
    /// <summary>
    /// Get the specified NamedProperty.
    /// Also takes in timeout interval, which is the maximum of time the system will allow this operation to continue before returning.
    /// </summary>
    public async Task <string> GetPropertyAsync(Uri parentName, string propertyName, TimeSpan timeout, CancellationToken cancellationToken)
    {
        var result = await ExceptionsHelper.TranslateCancellations(
            () => _propertyManagementClient.GetPropertyAsync(parentName, propertyName, timeout, cancellationToken),
            cancellationToken);

        if (result != null)
        {
            // Transform Nameproperty type to plain string, Nameproperty is a sealed class that is not unit-testable.
            return(result.GetValue <string>());
        }

        return(null);
    }
Exemple #28
0
        public static IDataAccessBuilder UseEntityFramework <T>(this IDataAccessBuilder builder,
                                                                Func <IServiceProvider, T> implementationFactory)
            where T : EFDataAccessContext
        {
            if (builder == null)
            {
                ExceptionsHelper.ArgumentNullException(nameof(builder));
            }
            if (implementationFactory == null)
            {
                ExceptionsHelper.ArgumentNullException(nameof(implementationFactory));
            }

            builder.Services.AddScoped <IDbContext, T>(implementationFactory);
            return(builder);
        }
Exemple #29
0
    /// <summary>
    /// Get ID for all partitions of a service. If the partition do not fit in a page, one
    /// page of results is returned as well as a continuation token which can be used to get the next page. Let PartitionFilter to be null because we are getting all partition.
    /// </summary>
    public async Task <IEnumerable <PartitionWrapper> > GetPartitionListAsync(Uri serviceName, TimeSpan timeout, CancellationToken cancellationToken)
    {
        var partitionList = new List <PartitionWrapper>();
        ServicePartitionList previousResult = null;

        // Set up the counter that record the time lapse.
        var stopWatch = ValueStopwatch.StartNew();

        do
        {
            cancellationToken.ThrowIfCancellationRequested();
            var remaining = timeout - stopWatch.Elapsed;
            if (remaining.Ticks < 0)
            {
                // If the passing time is longer than the timeout duration.
                throw new TimeoutException($"Unable to enumerate all partition pages in the allotted time budget of {timeout.TotalSeconds} seconds");
            }

            previousResult = await ExceptionsHelper.TranslateCancellations(
                () => _queryClient.GetPartitionListAsync(
                    serviceName: serviceName,
                    partitionIdFilter: null,
                    continuationToken: previousResult?.ContinuationToken,
                    timeout: remaining,
                    cancellationToken: cancellationToken),
                cancellationToken);

            foreach (var partition in previousResult)
            {
                var partitionName = string.Empty;

                if (partition.PartitionInformation is NamedPartitionInformation namedPartition)
                {
                    partitionName = namedPartition.Name;
                }

                partitionList.Add(
                    new PartitionWrapper
                {
                    Id   = partition.PartitionInformation.Id,
                    Name = partitionName
                });
            }
        }while (!string.IsNullOrEmpty(previousResult?.ContinuationToken));

        return(partitionList);
    }
Exemple #30
0
    /// <summary>
    /// Gets the ServiceManifestName for a specific service,
    /// Also takes in timeout interval, which is the maximum of time the system will allow this operation to continue before returning.
    /// </summary>
    public async Task <string> GetServiceManifestName(string applicationTypeName, string applicationTypeVersion, string serviceTypeName, TimeSpan timeout, CancellationToken cancellationToken)
    {
        var serviceTypes = await ExceptionsHelper.TranslateCancellations(
            () => _queryClient.GetServiceTypeListAsync(
                applicationTypeName: applicationTypeName,
                applicationTypeVersion: applicationTypeVersion,
                serviceTypeNameFilter: serviceTypeName,
                timeout: timeout,
                cancellationToken: cancellationToken),
            cancellationToken);

        if (serviceTypes.Count == 0)
        {
            throw new InvalidOperationException($"Did not find a service manifest for ApplicationTypeName={applicationTypeName} ApplicationTypeVersion={applicationTypeVersion} ServiceTypeName={serviceTypeName}");
        }
        return(serviceTypes[0].ServiceManifestName);
    }