private async Task <HttpRequestMessage> CreateRequest <TResponse, TBody>(HttpMethod method, string relativeUrl, Dictionary <string, List <string> > customHeaders,
                                                                                 CancellationToken cancellationToken, TBody instance) where TBody : class
        {
            InternalContract.RequireNotNullOrWhitespace(relativeUrl, nameof(relativeUrl));
            var baseUrl = BaseUri.AbsoluteUri;

            if (!baseUrl.EndsWith("/"))
            {
                baseUrl += "/";
            }
            if (relativeUrl.StartsWith("/"))
            {
                relativeUrl = relativeUrl.Substring(1);
            }
            var url = new Uri(new Uri(baseUrl), relativeUrl).ToString();

            var request = CreateRequest(method, url, customHeaders);

            if (instance != null)
            {
                var requestContent =
                    Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(instance, _serializationSettings);
                request.Content = new StringContent(requestContent, System.Text.Encoding.UTF8);
                request.Content.Headers.ContentType =
                    System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            }

            if (Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Credentials.ProcessHttpRequestAsync(request, cancellationToken).ConfigureAwait(false);
            }
            return(request);
        }
        /// <inheritdoc />
        public async Task <TDatabaseItem> SearchFirstAdvancedAsync(string selectStatement, string orderBy = null, object param = null, CancellationToken token = default(CancellationToken))
        {
            InternalContract.RequireNotNullOrWhitespace(selectStatement, nameof(selectStatement));
            var result = await InternalSearchAsync(param, selectStatement, orderBy, 0, 1);

            return(result.SingleOrDefault());
        }
        public async Task <TResponse> GetAsync <TResponse>(string relativeUrl)
        {
            InternalContract.RequireNotNullOrWhitespace(relativeUrl, nameof(relativeUrl));
            var response = await SendRequestAsync <TResponse, object>(HttpMethod.Get, relativeUrl);

            return(response.Body);
        }
        public async Task <TResponse> PutAsync <TResponse, TBody>(string relativeUrl, TBody instance)
            where TBody : class
        {
            InternalContract.RequireNotNullOrWhitespace(relativeUrl, nameof(relativeUrl));
            var response = await SendRequestAsync <TResponse, TBody>(HttpMethod.Post, relativeUrl, null, default(CancellationToken), instance);

            return(response.Body);
        }
Пример #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");
 }
 protected internal async Task <IEnumerable <TDatabaseItem> > QueryAsync(string statement, object param = null, CancellationToken token = default(CancellationToken))
 {
     InternalContract.RequireNotNullOrWhitespace(statement, nameof(statement));
     using (var db = Database.NewSqlConnection())
     {
         return(await db.QueryAsync <TDatabaseItem>(statement, param));
     }
 }
 protected internal async Task ExecuteAsync(string statement, object param = null, CancellationToken token = default(CancellationToken))
 {
     InternalContract.RequireNotNullOrWhitespace(statement, nameof(statement));
     using (var db = Database.NewSqlConnection())
     {
         await db.ExecuteAsync(statement, param);
     }
 }
Пример #8
0
 /// <inheritdoc />
 public T GetValue <T>(string key)
 {
     InternalContract.RequireNotNullOrWhitespace(key, nameof(key));
     if (Holder?.Value?.ContainsKey(key) != true)
     {
         return(default(T));
     }
     return((T)Holder.Value[key]);
 }
Пример #9
0
 /// <inheritdoc />
 public T GetValue <T>(string key)
 {
     InternalContract.RequireNotNullOrWhitespace(key, nameof(key));
     if (!Dictionary.ContainsKey(key))
     {
         return(default(T));
     }
     return((T)Dictionary[key]);
 }
Пример #10
0
        /// <inheritdoc />
        public async Task PublishAsync(string entityName, string eventName, int majorVersion, int minorVersion, JObject eventBody)
        {
            InternalContract.RequireNotNullOrWhitespace(entityName, nameof(entityName));
            InternalContract.RequireNotNullOrWhitespace(eventName, nameof(eventName));
            InternalContract.RequireGreaterThanOrEqualTo(1, majorVersion, nameof(majorVersion));
            InternalContract.RequireGreaterThanOrEqualTo(0, minorVersion, nameof(minorVersion));

            FulcrumAssert.IsTrue(FulcrumApplication.IsInDevelopment, $"This method can only be called in run time level Development. The run time level was {FulcrumApplication.Setup.RunTimeLevel}");
            var relativeUrl = $"api/BusinessEvents/{entityName}/{eventName}/{majorVersion}/{minorVersion}";
            await RestClient.PostNoResponseContentAsync(relativeUrl, eventBody);
        }
Пример #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;
 }
Пример #12
0
 /// <inheritdoc />
 public void SetValue <T>(string name, T data)
 {
     InternalContract.RequireNotNullOrWhitespace(name, nameof(name));
     InternalContract.RequireNotNull(data, nameof(data));
     FulcrumAssert.IsNotNull(Holder, $"{Namespace}: 07B2EC29-9231-4DC1-82FF-09DCB6EC87FA");
     if (Holder.Value == null)
     {
         Holder.Value = new Dictionary <string, object>();
     }
     Holder.Value[name] = data;
 }
        /// <summary>
        /// Find the items specified by the <paramref name="selectStatement"/>.
        /// </summary>
        /// <param name="param">The fields for the <paramref name="selectStatement"/> condition.</param>
        /// <param name="selectStatement">The SELECT statement, including WHERE, but not ORDER BY.</param>
        /// <param name="orderBy">An expression for how to order the result.</param>
        /// <param name="offset">The number of items that will be skipped in result.</param>
        /// <param name="limit">The maximum number of items to return.</param>
        /// <returns>The found items.</returns>
        ///
        protected async Task <IEnumerable <TDatabaseItem> > InternalSearchAsync(object param, string selectStatement, string orderBy,
                                                                                int offset, int limit)
        {
            InternalContract.RequireGreaterThanOrEqualTo(0, offset, nameof(offset));
            InternalContract.RequireGreaterThanOrEqualTo(0, limit, nameof(limit));
            InternalContract.RequireNotNullOrWhitespace(selectStatement, nameof(selectStatement));
            orderBy = orderBy ?? TableMetadata.GetOrderBy() ?? "1";
            var sqlQuery = $"{selectStatement} " +
                           $" ORDER BY {orderBy}" +
                           $" OFFSET {offset} ROWS FETCH NEXT {limit} ROWS ONLY";

            return(await QueryAsync(sqlQuery, param));
        }
        /// <inheritdoc />
        public async Task <Person> FindFirstOrDefaultByNameAsync(string name, CancellationToken token = default(CancellationToken))
        {
            InternalContract.RequireNotNullOrWhitespace(name, nameof(name));
            var enumerator =
                new PageEnvelopeEnumeratorAsync <Person>((offset, t) => ReadAllWithPagingAsync(offset, null, t), token);

            while (await enumerator.MoveNextAsync())
            {
                if (enumerator.Current.Name == name)
                {
                    return(enumerator.Current);
                }
            }

            return(null);
        }
        /// <inheritdoc />
        public async Task <int> CountItemsAdvancedAsync(string selectFirst, string selectRest, object param = null, CancellationToken token = default(CancellationToken))
        {
            InternalContract.RequireNotNullOrWhitespace(selectFirst, nameof(selectFirst));
            InternalContract.RequireNotNullOrWhitespace(selectRest, nameof(selectRest));
            if (selectRest == null)
            {
                return(0);
            }
            var selectStatement = $"{selectFirst} {selectRest}";

            using (IDbConnection db = Database.NewSqlConnection())
            {
                return((await db.QueryAsync <int>(selectStatement, param))
                       .SingleOrDefault());
            }
        }
Пример #16
0
        public void EmptyString()
        {
            const string parameterName = "parameterName";

            try
            {
                string emptyString = "";
                // ReSharper disable once ExpressionIsAlwaysNull
                InternalContract.RequireNotNullOrWhitespace(emptyString, 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}.");
            }
        }
        public void WhitespaceString()
        {
            const string parameterName = "parameterName";

            try
            {
                string whitespaceString = "     \t";
                // ReSharper disable once ExpressionIsAlwaysNull
                InternalContract.RequireNotNullOrWhitespace(whitespaceString, 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}.");
            }
        }
Пример #18
0
        /// <inheritdoc />
        public async Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options,
                                   CancellationToken token = default(CancellationToken))
        {
            InternalContract.RequireNotNullOrWhitespace(key, nameof(key));
            InternalContract.RequireNotNull(value, nameof(value));

            var item = await GetAsync(key, token);

            if (item == null)
            {
                try
                {
                    await ItemStorage.CreateWithSpecifiedIdAsync(key, value, token);
                }
                catch (FulcrumConflictException)
                {
                    await ItemStorage.UpdateAsync(key, value, token);
                }
            }
            else
            {
                await ItemStorage.UpdateAsync(key, value, token);
            }
        }
 /// <inheritdoc />
 public async Task <TDatabaseItem> SearchAdvancedSingleAsync(string selectStatement, object param = null, CancellationToken token = default(CancellationToken))
 {
     InternalContract.RequireNotNullOrWhitespace(selectStatement, nameof(selectStatement));
     return(await SearchFirstAdvancedAsync(selectStatement, null, param, token));
 }
 /// <summary>
 /// Constructor
 /// </summary>
 public MemoryQueue(string name)
 {
     InternalContract.RequireNotNullOrWhitespace(name, nameof(name));
     Name   = name;
     _queue = new Queue <T>();
 }
Пример #21
0
 /// <inheritdoc />
 public async Task <byte[]> GetAsync(string key, CancellationToken token = default(CancellationToken))
 {
     InternalContract.RequireNotNullOrWhitespace(key, nameof(key));
     return(await ItemStorage.ReadAsync(key, token));
 }
 public async Task PostNoResponseContentAsync <TBody>(string relativeUrl, TBody instance)
     where TBody : class
 {
     InternalContract.RequireNotNullOrWhitespace(relativeUrl, nameof(relativeUrl));
     await SendRequestAsync <object, TBody>(HttpMethod.Post, relativeUrl, null, default(CancellationToken), instance);
 }
 public async Task DeleteAsync(string relativeUrl)
 {
     InternalContract.RequireNotNullOrWhitespace(relativeUrl, nameof(relativeUrl));
     await SendRequestAsync <object, object>(HttpMethod.Delete, relativeUrl);
 }
Пример #24
0
 /// <inheritdoc />
 public async Task RemoveAsync(string key, CancellationToken token = default(CancellationToken))
 {
     InternalContract.RequireNotNullOrWhitespace(key, nameof(key));
     await ItemStorage.DeleteAsync(key, token);
 }
 public async Task <T> PutAsync <T>(string relativeUrl, T instance)
     where T : class
 {
     InternalContract.RequireNotNullOrWhitespace(relativeUrl, nameof(relativeUrl));
     return(await PutAsync <T, T>(relativeUrl, instance));
 }
 /// <summary>
 /// Get a value from the cache if all constraints are fulfilled.
 /// </summary>
 protected async Task <TModel> CacheGetByKeyAsync(string key, CancellationToken token = default(CancellationToken))
 {
     InternalContract.RequireNotNullOrWhitespace(key, nameof(key));
     return(await CacheGetAsync(default(TId), key, token));
 }
 public async Task PostNoResponseContentAsync(string relativeUrl)
 {
     InternalContract.RequireNotNullOrWhitespace(relativeUrl, nameof(relativeUrl));
     await SendRequestAsync <object, object>(HttpMethod.Post, relativeUrl);
 }
Пример #28
0
 /// <inheritdoc />
 public void SetValue <T>(string name, T data)
 {
     InternalContract.RequireNotNullOrWhitespace(name, nameof(name));
     InternalContract.RequireNotNull(data, nameof(data));
     Dictionary[name] = data;
 }
 /// <summary>
 /// Put the item in the cache.
 /// </summary>
 protected async Task CacheSetByKeyAsync(string key, TModel item, CancellationToken token = default(CancellationToken))
 {
     InternalContract.RequireNotNullOrWhitespace(key, nameof(key));
     await CacheSetAsync(default(TId), item, key, token);
 }