/// <summary>
 ///     Constructor
 /// </summary>
 public MemoryQueue(string name)
 {
     InternalContract.RequireNotNullOrWhiteSpace(name, nameof(name));
     Name   = name;
     _queue = new ConcurrentQueue <MessageEnvelope <T> >();
     KeepQueueAliveTimeSpan = TimeSpan.FromSeconds(1);
 }
Esempio n. 2
0
        public IFile CreateFile(string name)
        {
            InternalContract.RequireNotNullOrWhiteSpace(name, nameof(name));
            var blockBlob = _blobContainer.GetBlockBlobReference(name);

            return(new AzureBlockBlob(blockBlob));
        }
Esempio n. 3
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;
            }
        }
        public ValueTranslatorHttpSender(IHttpSender httpSender, string translationClientName)
        {
            InternalContract.RequireNotNull(httpSender, nameof(httpSender));
            InternalContract.RequireNotNullOrWhiteSpace(translationClientName, nameof(translationClientName));
            HttpSender = httpSender;

            TranslationClientName = translationClientName;
        }
Esempio n. 5
0
 /// <summary>
 /// Constructor
 /// </summary>
 public Tenant(string organization, string environment)
 {
     InternalContract.RequireNotNullOrWhiteSpace(organization, nameof(organization));
     InternalContract.RequireNotNullOrWhiteSpace(environment, nameof(environment));
     Organization = organization?.ToLower();
     Environment  = environment?.ToLower();
     Validate($"{Namespace}: 80BAC4F7-6369-4ACD-A34F-413A20E24C27");
 }
        public AzureBlobClient(string connectionString)
        {
            InternalContract.RequireNotNullOrWhiteSpace(connectionString, nameof(connectionString));
            var storageAccount = CloudStorageAccount.Parse(connectionString);

            _blobClient = storageAccount.CreateCloudBlobClient();
            FulcrumAssert.IsNotNull(_blobClient, null, "Could not create a cloud blob client.");
        }
        public AzureStorageTable(string connectionString, string name)
        {
            InternalContract.RequireNotNullOrWhiteSpace(connectionString, nameof(connectionString));
            var storageAccount = CloudStorageAccount.Parse(connectionString);
            var client         = storageAccount.CreateCloudTableClient();

            FulcrumAssert.IsNotNull(client, null, "Could not create a cloud table client.");
            Table = client.GetTableReference(name);
        }
Esempio n. 8
0
 /// <summary>
 /// Set up a new client translator.
 /// </summary>
 /// <param name="idConceptName">The <see cref="IdConceptName"/>.</param>
 /// <param name="getClientNameMethod">The <see cref="GetClientNameMethod"/>.</param>
 /// <param name="translatorService">The <see cref="TranslatorService"/>.</param>
 protected ClientTranslatorBase(string idConceptName, System.Func <string> getClientNameMethod, ITranslatorService translatorService)
 {
     InternalContract.RequireNotNullOrWhiteSpace(idConceptName, nameof(idConceptName));
     InternalContract.RequireNotNull(getClientNameMethod, nameof(getClientNameMethod));
     InternalContract.RequireNotNull(translatorService, nameof(translatorService));
     IdConceptName       = idConceptName;
     GetClientNameMethod = getClientNameMethod;
     TranslatorService   = translatorService;
 }
 /// <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 async Task <TStorableItem> ReadAsync(string partitionKey, string rowKey, CancellationToken token = default)
        {
            InternalContract.RequireNotNullOrWhiteSpace(partitionKey, nameof(partitionKey));
            InternalContract.RequireNotNullOrWhiteSpace(rowKey, nameof(rowKey));

            var tableRequestOptions = new TableRequestOptions();
            var operationContext    = new OperationContext();

            if (!await Table.ExistsAsync(tableRequestOptions, operationContext, token))
            {
                return(default);
 /// <summary>
 /// A translator for a specific <paramref name="clientName"/> that will use the <paramref name="service"/> for the actual translations.
 /// </summary>
 public Translator(string clientName, ITranslatorService service)
 {
     InternalContract.RequireNotNullOrWhiteSpace(clientName, nameof(clientName));
     InternalContract.RequireNotNull(service, nameof(service));
     _clientName        = clientName;
     _service           = service;
     _conceptValues     = new HashSet <string>();
     _translations      = new Dictionary <string, string>();
     _conceptValueRegex = new Regex(@"\(([^!]+)!([^!]+)!(.+)\)", RegexOptions.Compiled);
     _conceptValueAndNothingElseInStringRegex = new Regex("\"" + @"(\(([^!]+)!([^!]+)!(?:(?!\)" + "\"" + @").)+\))" + "\"", RegexOptions.Compiled);
 }
        /// <summary>
        /// Use this method to add a new <see cref="FulcrumException"/>. This means that it will be included in converting.
        /// </summary>
        /// <param name="exceptionType">The type of the exception.</param>
        /// <param name="inboundStatusCode">The status code that it should be converted to if we convert it to an HTTP response.</param>
        /// <param name="outboundExceptionType">Fulcrum errors of type <paramref name="exceptionType"/> should be converted to this type of exception.</param>
        public static void AddFulcrumException(Type exceptionType, HttpStatusCode inboundStatusCode, string outboundExceptionType)
        {
            InternalContract.RequireNotNull(exceptionType, nameof(exceptionType));
            InternalContract.RequireNotNullOrWhiteSpace(outboundExceptionType, nameof(outboundExceptionType));
            var createDelegate  = GetInstanceDelegate(exceptionType);
            var sourceException = createDelegate("test", (Exception)null);

            FactoryMethodsCache.Add(sourceException.Type, createDelegate);
            HttpStatusCodesCache.Add(sourceException.Type, inboundStatusCode);
            FulcrumErrorTargetExceptionType.Add(sourceException.Type, outboundExceptionType);
        }
        /// <inheritdoc />
        public StackifyLogger(string serverKey)
        {
            // Null serverKey is for testing, no log message is sent, but the LastSentEnvelope property is still set.
            if (!FulcrumApplication.IsInDevelopment)
            {
                InternalContract.RequireNotNullOrWhiteSpace(serverKey, nameof(serverKey));
            }
            _client = serverKey == null ? null : new Client(serverKey);
            var tenant = FulcrumApplication.Setup.Tenant;

            _env        = $"{tenant.Organization}/{tenant.Environment}";
            _serverName = FulcrumApplication.Setup.Name;
            _appName    = $"{FulcrumApplication.Setup.Name} {(FulcrumApplication.Setup.RunTimeLevel)}";
        }
Esempio n. 14
0
        /// <inheritdoc />
        public async Task <int> CountItemsAdvancedAsync(string selectFirst, string selectRest, object param = null, CancellationToken cancellationToken = default)
        {
            InternalContract.RequireNotNullOrWhiteSpace(selectFirst, nameof(selectFirst));
            InternalContract.RequireNotNullOrWhiteSpace(selectRest, nameof(selectRest));
            if (selectRest == null)
            {
                return(0);
            }
            var selectStatement = $"{selectFirst} {selectRest}";
            var result          = await InternalQueryAsync <int>(selectStatement, param, cancellationToken);

            FulcrumAssert.IsNotNull(result, CodeLocation.AsString());
            return(result.SingleOrDefault());
        }
        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));
        }
Esempio n. 16
0
 /// <inheritdoc />
 public async Task WithdrawAsync(string id, CancellationToken token = default(CancellationToken))
 {
     InternalContract.RequireNotNullOrWhiteSpace(id, nameof(id));
     try
     {
         await _crmSystem.LeadFunctionality.RejectAsync(id.ToGuid(), "Application withdrawn.");
     }
     catch (NotFoundException)
     {
         throw new FulcrumNotFoundException($"The application with id {id} could not be found.");
     }
     catch (Exception e)
     {
         throw e.ToNexusException();
     }
 }
Esempio n. 17
0
        /// <inheritdoc />
        public async Task <string> ApproveAsync(string id, CancellationToken token = default(CancellationToken))
        {
            InternalContract.RequireNotNullOrWhiteSpace(id, nameof(id));
            try
            {
                var memberId = await _crmSystem.LeadFunctionality.QualifyAsync(id.ToGuid());

                return(memberId.ToIdString());
            }
            catch (NotFoundException)
            {
                throw new FulcrumNotFoundException($"The application with id {id} could not be found.");
            }
            catch (Exception e)
            {
                throw e.ToNexusException();
            }
        }
Esempio n. 18
0
        public void WhitespaceString()
        {
            const string parameterName = "parameterName";

            try
            {
                string whitespaceString = "     \t";
                // ReSharper disable once ExpressionIsAlwaysNull
                InternalContract.RequireNotNullOrWhiteSpace(whitespaceString, parameterName);
                UT.Assert.Fail("An exception should have been thrown");
            }
            catch (FulcrumContractException fulcrumException)
            {
                UT.Assert.IsTrue(fulcrumException.TechnicalMessage.Contains(parameterName));
            }
            catch (Exception e)
            {
                UT.Assert.Fail($"Expected a specific FulcrumException but got {e.GetType().FullName}.");
            }
        }
        /// <summary>
        /// Get a string value.
        /// </summary>
        /// <param name="name">The name of the app setting.</param>
        /// <param name="isMandatory">Throw an excepton if this is true and no value was found.</param>
        /// <returns>The found string or null.</returns>
        public string GetString(string name, bool isMandatory)
        {
            // We must not have InternalContract and stuff here, since we may not have set up logging, etc.
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new FulcrumContractException($"Parameter {nameof(name)} was empty.");
            }
            InternalContract.RequireNotNullOrWhiteSpace(name, nameof(name));
            var value = _appSettingGetter?.GetAppSetting(name)
#if NETSTANDARD
                        ?? _configuration[name]
#endif
            ;

            if (isMandatory && string.IsNullOrWhiteSpace(value))
            {
                throw new FulcrumContractException($"Missing app setting: {name}");
            }
            return(value);
        }
        public async Task CreateAsync(string partitionKey, string rowKey, TStorableItemCreate item, CancellationToken token = default)
        {
            InternalContract.RequireNotNullOrWhiteSpace(partitionKey, nameof(partitionKey));
            InternalContract.RequireNotNullOrWhiteSpace(rowKey, nameof(rowKey));
            InternalContract.RequireNotNull(item, nameof(item));
            InternalContract.RequireValidated(item, nameof(item));

            var dbItem = StorageHelper.DeepCopy <TStorableItem, TStorableItemCreate>(item);

            StorageHelper.MaybeCreateNewEtag(dbItem);
            StorageHelper.MaybeUpdateTimeStamps(dbItem, true);
            InternalContract.RequireValidated(dbItem, nameof(item));

            var tableRequestOptions = new TableRequestOptions();
            var operationContext    = new OperationContext();
            var createTableTask     = Table.CreateIfNotExistsAsync(tableRequestOptions, operationContext, token);
            var entity = new JsonEntity(partitionKey, rowKey)
            {
                ETag         = dbItem.Etag,
                JsonAsString = JsonConvert.SerializeObject(dbItem)
            };
            await createTableTask;
            await Table.ExecuteAsync(TableOperation.Insert(entity, true), tableRequestOptions, operationContext, token);
        }
        /// <inheritdoc />
        public async Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options,
                                   CancellationToken cancellationToken = default)
        {
            InternalContract.RequireNotNullOrWhiteSpace(key, nameof(key));
            InternalContract.RequireNotNull(value, nameof(value));

            var item = await GetAsync(key, cancellationToken);

            if (item == null)
            {
                try
                {
                    await ItemStorage.CreateWithSpecifiedIdAsync(key, value, cancellationToken);
                }
                catch (FulcrumConflictException)
                {
                    await ItemStorage.UpdateAsync(key, value, cancellationToken);
                }
            }
            else
            {
                await ItemStorage.UpdateAsync(key, value, cancellationToken);
            }
        }
Esempio n. 22
0
 /// <inheritdoc />
 public Client(string serverKey)
 {
     InternalContract.RequireNotNullOrWhiteSpace(serverKey, nameof(serverKey));
     _serverKey = serverKey;
     _client    = new RestClient(new HttpSender(@"https://api.stackify.com/Log/Save"));
 }
Esempio n. 23
0
 /// <summary>
 /// The constructor
 /// </summary>
 /// <param name="connectionString">How to connect to the database.</param>
 public Database(string connectionString)
 {
     InternalContract.RequireNotNullOrWhiteSpace(connectionString, nameof(connectionString));
     _connectionString = connectionString;
 }
Esempio n. 24
0
 /// <inheritdoc />
 public async Task DeleteAsync(string id, CancellationToken token = new CancellationToken())
 {
     InternalContract.RequireNotNullOrWhiteSpace(id, nameof(id));
     await _crmSystem.ContactFunctionality.Delete(id.ToGuid());
 }
 public MemoryQueue(string name, QueueItemActionDelegate queueItemAction = null,
                    bool actionsCanExecuteWithoutIndividualAwait         = false) : this(name)
 {
     InternalContract.RequireNotNullOrWhiteSpace(name, nameof(name));
     SetQueueItemAction(queueItemAction, actionsCanExecuteWithoutIndividualAwait);
 }
 public MemoryQueue(string name, QueueItemActionDelegate queueItemAction) : this(name)
 {
     InternalContract.RequireNotNullOrWhiteSpace(name, nameof(name));
     SetQueueItemAction(queueItemAction);
 }
 /// <inheritdoc />
 public T GetValue <T>(string key)
 {
     InternalContract.RequireNotNullOrWhiteSpace(key, nameof(key));
     if (!Dictionary.TryGetValue(key, out AsyncLocal <object> asyncLocalObject))
     {
         return(default);
Esempio n. 28
0
 /// <summary>
 /// Constructor
 /// </summary>
 public OneValueProvider(IValueProvider valueProvider, string key)
 {
     _valueProvider = valueProvider;
     InternalContract.RequireNotNullOrWhiteSpace(key, nameof(key));
     Key = key;
 }
 /// <inheritdoc />
 public async Task RemoveAsync(string key, CancellationToken cancellationToken = default)
 {
     InternalContract.RequireNotNullOrWhiteSpace(key, nameof(key));
     await ItemStorage.DeleteAsync(key, cancellationToken);
 }
 /// <inheritdoc />
 public async Task <byte[]> GetAsync(string key, CancellationToken cancellationToken = default)
 {
     InternalContract.RequireNotNullOrWhiteSpace(key, nameof(key));
     return(await ItemStorage.ReadAsync(key, cancellationToken));
 }