Exemplo n.º 1
0
        public IContextUpdater CreateContextUpdater(string taskId, string runId)
        {
            EnsureArg.IsNotEmptyOrWhiteSpace(taskId, nameof(taskId));
            EnsureArg.IsNotEmptyOrWhiteSpace(runId, nameof(runId));

            return(new SqlServerTaskContextUpdater(taskId, runId, _sqlConnectionWrapperFactory, _loggerFactory.CreateLogger <SqlServerTaskContextUpdater>()));
        }
        public DataBaseFunctionalityValidator(IDataSource dataSource, IOptions <ConnectionStrings> configuration)
        {
            _dataSource    = dataSource;
            _configuration = configuration.Value;

            EnsureArg.IsNotEmptyOrWhiteSpace(_configuration.DefaultConnection);
        }
Exemplo n.º 3
0
 public RetrieveResourceResponse(IEnumerable <Stream> responseStreams, string contentType)
 {
     EnsureArg.IsNotNull(responseStreams, nameof(responseStreams));
     EnsureArg.IsNotEmptyOrWhiteSpace(contentType, nameof(contentType));
     ResponseStreams = responseStreams;
     ContentType     = contentType;
 }
 public DataBaseFunctionalityValidator(ITokenDbContextFactory dbContextFactory,
                                       IOptions <ConnectionStrings> configuration)
 {
     _dbContextFactory = dbContextFactory;
     EnsureArg.IsNotEmptyOrWhiteSpace(_configuration.DefaultConnection);
     _configuration = configuration.Value;
 }
        public async Task <string> GetFirmwareUrlAsync(string deviceType)
        {
            EnsureArg.IsNotEmptyOrWhiteSpace(deviceType);
            var gitUrl = await _deviceServiceManager.GetFirmwareGitUrlAsync(deviceType).ConfigureAwait(false);

            return(gitUrl);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Creates the configuration asynchronous.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns></returns>
        public async Task <string> CreateConfigAsync(ConfigReadModel model)
        {
            EnsureArg.IsNotNull(model);
            EnsureArg.IsNotEmptyOrWhiteSpace(model.Block);
            EnsureArg.IsNotEmptyOrWhiteSpace(model.Module);

            return(await _service.CreateConfigTomlAsync(model));
        }
        public void IsNotEmptyOrWhiteSpace_WhenPartialWhiteSpace_It_should_not_throw()
        {
            string value = "  string with whitespace in it  ";

            ShouldNotThrow(
                () => Ensure.String.IsNotEmptyOrWhiteSpace(value, ParamName),
                () => EnsureArg.IsNotEmptyOrWhiteSpace(value, ParamName),
                () => Ensure.That(value, ParamName).IsNotEmptyOrWhiteSpace());
        }
        public void IsNotEmptyOrWhiteSpace_WhenNull_It_should_not_throw()
        {
            string value = null;

            ShouldNotThrow(
                () => Ensure.String.IsNotEmptyOrWhiteSpace(value, ParamName),
                () => Ensure.That(value, ParamName).IsNotEmptyOrWhiteSpace(),
                () => EnsureArg.IsNotEmptyOrWhiteSpace(value, ParamName));
        }
Exemplo n.º 9
0
        /// <summary>
        /// Gets the modules asynchronous.
        /// </summary>
        /// <param name="configTomlFileContent">Content of the configuration toml file.</param>
        /// <returns></returns>
        private async Task <IEnumerable <ModuleReadModel> > GetModulesAsync(string configTomlFileContent)
        {
            EnsureArg.IsNotEmptyOrWhiteSpace(configTomlFileContent);

            // get list of all modules.
            var modules = GetListOfModules(configTomlFileContent).ToList();
            await _defaultValueManager.MergeValuesWithModulesAsync(configTomlFileContent, modules).ConfigureAwait(false);

            return(modules);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ManagerResponseBase{TErrorCode}"/> class.
        /// </summary>
        /// <param name="errorCode">The error code.</param>
        /// <param name="message">The message.</param>
        public ManagerResponseBase(TErrorCode errorCode, string message)
        {
            EnsureArg.IsNotNull <TErrorCode>(errorCode, nameof(errorCode));
            EnsureArg.IsNotEmptyOrWhiteSpace(message, nameof(message));

            ErrorRecords = new ErrorRecords <TErrorCode>
            {
                new ErrorRecord <TErrorCode>(errorCode, message)
            };
        }
Exemplo n.º 11
0
        public (Channel <ImportResource> resourceChannel, Task loadTask) LoadResources(string resourceLocation, long startIndex, string resourceType, Func <long, long> sequenceIdGenerator, CancellationToken cancellationToken)
        {
            EnsureArg.IsNotEmptyOrWhiteSpace(resourceLocation, nameof(resourceLocation));

            Channel <ImportResource> outputChannel = Channel.CreateBounded <ImportResource>(ChannelMaxCapacity);

            Task loadTask = Task.Run(async() => await LoadResourcesInternalAsync(outputChannel, resourceLocation, startIndex, resourceType, sequenceIdGenerator, cancellationToken), cancellationToken);

            return(outputChannel, loadTask);
        }
Exemplo n.º 12
0
        public void IsNotEmptyOrWhiteSpace_WhenWhiteSpace_ThrowsArgumentException()
        {
            string value = "        ";

            ShouldThrow <ArgumentException>(
                ExceptionMessages.Strings_IsNotEmptyOrWhiteSpace_Failed,
                () => Ensure.String.IsNotEmptyOrWhiteSpace(value, ParamName),
                () => Ensure.That(value, ParamName).IsNotEmptyOrWhiteSpace(),
                () => EnsureArg.IsNotEmptyOrWhiteSpace(value, ParamName));
        }
Exemplo n.º 13
0
        public IExpressionEvaluator Create(TemplateExpression expression)
        {
            EnsureArg.IsNotEmptyOrWhiteSpace(expression?.Value, nameof(expression.Value));
            EnsureArg.IsNotNull(expression?.Language, nameof(expression.Language));

            return(expression.Language switch
            {
                TemplateExpressionLanguage.JsonPath => new JsonPathExpressionEvaluator(expression.Value),
                TemplateExpressionLanguage.JmesPath => new JmesPathExpressionEvaluator(_jmesPath, expression.Value),
                _ => throw new TemplateExpressionException($"Unsupported Expression Language: {expression?.Language}")
            });
Exemplo n.º 14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ErrorRecord{TErrorCode}"/> class.
        /// </summary>
        /// <param name="errorCode">The error code.</param>
        /// <param name="message">The message.</param>
        public ErrorRecord(TErrorCode errorCode, string message)
        {
            EnsureArg.IsNotNull <TErrorCode>(errorCode, nameof(errorCode));
            EnsureArg.IsNotEmptyOrWhiteSpace(message, nameof(message));

            var errorMessages = new ErrorMessages <TErrorCode>
            {
                new ErrorMessage <TErrorCode>(errorCode, message)
            };

            SetValues(null, 0, errorMessages);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Gets the list of modules.
        /// </summary>
        /// <param name="configTomlFile">The configuration toml file.</param>
        /// <returns></returns>
        private static IEnumerable <ModuleReadModel> GetListOfModules(string configTomlFile)
        {
            EnsureArg.IsNotEmptyOrWhiteSpace(configTomlFile);

            var data = TomlFileReader.ReadDataFromString <ConfigurationReadModel>(configTomlFile);

            var listOfModules = data.Module;

            listOfModules = listOfModules.Select((module, index) => new ModuleReadModel {
                Id = index, Config = module.Config, Name = module.Name, UUID = module.UUID
            }).ToList();
            return(listOfModules);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ErrorRecord{TErrorCode}"/> class.
        /// </summary>
        /// <param name="ordinalPosition">The ordinal position.</param>
        /// <param name="errorCode">The error code.</param>
        /// <param name="message">The message.</param>
        public ErrorRecord(int ordinalPosition, TErrorCode errorCode, string message)
        {
            EnsureArg.IsGte(ordinalPosition, 0, nameof(ordinalPosition));
            EnsureArg.IsNotNull <TErrorCode>(errorCode, nameof(errorCode));
            EnsureArg.IsNotEmptyOrWhiteSpace(message, nameof(message));

            var errorMessages = new ErrorMessages <TErrorCode>
            {
                new ErrorMessage <TErrorCode>(errorCode, message)
            };

            SetValues(null, ordinalPosition, errorMessages);
        }
        public IExpressionEvaluator Create(TemplateExpression expression)
        {
            EnsureArg.IsNotEmptyOrWhiteSpace(expression?.Value, nameof(expression.Value));

            var expressionLanguage = expression.Language ?? TemplateExpressionLanguage.JsonPath;

            if (expressionLanguage != TemplateExpressionLanguage.JsonPath)
            {
                throw new TemplateExpressionException($"Unsupported Expression Language {expressionLanguage}. Only JsonPath is supported.");
            }

            return(new JsonPathExpressionEvaluator(expression.Value));
        }
        /// <summary>
        /// Sets the git repo URL.
        /// </summary>
        /// <param name="deviceType">Type of the device.</param>
        /// <param name="gitUrl">The git URL.</param>
        public void SetGitRepoUrl(string deviceType, string gitUrl)
        {
            EnsureArg.IsNotEmptyOrWhiteSpace(deviceType);
            EnsureArg.IsNotEmptyOrWhiteSpace(gitUrl);

            _firmwareVersionGitConnection.GitRemoteLocation = gitUrl;
            _logger.LogInformation("Setting git repository connection");

            var appPath = GlobalMethods.GetCurrentAppPath();
            var temp    = Path.Combine(appPath, _firmwareVersionGitConnection.GitLocalFolder + "-" + deviceType);

            _repoManager.SetConnectionOptions(_firmwareVersionGitConnection, temp);
        }
Exemplo n.º 19
0
        public Stream TranscodeFrame(DicomFile dicomFile, int frameIndex, string requestedTransferSyntax)
        {
            EnsureArg.IsNotNull(dicomFile, nameof(dicomFile));
            EnsureArg.IsNotEmptyOrWhiteSpace(requestedTransferSyntax, nameof(requestedTransferSyntax));
            DicomDataset dataset = dicomFile.Dataset;

            // Validate requested frame index exists in file.
            dicomFile.GetPixelDataAndValidateFrames(new[] { frameIndex });
            var parsedDicomTransferSyntax = DicomTransferSyntax.Parse(requestedTransferSyntax);

            IByteBuffer resultByteBuffer = TranscodeFrame(dataset, frameIndex, parsedDicomTransferSyntax);

            return(_recyclableMemoryStreamManager.GetStream("RetrieveDicomResourceHandler.GetFrameAsDicomData", resultByteBuffer.Data, 0, resultByteBuffer.Data.Length));
        }
Exemplo n.º 20
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SearchModifier"/> class.
        /// </summary>
        /// <param name="searchModifierCode"><see cref="SearchModifierCode"/></param>
        /// <param name="resourceType">Resource type used to constrain abstract modifier code (e.g. <see cref="SearchModifierCode.Type"/>)</param>
        public SearchModifier(SearchModifierCode searchModifierCode, string resourceType = null)
        {
            if (searchModifierCode == SearchModifierCode.Type)
            {
                EnsureArg.IsNotEmptyOrWhiteSpace(resourceType, nameof(resourceType));
            }
            else
            {
                EnsureArg.Is(resourceType, null, nameof(resourceType));
            }

            SearchModifierCode = searchModifierCode;
            ResourceType       = resourceType;
        }
Exemplo n.º 21
0
        public static StringSegment GetParameter(this MediaTypeHeaderValue headerValue, string parameterName, bool tryRemoveQuotes = true)
        {
            EnsureArg.IsNotNull(headerValue, nameof(headerValue));
            EnsureArg.IsNotEmptyOrWhiteSpace(parameterName, nameof(parameterName));
            foreach (NameValueHeaderValue parameter in headerValue.Parameters)
            {
                if (StringSegment.Equals(parameter.Name, parameterName, StringComparison.OrdinalIgnoreCase))
                {
                    return(tryRemoveQuotes ? HeaderUtilities.RemoveQuotes(parameter.Value) : parameter.Value);
                }
            }

            return(StringSegment.Empty);
        }
Exemplo n.º 22
0
        protected T EvalExpression <T>(JToken token, string name, bool isRequired = false, params TemplateExpression[] expressions)
        {
            EnsureArg.IsNotNull(token, nameof(token));
            EnsureArg.IsNotEmptyOrWhiteSpace(name, nameof(name));

            if (expressions?.Any(e => e != null) == true)
            {
                var exceptions = new List <Exception>();

                foreach (var expression in expressions)
                {
                    if (expression == null)
                    {
                        continue;
                    }

                    var evaluator      = ExpressionEvaluatorFactory.Create(expression);
                    var evaluatedToken = evaluator.SelectToken(token);

                    if (evaluatedToken != null)
                    {
                        try
                        {
                            return(evaluatedToken.Value <T>());
                        }
                        catch (Exception e)
                        {
                            exceptions.Add(new IncompatibleDataException($"Encounted an error while extracting value for [{name}] using expression {expression.Value}", e));
                        }
                    }
                }

                if (isRequired)
                {
                    if (exceptions.Count > 0)
                    {
                        throw new IncompatibleDataException($"Unable to extract required value for [{name}]", new AggregateException(exceptions));
                    }

                    throw new IncompatibleDataException($"Unable to extract required value for [{name}] using {string.Join(",", expressions.Select(e => e.Value).ToArray())}");
                }
            }
            else if (isRequired)
            {
                throw new IncompatibleDataException($"An expression must be set for [{name}]");
            }

            return(default);
        public async Task <IEnumerable <string> > GetAllFirmwareVersionsAsync(string deviceType)
        {
            EnsureArg.IsNotEmptyOrWhiteSpace(deviceType);
            _logger.LogInformation($"{Prefix}: methodName: {nameof(GetAllFirmwareVersionsAsync)} Getting list of all firmware versions for device type {deviceType}.");
            var gitUrl = await GetFirmwareUrlAsync(deviceType).ConfigureAwait(false);

            _logger.LogInformation($"{Prefix}: methodName: {nameof(GetAllFirmwareVersionsAsync)} Git Repo url for device type {deviceType} is {gitUrl}.");

            SetGitRepoUrl(deviceType, gitUrl);

            // clone git repository.
            await CloneGitRepoAsync().ConfigureAwait(false);

            var listFirmwareVersions = await GetAllFirmwareVersionsAsync()
                                       .ConfigureAwait(false);

            return(listFirmwareVersions);
        }
Exemplo n.º 24
0
        public AcceptHeaderDescriptor(PayloadTypes payloadType, string mediaType, bool isTransferSyntaxMandatory, string transferSyntaxWhenMissing, ISet <string> acceptableTransferSyntaxes)
        {
            EnsureArg.IsNotEmptyOrWhiteSpace(mediaType, nameof(mediaType));

            // When transfersyntax is not mandatory, transferSyntaxWhenMissing has to be presented
            if (!isTransferSyntaxMandatory)
            {
                EnsureArg.IsNotEmptyOrWhiteSpace(transferSyntaxWhenMissing, nameof(transferSyntaxWhenMissing));
            }

            EnsureArg.IsNotNull(acceptableTransferSyntaxes, nameof(acceptableTransferSyntaxes));

            PayloadType = payloadType;
            MediaType   = mediaType;
            IsTransferSyntaxMandatory  = isTransferSyntaxMandatory;
            TransferSyntaxWhenMissing  = transferSyntaxWhenMissing;
            AcceptableTransferSyntaxes = acceptableTransferSyntaxes;
        }
Exemplo n.º 25
0
        public static string GetEventHubFQDN(string host)
        {
            EnsureArg.IsNotEmptyOrWhiteSpace(host);

            if (Uri.IsWellFormedUriString(host, UriKind.Absolute))
            {
                var uri = new Uri(host);
                host = uri.Host;
            }

            if (Uri.CheckHostName(host) != UriHostNameType.Unknown)
            {
                return(host);
            }
            else
            {
                throw new Exception($"The event hub FQDN: {host} is not valid");
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// Reads the data from string.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data">The data.</param>
        /// <param name="settings">The settings.</param>
        /// <returns></returns>
        /// <exception cref="CustomArgumentException"></exception>
        public static T ReadDataFromString <T>(string data, TomlSettings settings = null) where T : class, new()
        {
            EnsureArg.IsNotEmptyOrWhiteSpace(data, nameof(data));

            T fileData;

            try
            {
                settings ??= LoadLowerCaseTomlSettings();

                fileData = Toml.ReadString <T>(data, settings);
            }
            catch (Exception exception)
            {
                throw new CustomArgumentException(Resource.TomlParsingError, exception);
            }

            return(fileData);
        }
Exemplo n.º 27
0
        /// <summary>
        /// Determines whether [is path URL].
        /// </summary>
        /// <param name="path">The path.</param>
        /// <returns>
        ///   <c>true</c> if [is path URL] [the specified path]; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsPathUrl(this string path)
        {
            EnsureArg.IsNotEmptyOrWhiteSpace(path);

            if (System.IO.File.Exists(path))
            {
                return(false);
            }

            try
            {
                var uri = new Uri(path);
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Exemplo n.º 28
0
        public async Task <Stream> TranscodeFileAsync(Stream stream, string requestedTransferSyntax)
        {
            EnsureArg.IsNotNull(stream, nameof(stream));
            EnsureArg.IsNotEmptyOrWhiteSpace(requestedTransferSyntax, nameof(requestedTransferSyntax));
            var parsedDicomTransferSyntax = DicomTransferSyntax.Parse(requestedTransferSyntax);

            DicomFile dicomFile;

            try
            {
                dicomFile = await DicomFile.OpenAsync(stream, FileReadOption.ReadLargeOnDemand);
            }
            catch (DicomFileException)
            {
                throw;
            }

            stream.Seek(0, SeekOrigin.Begin);

            return(await TranscodeFileAsync(dicomFile, parsedDicomTransferSyntax));
        }
        private static IServiceCollection AddFunctionsOptions <T>(
            this IServiceCollection services,
            IConfiguration configuration,
            string sectionName,
            bool bindNonPublicProperties = false)
            where T : class
        {
            EnsureArg.IsNotNull(services, nameof(services));
            EnsureArg.IsNotNull(configuration, nameof(configuration));
            EnsureArg.IsNotEmptyOrWhiteSpace(sectionName, nameof(sectionName));

            services
            .AddOptions <T>()
            .Bind(
                configuration
                .GetSection(DicomFunctionsConfiguration.SectionName)
                .GetSection(sectionName),
                x => x.BindNonPublicProperties = bindNonPublicProperties)
            .ValidateDataAnnotations();

            return(services);
        }
        public async Task <Asset> CreateOutputAssetAsync(string inputAssetName, string outputAssetName)
        {
            EnsureArg.IsNotEmptyOrWhiteSpace(inputAssetName, nameof(inputAssetName));
            EnsureArg.IsNotEmptyOrWhiteSpace(outputAssetName, nameof(outputAssetName));
            var asset = new Asset();

            // Asset outputAsset =
            //     await _azureMediaServicesClient
            //         .Assets
            //         .GetAsync(
            //             _clientSettings.ResourceGroup,
            //             _clientSettings.AccountName,
            //             inputAssetName);

            return(await _azureMediaServicesClient.Assets.CreateOrUpdateAsync(
                       _clientSettings.ResourceGroup,
                       _clientSettings.AccountName,
                       outputAssetName,
                       asset));

            // TODO: Hypothetically we should be able to check if the asset exists and if it does we should not add anything
            // Check if an asset already exists.
        }