Пример #1
0
        /// <summary>
        /// Initialize <see cref="Setup"/>.
        /// </summary>
        /// <param name="name">The name of the application.</param>
        /// <param name="tenant">The tenant that the application itself runs in.</param>
        /// <param name="level">The run time level for the application itself.</param>
        /// <remarks>Will setup all mandatory fields for <see cref="Setup"/>, but you might want to override those values when this method returns."/></remarks>
        public static void Initialize(string name, Tenant tenant, RunTimeLevelEnum level)
        {
            InternalContract.RequireNotNullOrWhiteSpace(name, nameof(name));
            InternalContract.RequireValidated(tenant, nameof(tenant));
            InternalContract.Require(level != RunTimeLevelEnum.None, $"{nameof(level)} ({level}) must be set to something else than {RunTimeLevelEnum.None}");

            Setup.Name         = name;
            Setup.Tenant       = tenant;
            Setup.RunTimeLevel = level;

            Setup.ThreadHandler         = ThreadHelper.RecommendedForRuntime;
            Setup.SynchronousFastLogger = LogHelper.RecommendedSyncLoggerForRuntime;
            switch (level)
            {
            case RunTimeLevelEnum.None:
            case RunTimeLevelEnum.Development:
                Setup.LogSeverityLevelThreshold = LogSeverityLevel.Verbose;
                break;

            case RunTimeLevelEnum.Test:
                Setup.LogSeverityLevelThreshold = LogSeverityLevel.Information;
                break;

            case RunTimeLevelEnum.ProductionSimulation:
            case RunTimeLevelEnum.Production:
                Setup.LogSeverityLevelThreshold = LogSeverityLevel.Warning;
                break;

            default:
                Setup.LogSeverityLevelThreshold = LogSeverityLevel.Verbose;
                InternalContract.Fail($"Parameter {nameof(level)} had an unexpected value ({level})");
                break;
            }
        }
 /// <summary>
 /// Register which controllers that should be used for a specific capability interface.
 /// </summary>
 public void RegisterControllersForCapability <TControllerInjector>(params Type[] controllerTypes)
     where TControllerInjector : IControllerInjector
 {
     InternalContract.Require(typeof(TControllerInjector).IsInterface,
                              $"The type ({typeof(TControllerInjector).Name}) passed to {nameof(RegisterControllersForCapability)} must be an interface.");
     RegisterControllersForCapability(typeof(TControllerInjector), controllerTypes);
 }
Пример #3
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="crudService">The persistence service that will actually create, read and update data.</param>
 /// <param name="options"></param>
 public CrudPersistenceHelper(ICrudable <TModelCreate, TModel, TId> crudService, CrudPersistenceHelperOptions options)
 {
     _readService = crudService as IRead <TModel, TId>;
     InternalContract.Require(_readService != null, $"Parameter {nameof(crudService)} must implement {nameof(IRead<TModel, TId>)}.");
     _crudService = crudService;
     _options     = options;
 }
        /// <summary>
        /// Get the cacke key
        /// </summary>
        protected static string GetCacheKeyFromId(TId id)
        {
            var key = id?.ToString();

            InternalContract.Require(key != null,
                                     $"Could not extract a cache key for an item of type {typeof(TModel).FullName}.");
            return(key);
        }
        public static int ToInt(this string source)
        {
            InternalContract.RequireNotNull(source, nameof(source));
            var success = int.TryParse(source, out var valueAsInt);

            InternalContract.Require(success, $"Could not parse parameter {nameof(source)} ({source}) of type {nameof(String)} into type {nameof(Int32)}.");
            return(valueAsInt);
        }
        public static Guid ToGuid(this string source)
        {
            InternalContract.RequireNotNull(source, nameof(source));
            var success = Guid.TryParse(source, out var valueAsGuid);

            InternalContract.Require(success, $"Could not parse parameter {nameof(source)} ({source}) of type {nameof(String)} into type {nameof(Guid)}.");
            return(valueAsGuid);
        }
Пример #7
0
        private static Guid ToGuid(string id)
        {
#pragma warning disable IDE0018 // Inline variable declaration
            Guid guid;
#pragma warning restore IDE0018 // Inline variable declaration
            InternalContract.Require(Guid.TryParse(id, out guid), $"Expected a Guid in {nameof(id)} but the value was ({id}).");
            return(guid);
        }
        public static T ToEnum <T>(this string source) where T : struct
        {
            InternalContract.RequireNotNull(source, nameof(source));
            InternalContract.Require(typeof(T).IsEnum, $"The generic type {typeof(T).Name} must be an enum.");
            var success = Enum.TryParse <T>(source, out var valueAsEnum);

            InternalContract.Require(success, $"Could not parse parameter {nameof(source)} ({source}) of type {nameof(String)} into type {nameof(T)}.");
            return(valueAsEnum);
        }
Пример #9
0
 public static T?ToNullableEnum <T>(this string source) where T : struct
 {
     InternalContract.Require(typeof(T).IsEnum, $"The generic type {typeof(T).Name} must be an enum.");
     if (source == null)
     {
         return(null);
     }
     return(source.ToEnum <T>());
 }
Пример #10
0
        public async Task DeleteAsync(string stringId)
        {
            var isInt = int.TryParse(stringId, out int id);

            InternalContract.Require(isInt, $"Could not parse '{stringId}' as an integer");
            InternalContract.RequireGreaterThan(0, id, nameof(id));
            var dalProduct = await _productPersistance.DeleteAsync(id).ConfigureAwait(false);

            return(FromDal(dalProduct));
        }
Пример #11
0
 /// <summary>
 /// Sets the server technical name. This name will be used as a default for all new FulcrumExceptions.
 /// </summary>
 /// <param name="serverTechnicalName"></param>
 public static void Initialize(string serverTechnicalName)
 {
     InternalContract.RequireNotNullOrWhitespace(serverTechnicalName, nameof(serverTechnicalName));
     serverTechnicalName = serverTechnicalName.ToLower();
     if (_serverTechnicalName != null)
     {
         InternalContract.Require(serverTechnicalName == _serverTechnicalName,
                                  $"Once the server name has been set ({_serverTechnicalName}, it can't be changed ({serverTechnicalName}).");
     }
     _serverTechnicalName = serverTechnicalName;
 }
        public static T ToEnum <T>(this int source) where T : struct
        {
            InternalContract.Require(typeof(T).IsEnum, $"The generic type {typeof(T).Name} must be an enum.");
            if (!Enum.IsDefined(typeof(T), source))
            {
                throw new FulcrumContractException(
                          $"The value {source} is not defined in the enumeration {nameof(T)}.");
            }

            return((T)Enum.ToObject(typeof(T), source));
        }
        /// <inheritdoc />
        public Task CreateWithSpecifiedIdAsync(string masterId, string slaveId, PersonConsentCreate item,
                                               CancellationToken token = new CancellationToken())
        {
            InternalContract.RequireNotNull(item, nameof(item));
            InternalContract.RequireValidated(item, nameof(item));
            InternalContract.Require(masterId == item.PersonId, $"{nameof(masterId)} ({masterId} must have the same value as {nameof(item)}.{nameof(item.PersonId)} ({item.PersonId}).");
            InternalContract.Require(slaveId == item.ConsentId, $"{nameof(slaveId)} ({slaveId} must have the same value as {nameof(item)}.{nameof(item.ConsentId)} ({item.ConsentId}).");
            var serverItem = MapToServer(item);

            return(_storage.PersonConsent.CreateAsync(serverItem, token));
        }
 /// <summary>
 /// Lower the semaphore. NOTE! Use this in a 'try-finally' statement to be absolutely
 /// sure that we eventually lower the semaphore. See <see cref="RaiseAsync"/>.
 /// </summary>
 public void Lower()
 {
     lock (_lock)
     {
         if (_insideLockLevel.Value > 0)
         {
             return;
         }
         InternalContract.Require(_count > 0, $"The semaphore was already at count {_count}, so you can't lower it again.");
         _count--;
     }
 }
        public Task <Foo> UpdateAndReturnAsync([TranslationConcept(Foo.IdConceptName)] string id, Foo item,
                                               CancellationToken token = default)
        {
            InternalContract.RequireNotNullOrWhiteSpace(id, nameof(id));
            InternalContract.RequireNotNull(item, nameof(item));
            var success = ConceptValue.TryParse(item.Id, out var conceptValue);

            FulcrumAssert.IsTrue(success);
            FulcrumAssert.AreEqual(Foo.IdConceptName, conceptValue.ConceptName);
            FulcrumAssert.AreEqual(Foo.ConsumerName, conceptValue.ClientName);
            InternalContract.Require(id == item.Id, $"Expected {nameof(id)} to be identical to {nameof(item)}.{nameof(item.Id)}.");
            item.Id = Translator.Decorate(Foo.IdConceptName, Foo.ProducerName, Foo.ProducerId1);
            return(Task.FromResult(item));
        }
Пример #16
0
        public static T ToEnum <T>(this string source) where T : struct
        {
            InternalContract.RequireNotNull(source, nameof(source));
            InternalContract.Require(typeof(T).IsEnum, $"The generic type {typeof(T).Name} must be an enum.");
            if (!Enum.IsDefined(typeof(T), source))
            {
                throw new FulcrumContractException(
                          $"The value {source} is not defined in the enumeration {nameof(T)}.");
            }
            var success = Enum.TryParse <T>(source, true, out var valueAsEnum);

            InternalContract.Require(success, $"Could not parse parameter {nameof(source)} ({source}) of type {nameof(String)} into type {nameof(T)}.");
            return(valueAsEnum);
        }
Пример #17
0
        /// <summary>
        /// Register which controllers that should be used for a specific capability interface.
        /// </summary>
        public void RegisterControllersForCapability(Type capabilityInterface, params Type[] controllerTypes)
        {
            InternalContract.Require(capabilityInterface, type => type.IsInterface, nameof(capabilityInterface));
            InternalContract.Require(capabilityInterface.IsInterface,
                                     $"The parameter {nameof(capabilityInterface)} must be an interface.");
            InternalContract.Require(typeof(IControllerInjector).IsAssignableFrom(capabilityInterface),
                                     $"The parameter {nameof(capabilityInterface)} must inherit from {typeof(IControllerInjector).FullName}.");
            foreach (var controllerType in controllerTypes)
            {
                InternalContract.Require(controllerType, type => type.IsClass, nameof(controllerType));
            }

            _capabilityInterfaceToControllerClasses.Add(capabilityInterface, controllerTypes);
        }
        /// <summary>
        /// Map an id between two types.
        /// </summary>
        /// <param name="source">The id to map.</param>
        /// <typeparam name="TTarget">The target type.</typeparam>
        /// <typeparam name="TSource">The source type.</typeparam>
        /// <exception cref="FulcrumNotImplementedException">Thrown if the type was not recognized. Please add that type to the class <see cref="TypeConversionExtensions"/>.</exception>
        public static TTarget MapToType <TTarget, TSource>(TSource source)
        {
            var sourceType = typeof(TSource);
            var targetType = typeof(TTarget);

            if (targetType == typeof(string))
            {
                if (source == null)
                {
                    return((TTarget)(object)null);
                }
                var result = source.ToString();
                if (sourceType == typeof(Guid) || sourceType == typeof(Guid?))
                {
                    result = result.ToLowerInvariant();
                }
                return((TTarget)(object)result);
            }
            InternalContract.Require(!targetType.IsEnum, $"Use MapToStruct for mapping of enums.");
            if (targetType == typeof(Guid) || targetType == typeof(Guid?))
            {
                if (targetType == typeof(Guid))
                {
                    InternalContract.RequireNotNull(source, nameof(source));
                }
                if (source == null)
                {
                    return((TTarget)(object)null);
                }
                return((TTarget)(object)source.ToString().ToGuid());
            }
            if (targetType == typeof(int) || targetType == typeof(int?))
            {
                if (targetType == typeof(int))
                {
                    InternalContract.RequireNotNull(source, nameof(source));
                }
                if (source == null)
                {
                    return((TTarget)(object)null);
                }
                return((TTarget)(object)source.ToString().ToInt());
            }
            throw new FulcrumNotImplementedException($"There is currently no rule on how to convert an id from type {sourceType.Name} to type {targetType.Name}.");
        }
        private async Task CacheItemCollectionOperationAsync(TModel[] itemsArray, int limit, string key, bool isSetOperation, CancellationToken token)
        {
            InternalContract.RequireNotNull(itemsArray, nameof(itemsArray));
            InternalContract.RequireGreaterThan(0, limit, nameof(limit));
            if (!isSetOperation)
            {
                InternalContract.Require(limit == int.MaxValue, $"When {nameof(isSetOperation)} is false, then {nameof(limit)} must be set to int.MaxValue ({int.MaxValue}), but it was set to {limit}.");
            }
            try
            {
                if (Options.SaveCollections)
                {
                    var cacheArrayTask = isSetOperation
                        ? CacheSetAsync(itemsArray, limit, key, token)
                        : Cache.RemoveAsync(key, token);
                    var cachePageTasks = new List <Task>();

                    // Cache individual pages
                    var offset = 0;
                    while (offset < itemsArray.Length)
                    {
                        var data         = itemsArray.Skip(offset).Take(PageInfo.DefaultLimit);
                        var pageEnvelope = new PageEnvelope <TModel>(offset, PageInfo.DefaultLimit, itemsArray.Length, data);
                        var task         = CacheItemPageOperationAsync(pageEnvelope, limit, key, isSetOperation, token);
                        cachePageTasks.Add(task);
                        offset += PageInfo.DefaultLimit;
                    }
                    await Task.WhenAll(cachePageTasks);

                    await cacheArrayTask;
                }
                else
                {
                    // Cache individual items
                    var cacheIndividualItemTasks = isSetOperation
                    ? itemsArray.Select(item => CacheSetAsync(item, token))
                        : itemsArray.Select(item => CacheRemoveByIdAsync(GetIdDelegate(item), token));
                    await Task.WhenAll(cacheIndividualItemTasks);
                }
            }
            finally
            {
                _collectionOperations.TryRemove(key, out _);
            }
        }
Пример #20
0
        public void FalseExpression()
        {
            const string message = "fail because expression is false";

            try
            {
                // ReSharper disable once ExpressionIsAlwaysNull
                InternalContract.Require((() => false), message);
                UT.Assert.Fail("An exception should have been thrown");
            }
            catch (FulcrumContractException fulcrumException)
            {
                UT.Assert.IsTrue(fulcrumException.TechnicalMessage.Contains(message));
            }
            catch (Exception e)
            {
                UT.Assert.Fail($"Expected a specific FulcrumException but got {e.GetType().FullName}.");
            }
        }
        public void False()
        {
            const string message = "fail because false";

            try
            {
                // ReSharper disable once ExpressionIsAlwaysNull
                InternalContract.Require(false, message);
                Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Fail("An exception should have been thrown");
            }
            catch (FulcrumContractException fulcrumException)
            {
                Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsTrue(fulcrumException.TechnicalMessage.Contains(message));
            }
            catch (Exception e)
            {
                Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Fail($"Expected a specific FulcrumException but got {e.GetType().FullName}.");
            }
        }
Пример #22
0
        /// <summary>
        /// Register a <paramref name="type"/> for a specific <paramref name="schemaName"/> and <paramref name="schemaVersion"/>.
        /// </summary>
        public SchemaParser Add(string schemaName, int schemaVersion, Type type)
        {
            InternalContract.RequireNotNull(schemaName, nameof(schemaName));
            InternalContract.RequireGreaterThanOrEqualTo(0, schemaVersion, nameof(schemaVersion));
            InternalContract.RequireNotNull(type, nameof(type));
            if (!_typeDictionary.TryGetValue(schemaName, out var versionDictionary))
            {
                versionDictionary = new ConcurrentDictionary <int, Type>();
                if (!_typeDictionary.TryAdd(schemaName, versionDictionary))
                {
                    versionDictionary = _typeDictionary[schemaName];
                }
            }

            var success = versionDictionary.TryAdd(schemaVersion, type);

            InternalContract.Require(success, $"Schema {schemaName} version {schemaVersion} had already been added.");

            return(this);
        }
        public void FalseParameterExpression()
        {
            const string parameterName = "parameterName";

            try
            {
                const int value = 23;
                // ReSharper disable once ExpressionIsAlwaysNull
                InternalContract.Require(value, x => x != 23, parameterName);
                Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Fail("An exception should have been thrown");
            }
            catch (FulcrumContractException fulcrumException)
            {
                Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsTrue(fulcrumException.TechnicalMessage.Contains(parameterName));
            }
            catch (Exception e)
            {
                Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Fail($"Expected a specific FulcrumException but got {e.GetType().FullName}.");
            }
        }
        /// <summary>
        /// Map an id between two types.
        /// </summary>
        /// <param name="source">The id to map.</param>
        /// <typeparam name="TTarget">The target type.</typeparam>
        /// <typeparam name="TSource">The source type.</typeparam>
        /// <exception cref="FulcrumNotImplementedException">Thrown if the type was not recognized. Please add that type to the class <see cref="MapperHelper"/>.</exception>
        public static TTarget MapToType <TTarget, TSource>(TSource source)
        {
            if (source == null)
            {
                return(default(TTarget));
            }
            if (Equals(source, default(TSource)))
            {
                return(default(TTarget));
            }
            var sourceType = typeof(TSource);
            var targetType = typeof(TTarget);

            if (targetType == typeof(string))
            {
                return((TTarget)(object)source.ToString());
            }
            if (targetType == typeof(Guid))
            {
                var success = Guid.TryParse(source.ToString(), out var valueAsGuid);
                InternalContract.Require(success, $"Could not parse parameter {nameof(source)} ({source}) of type {sourceType.Name} into type Guid.");
                return((TTarget)(object)valueAsGuid);
            }
            if (targetType == typeof(int))
            {
                var success = int.TryParse(source.ToString(), out var valueAsInt);
                InternalContract.Require(success, $"Could not parse parameter {nameof(source)} ({source}) of type {sourceType.Name} into type int.");
                return((TTarget)(object)valueAsInt);
            }
            if (targetType == typeof(int))
            {
                var success = int.TryParse(source.ToString(), out var valueAsInt);
                InternalContract.Require(success, $"Could not parse parameter {nameof(source)} ({source}) of type {sourceType.Name} into type int.");
                return((TTarget)(object)valueAsInt);
            }
            throw new FulcrumNotImplementedException($"There is currently no rule on how to convert an id from type {sourceType.Name} to type {targetType.Name}.");
        }
Пример #25
0
 /// <inheritdoc />
 public async Task DeleteAllAsync(CancellationToken token = new CancellationToken())
 {
     InternalContract.Require(!FulcrumApplication.IsInProductionOrProductionSimulation, "This method can\'t be called in production.");
     await _crmSystem.LeadFunctionality.DeleteAll();
 }
Пример #26
0
 /// <summary>
 /// Try to convert a JSON string into an object of one of the registered types
 /// </summary>
 /// <param name="jToken">The JSON object to convert.</param>
 /// <param name="obj">The converted object.</param>
 /// <returns>True if the conversion was successful.</returns>
 public bool TryParse(JToken jToken, out object obj)
 {
     InternalContract.RequireNotNull(jToken, nameof(jToken));
     InternalContract.Require(jToken.Type == JTokenType.Object, $"Parameter {nameof(jToken)} must be of a JSON object, but it was of type {jToken.Type}.");
     return(TryParse(jToken.ToString(), out obj));
 }
 /// <summary>
 /// Constructor
 /// </summary>
 public ClientCredentials(AuthenticationToken token)
 {
     InternalContract.RequireNotNull(token, nameof(token));
     InternalContract.Require(token.Type == "Bearer", $"Parameter {nameof(token)} must be of type Bearer.");
     _token = token;
 }
 private ITranslator CreateTranslator()
 {
     InternalContract.Require(TranslatorService != null,
                              $"{nameof(ValueTranslatorHttpSender)}.{nameof(TranslatorService)} must be set. It is a static property, so you normally set it once when your app starts up.");
     return(new Translator(TranslationClientName, TranslatorService));
 }
Пример #29
0
 /// <summary>
 /// Use this once to set a mandatory role for all services that has the attribute <see cref="MandatoryRoleRequirement"/>.
 /// </summary>
 /// <param name="roleName">The role to use for this application, e.g. 'business-api-caller'.</param>
 public static void SetMandatoryRole(string roleName)
 {
     InternalContract.Require(_mandatoryRole == null,
                              $"The mandatory role has already been set ({_mandatoryRole}). You are not allowed to change it.");
     _mandatoryRole = roleName;
 }
 /// <summary>
 /// Decrypt <paramref name="cipherText"/> using the symmetric key
 /// <param name="cipherText">The text to be decrypted</param>.
 /// </summary>
 public byte[] Decrypt(byte[] cipherText)
 {
     InternalContract.Require(_iv != null, "IV has not been set when calling the constructor.");
     return(ConvertText(cipherText, ref _iv));
 }