Ejemplo n.º 1
0
 public static bool IsIntegralNumeric(this Type type)
 {
     ArgCheck.NotNull(nameof(type), type);
     if (type == typeof(byte) || type == typeof(sbyte) ||
         type == typeof(short) || type == typeof(ushort) ||
         type == typeof(int) || type == typeof(uint) ||
         type == typeof(long) || type == typeof(ulong))
     {
         return(true);
     }
     return(false);
 }
Ejemplo n.º 2
0
        public static void AddRange <T>(this IList <T> list, IEnumerable <T> items)
        {
            ArgCheck.NotNull(nameof(list), list);

            if (items != null)
            {
                foreach (var item in items)
                {
                    list.Add(item);
                }
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Deletes the specified <paramref name="tenant"/> from the tenant store.
        /// </summary>
        /// <param name="tenant">The tenant to delete.</param>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
        /// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="TenancyResult"/> of the update operation.</returns>
        public override Task <TenancyResult> DeleteAsync(TTenant tenant, CancellationToken cancellationToken = default)
        {
            ArgCheck.NotNull(nameof(tenant), tenant);
            cancellationToken.ThrowIfCancellationRequested();
            ThrowIfDisposed();

            _tenants.Remove(tenant);

            Logger.LogDebug($"Tenant ID '{{{nameof(TenancyTenant.Id)}}}' deleted.", tenant.Id);

            return(Task.FromResult(TenancyResult.Success));
        }
        /// <summary>
        /// Adds a named Cosmos client registration by factory to the service collection.
        /// </summary>
        public static IServiceCollection AddCosmosClient(this IServiceCollection services, string name, Func <IServiceProvider, CosmosClientRegistration> clientRegistrationFactory)
        {
            ArgCheck.NotNull(nameof(name), name);
            ArgCheck.NotNull(nameof(clientRegistrationFactory), clientRegistrationFactory);

            return(AddCosmosClientCore(services, sp =>
            {
                var clientRegistration = clientRegistrationFactory(sp);
                clientRegistration.Name = name;
                return clientRegistration;
            }));
        }
Ejemplo n.º 5
0
        public override void ValidateArguments()
        {
            base.ValidateArguments();

            // Load defaults from environment
            if (CurrentEnvironment != null && ConnectionString == null)
            {
                ConnectionString = GetConnectionFromEnvironment(CurrentEnvironment);
            }

            ArgCheck.RequiredOrConfig(ConnectionString, "ConnectionString");
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Adds a <see cref="HeaderParser"/> to the collection of parsers for detecting the current tenant's canonical name by an HTTP header.
        /// Eg. use "X-TENANT" for matching on X-TENANT = tenant1
        /// </summary>
        /// <typeparam name="TTenant">The type representing a tenant.</typeparam>
        /// <typeparam name="TKey">The type of the primary key for a tenant.</typeparam>
        /// <param name="builder">Builder to add the <see cref="HeaderParser"/> to.</param>
        /// <param name="headerName">The HTTP header name which will contain the tenant's canonical name of the request.</param>
        /// <returns><paramref name="parsers"/> for fluent API.</returns>
        public static TenancyBuilder <TTenant, TKey> AddHeaderParser <TTenant, TKey>(this TenancyBuilder <TTenant, TKey> builder, string headerName)
            where TTenant : class
            where TKey : IEquatable <TKey>
        {
            ArgCheck.NotNull(nameof(builder), builder);
            ArgCheck.NotNullOrEmpty(nameof(headerName), headerName);

            return(builder.AddRequestParser(sp => new HeaderParser()
            {
                HeaderName = headerName
            }));
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Adds a <see cref="CustomParser"/> to the collection of parsers for detecting the current tenant's canonical name
        /// from a custom function.
        /// </summary>
        /// <typeparam name="TTenant">The type representing a tenant.</typeparam>
        /// <typeparam name="TKey">The type of the primary key for a tenant.</typeparam>
        /// <param name="builder">Builder to add the <see cref="CustomParser"/> to.</param>
        /// <param name="parser">Async func that returns the tenant's canonical name from the current request.</param>
        /// <returns><paramref name="parsers"/> for fluent API.</returns>
        public static TenancyBuilder <TTenant, TKey> AddCustomParser <TTenant, TKey>(this TenancyBuilder <TTenant, TKey> builder, Func <HttpContext, ValueTask <string> > parser)
            where TTenant : class
            where TKey : IEquatable <TKey>
        {
            ArgCheck.NotNull(nameof(builder), builder);
            ArgCheck.NotNull(nameof(parser), parser);

            return(builder.AddRequestParser(sp => new CustomParser()
            {
                Parser = parser
            }));
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Adds a <see cref="UserClaimParser"/> to the collection of parsers for detecting the current tenant's canonical name
        /// from a user claim on the authenticated user principal.
        /// Eg: claim type "http://schemas.microsoft.com/identity/claims/tenantid" or "tid".
        /// </summary>
        /// <typeparam name="TTenant">The type representing a tenant.</typeparam>
        /// <typeparam name="TKey">The type of the primary key for a tenant.</typeparam>
        /// <param name="builder">Builder to add the <see cref="UserClaimParser"/> to.</param>
        /// <param name="claimType">Claim type that contains the tenant canonical name as its value.</param>
        /// <returns><paramref name="parsers"/> for fluent API.</returns>
        public static TenancyBuilder <TTenant, TKey> AddClaimParser <TTenant, TKey>(this TenancyBuilder <TTenant, TKey> builder, string claimType)
            where TTenant : class
            where TKey : IEquatable <TKey>
        {
            ArgCheck.NotNull(nameof(builder), builder);
            ArgCheck.NotNullOrEmpty(nameof(claimType), claimType);

            return(builder.AddRequestParser(sp => new UserClaimParser()
            {
                ClaimType = claimType
            }));
        }
Ejemplo n.º 9
0
        public override void ValidateArguments()
        {
            base.ValidateArguments();

            // Load defaults from environment
            if (CurrentEnvironment != null && ReportStorage == null)
            {
                ReportStorage = CurrentEnvironment.ReportStorage;
            }

            ArgCheck.RequiredOrConfig(ReportStorage, "ReportStorage");
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Adds a <see cref="HostParser"/> to the collection of parsers for detecting the current tenant's canonical name by using a regular expression on the request's hostname.
        /// Eg: use @"^([a-z0-9][a-z0-9-]*[a-z0-9])(?:\.[a-z][a-z])?\.tenants\.multitenancyserver\.io$" for
        /// matching on tenant1.eu.tenants.multitenancyserver.io where '.eu.' is an optional and dynamic two letter region code.
        /// The first group capture of a successful match is used, use anonymouse groups (?:) to avoid unwanted captures.
        /// </summary>
        /// <typeparam name="TTenant">The type representing a tenant.</typeparam>
        /// <typeparam name="TKey">The type of the primary key for a tenant.</typeparam>
        /// <param name="builder">Builder to add the <see cref="HostParser"/> to.</param>
        /// <param name="hostPattern">A regular expression to retreive the tenant canonical name from the full hostname (domain) of the request.</param>
        /// <returns><paramref name="parsers"/> for fluent API.</returns>
        public static TenancyBuilder <TTenant, TKey> AddHostnameParser <TTenant, TKey>(this TenancyBuilder <TTenant, TKey> builder, string hostPattern)
            where TTenant : class
            where TKey : IEquatable <TKey>
        {
            ArgCheck.NotNull(nameof(builder), builder);
            ArgCheck.NotNullOrEmpty(nameof(hostPattern), hostPattern);

            return(builder.AddRequestParser(sp => new HostParser()
            {
                HostPattern = hostPattern
            }));
        }
Ejemplo n.º 11
0
        public static void InsertRange <T>(this IList <T> list, int index, IEnumerable <T> items)
        {
            ArgCheck.NotNull(nameof(list), list);

            if (items != null)
            {
                foreach (var item in items)
                {
                    list.Insert(index++, item);
                }
            }
        }
Ejemplo n.º 12
0
        object ISerializer.Deserialize(Type type, object data)
        {
            ArgCheck.NotNull(nameof(type), type);

            var result = Deserialize((byte[])data);

            if (result != null && result.GetType() != type)
            {
                throw new InvalidCastException();
            }
            return(result);
        }
Ejemplo n.º 13
0
        public static TValue GetOrAdd <TKey, TValue>(this IDictionary <TKey, TValue> dictionary, TKey key, TValue value)
        {
            ArgCheck.NotNull(nameof(dictionary), dictionary);

            if (!dictionary.TryGetValue(key, out var v))
            {
                v = value;
                dictionary.Add(key, v);
            }

            return(v);
        }
        public override void ValidateArguments()
        {
            base.ValidateArguments();

            if (BackupStorage == null && CurrentEnvironment != null)
            {
                BackupStorage = CurrentEnvironment.BackupStorage;
            }
            ArgCheck.RequiredOrConfig(BackupStorage, "BackupStorage");

            ArgCheck.Required(Reason, "Reason");
        }
Ejemplo n.º 15
0
        public override void ValidateArguments()
        {
            base.ValidateArguments();

            ArgCheck.Required(Label, "Label");
            ArgCheck.Required(CloudService, "CloudService");

            if (MaxRecurrenceFrequency.HasValue)
            {
                ArgCheck.Required(MaxRecurrenceInterval, "MaxRecurrenceInterval");
            }
        }
Ejemplo n.º 16
0
        public static void AddParameter(this IDbCommand command, string name, object value, DbType type, int scale, int precision)
        {
            ArgCheck.NotNull(nameof(command), command);
            var parameter = command.CreateParameter();

            parameter.ParameterName = name;
            parameter.Value         = value ?? DBNull.Value;
            parameter.DbType        = type;
            parameter.Scale         = (byte)scale;
            parameter.Precision     = (byte)precision;
            command.Parameters.Add(parameter);
        }
Ejemplo n.º 17
0
        public static SecureString Secure(this string unsecured)
        {
            ArgCheck.NotNull(nameof(unsecured), unsecured);
            var secureString = new SecureString();

            foreach (var c in unsecured)
            {
                secureString.AppendChar(c);
            }
            secureString.MakeReadOnly();
            return(secureString);
        }
        public static IServiceCollection AddAzureKeyVaultSecretStore(this IServiceCollection services, Action <AzureKeyVaultSecretStoreOptionsBuilder> setupAction)
        {
            ArgCheck.NotNull(nameof(services), services);
            ArgCheck.NotNull(nameof(setupAction), setupAction);

            return(services.AddSingleton <ISecretReadOnlyStore>(serviceProvider =>
            {
                var builder = new AzureKeyVaultSecretStoreOptionsBuilder();
                setupAction(builder);
                var options = builder.Build();
                return new AzureKeyVaultSecretStore(options);
            }));
        }
Ejemplo n.º 19
0
 public AzureBlobStorageCacheClient(string connectionString, IAsyncStreamSerializer serializer, string containerName, string defaultPartitionDirectory, ILogger logger, bool throwOnError)
     : base(throwOnError, logger)
 {
     ArgCheck.NotNullOrEmpty(nameof(connectionString), connectionString);
     ArgCheck.NotNull(nameof(serializer), serializer);
     ArgCheck.NotNullOrEmpty(nameof(containerName), containerName);
     _containerName             = containerName;
     _defaultPartitionDirectory = defaultPartitionDirectory;
     _serializer     = serializer;
     _storageAccount = CloudStorageAccount.Parse(connectionString);
     _client         = _storageAccount.CreateCloudBlobClient();
     _container      = _client.GetContainerReference(_containerName);
 }
Ejemplo n.º 20
0
        /// <summary>
        /// Gets the types defined in this assembly that can be loaded.
        /// </summary>
        /// <param name="assembly">The assembly to search.</param>
        /// <returns>An array that contains all the types that are defined in this assembly that can be loaded.</returns>
        public static IEnumerable <Type> GetLoadableTypes(this Assembly assembly)
        {
            ArgCheck.NotNull(nameof(assembly), assembly);

            try
            {
                return(assembly.GetTypes());
            }
            catch (ReflectionTypeLoadException ex)
            {
                return(ex.Types.WhereNotNull());
            }
        }
Ejemplo n.º 21
0
        public static TValue GetOrAdd <TKey, TValue>(this IDictionary <TKey, TValue> dictionary, TKey key, Func <TKey, TValue> valueFactory)
        {
            ArgCheck.NotNull(nameof(dictionary), dictionary);
            ArgCheck.NotNull(nameof(valueFactory), valueFactory);

            if (!dictionary.TryGetValue(key, out var value))
            {
                value = valueFactory(key);
                dictionary.Add(key, value);
            }

            return(value);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Replaces the first matching token in a string, eg: "Insert{MyToken}Here".
        /// The token may contain a format, eg: "{MyToken:F2}" or "{MyToken:yyyy-MM-dd}".
        /// The characters '}' and ':' are not supported in the token name.
        /// You can compare the resulting string to the original string to determine if a replacement took place.
        /// </summary>
        /// <param name="str">Input string that may contain one or more tokens.</param>
        /// <param name="token">Name of the token to replace, eg: use "MyToken" to replace "{MyToken}".</param>
        /// <param name="value">Replacement value, to be converted to a string formatted with either the format specified by the token
        /// otherwise by <paramref name="defaultFormat"/>.</param>
        /// <param name="defaultFormat">Default format to use on the <paramref name="value"/> if no format is specified on the matched token.</param>
        /// <param name="formatProvider">The provider to use to format the <paramref name="value"/>. -or-
        /// A null reference to obtain the numeric format information from the current locale setting of the operating system.</param>
        /// <returns>The result of <paramref name="str"/> with the matching token (if found) replaced with a formatted <paramref name="value"/>.</returns>
        public static string ReplaceToken(this string str, string token, IFormattable value, string defaultFormat = null, IFormatProvider formatProvider = null)
        {
            ArgCheck.NotNull(nameof(str), str);
            ArgCheck.NotNullOrEmpty(nameof(token), token);
            var match = Regex.Match(str, $@"{{{token}(?::([^}}]*))?}}", RegexOptions.Compiled);

            if (match.Success && match.Groups[0].Success)
            {
                return(str.Replace(match.Groups[0].Value,
                                   value?.ToString(match.Groups[1].Success ? match.Groups[1].Value : defaultFormat, formatProvider)));
            }
            return(str);
        }
        public static IServiceCollection AddAzureKeyVaultPrivateCertificateStore(this IServiceCollection services, Action <IServiceProvider, AzureKeyVaultSecretStoreOptionsBuilder> setupAction)
        {
            ArgCheck.NotNull(nameof(services), services);
            ArgCheck.NotNull(nameof(setupAction), setupAction);

            return(services.AddScoped <IPrivateCertificateStore>(serviceProvider =>
            {
                var builder = new AzureKeyVaultSecretStoreOptionsBuilder();
                setupAction(serviceProvider, builder);
                var options = builder.Build();
                return new AzureKeyVaultSecretStore(options);
            }));
        }
Ejemplo n.º 24
0
        public Task <X509Certificate2> GetCertificateAsync(string name, bool withPrivateKey = false, CancellationToken cancellationToken = default)
        {
            ArgCheck.NotNullOrEmpty(nameof(name), name);

            if (withPrivateKey)
            {
                return(_privateKeyStore.GetPrivateCertificateAsync(name, cancellationToken));
            }
            else
            {
                return(_publicKeyStore.GetPublicCertificateAsync(name, cancellationToken));
            }
        }
Ejemplo n.º 25
0
        public override void ValidateArguments()
        {
            base.ValidateArguments();
            ArgCheck.Required(PackageId, "PackageId");
            ArgCheck.Required(PackageVersion, "PackageVersion");
            ArgCheck.Required(PackageHash, "PackageHash");

            if (BackupStorage == null && CurrentEnvironment != null)
            {
                BackupStorage = CurrentEnvironment.BackupStorage;
            }
            ArgCheck.RequiredOrConfig(BackupStorage, "BackupStorage");
        }
Ejemplo n.º 26
0
 public virtual Task SetRangeAsync <T>(IEnumerable <KeyValuePair <string, T> > keyValues, DateTimeOffset?absoluteExpiration, string partition = null)
 {
     ArgCheck.NotNull(nameof(keyValues), keyValues);
     if (keyValues.Any(keyValue => keyValue.Key == null))
     {
         throw new ArgumentException("Parameter keyValues must contain non-null keys.", "keyValues");
     }
     if (keyValues.GroupBy(keyValue => keyValue.Key).Any(g => g.Count() > 1))
     {
         throw new ArgumentException("Parameter keyValues must contain only distinct keys.", "keyValues");
     }
     return(SetAsyncHelper(keyValues, absoluteExpiration, partition));
 }
Ejemplo n.º 27
0
 private AzureTableStorageCacheClient(CloudStorageAccount account, ISerializer serializer, string tableName, string defaultPartitionKey, ILogger logger, bool throwOnError)
     : base(throwOnError, logger)
 {
     ArgCheck.NotNull(nameof(account), account);
     ArgCheck.NotNull(nameof(serializer), serializer);
     ArgCheck.NotNullOrEmpty(nameof(tableName), tableName);
     _tableName           = tableName;
     _defaultPartitionKey = defaultPartitionKey;
     _serializer          = serializer;
     _storageAccount      = account;
     _client = _storageAccount.CreateCloudTableClient();
     _table  = _client.GetTableReference(_tableName);
 }
Ejemplo n.º 28
0
        object IStreamSerializer.DeserializeFromStream(Type type, Stream stream)
        {
            ArgCheck.NotNull(nameof(type), type);
            ArgCheck.NotNull(nameof(stream), stream);

            var result = DeserializeFromStream(stream);

            if (result != null && result.GetType() != type)
            {
                throw new InvalidCastException();
            }
            return(result);
        }
Ejemplo n.º 29
0
 public static void FireAndForget(this Task task)
 {
     // TODO: not sure this work correctly, there have been some issues with testing, need to confirm this will work every time
     ArgCheck.NotNull(nameof(task), task);
     task.ContinueWith(t =>
     {
         try
         {
             t.Wait();
         }
         catch { }
     }, TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously).ConfigureAwait(false);
 }
Ejemplo n.º 30
0
        async Task <object> IAsyncStreamSerializer.DeserializeFromStreamAsync(Type type, Stream stream, CancellationToken cancellationToken)
        {
            ArgCheck.NotNull(nameof(type), type);
            ArgCheck.NotNull(nameof(stream), stream);

            var result = await DeserializeFromStreamAsync(stream, cancellationToken).ConfigureAwait(false);

            if (result != null && result.GetType() != type)
            {
                throw new InvalidCastException();
            }
            return(result);
        }