Ejemplo n.º 1
0
 protected virtual void OnValidateFormatMediaTypeName(ArgumentUtilitiesHandle <string> name)
 {
     name
     .EnsureNotNull()
     .EnsureNotEmptyOrWhiteSpace();
     //
 }
Ejemplo n.º 2
0
        // TODO: Improve exception message.
        //
        public static Stats Calculate(ArgumentUtilitiesHandle <IEnumerable <double> > values, Stats entire = default)
        {
            values.EnsureNotNull();
            var valuesArray =
                values
                .Value
                .Select(
                    (locValue, locIndex) => {
                if (double.IsNaN(locValue))
                {
                    throw
                    new ArgumentOutOfRangeException(
                        paramName: $"{values.Name}[{locIndex:d}]",
                        message: FormatXResource(locator: typeof(ArgumentOutOfRangeException), subpath: "CanNotNaN"));
                }
                return(locValue);
            })
                .ToArray();

            if (valuesArray.Length == 0)
            {
                return(entire is null ? Empty : new Stats(entire: entire));
            }
            else if (!(entire is null) && (entire.IsEmpty || entire.Count < valuesArray.Length))
            {
                throw new ArgumentOutOfRangeException(paramName: nameof(entire));
            }
Ejemplo n.º 3
0
 // TODO: Put strings into the resources.
 //
 public static void EnsureValid(ArgumentUtilitiesHandle <string> name)
 {
     if (!IsValid(name.Value, out var validationMessage))
     {
         var exceptionMessage = (name.IsProp ? $"Указано недопустимое значение свойства '{name.Name}'.{Environment.NewLine}" : string.Empty) + validationMessage;
         throw name.ExceptionFactory?.Invoke(message: exceptionMessage) ?? new ArgumentException(message: exceptionMessage, paramName: name.Name);
     }
 }
 public ServiceProviderHandler(ArgumentUtilitiesHandle <IServiceProvider> serviceProvider)
 {
     serviceProvider.EnsureNotNull();
     //
     _serviceProvider = serviceProvider.Value;
     _serviceScope    = null;
     _hasServiceScope = false;
 }
        public ServiceProviderHandler(ArgumentUtilitiesHandle <IServiceScope> serviceScope, bool ownsServiceScope = default)
        {
            var locServiceScope    = serviceScope.EnsureNotNull().Value;
            var locServiceProvider = locServiceScope.ServiceProvider.ArgProp($"{nameof(serviceScope)}.{nameof(serviceScope.Value.ServiceProvider)}").EnsureNotNull().Value;

            //
            _serviceProvider = locServiceProvider;
            _serviceScope    = locServiceScope.ToValueHolder(ownsValue: ownsServiceScope);
            _hasServiceScope = true;
        }
Ejemplo n.º 6
0
        public static void EnsureValid(ArgumentUtilitiesHandle <string> id)
        {
            string validationMessage;

            if (!IsValid(id.Value, out validationMessage))
            {
                throw
                    new ArgumentException(message: validationMessage, paramName: id.Name);
            }
        }
Ejemplo n.º 7
0
 public DependencyScope(ArgumentUtilitiesHandle <IServiceProviderHandler> outerServiceProvider, bool ownsOuterServiceProvider = default)
 {
     outerServiceProvider.EnsureNotNull();
     //
     _outerScopeGetter           = new DefaultOuterDependencyScopeGetter(outerScope: null).ToValueHolder(ownsValue: true);
     _prohibitNewInstanceRequest = false;
     P_CtorInitializer(
         exporter: new DefaultDependencyExporter(handler: outerServiceProvider.Value, ownsHandler: ownsOuterServiceProvider),
         ownsDependencyExporter: true,
         outerServiceProvider: outerServiceProvider.Value.ServiceProvider,
         owner: null);
 }
Ejemplo n.º 8
0
        public MetadataPathName(ArgumentUtilitiesHandle <string> metadataPathName)
        {
            string validationMessage;

            if (P_TryParse(metadataPathName, out validationMessage, out _value, out _components))
            {
                P_PutInCache(this);
            }
            else
            {
                throw new ArgumentException(message: $"{FormatXResource(typeof(ArgumentException), "ValueIsInvalid")}{Environment.NewLine}{validationMessage}", paramName: metadataPathName.Name);
            }
        }
Ejemplo n.º 9
0
        public static void ParseSerializationString(ArgumentUtilitiesHandle <string> value, out string assembly, out string type)
        {
            value.EnsureNotNull().EnsureNotEmpty().EnsureHasMaxLength(maxLength: SerializationStringMaxLength).EnsureMatchRegex(regex: SerializationStringRegex);
            //
            var valueString = value.Value;
            var index1      = valueString.IndexOf(value: '=');
            var index2      = valueString.IndexOf(value: ';', startIndex: index1 + 1);
            var index3      = valueString.IndexOf(value: '=', startIndex: index2);
            var locAssembly = valueString.Substring(startIndex: index1 + 1, index2 - index1 - 1);
            var locType     = valueString.Substring(startIndex: index3 + 1, valueString.Length - (index3 + 1) - (valueString[valueString.Length - 1] == ';' ? 1 : 0));

            assembly = locAssembly;
            type     = locType;
        }
Ejemplo n.º 10
0
 public static UriBasedIdentifier AsChanged(this UriBasedIdentifier original, ArgumentUtilitiesHandle <string> newUriString)
 {
     if (newUriString.Value == null)
     {
         return(null);
     }
     else if (ReferenceEquals(original, null) || !original.StringValue.EqualsOrdinalCS(newUriString.Value))
     {
         return(new UriBasedIdentifier(uriString: newUriString));
     }
     else
     {
         return(original);
     }
 }
Ejemplo n.º 11
0
        public static bool IsNonStaticRead(this ArgumentUtilitiesHandle <PropertyInfo> hnd, out MethodInfo getAccessor)
        {
            MethodInfo getter, setter;

            hnd.EnsureNotNull().EnsureNonStatic(out getter, out setter);
            //
            if (getter is null)
            {
                getAccessor = null;
                return(false);
            }
            else
            {
                getAccessor = getter;
                return(true);
            }
        }
Ejemplo n.º 12
0
        public static bool IsWrite(this ArgumentUtilitiesHandle <PropertyInfo> hnd, out MethodInfo setAccessor)
        {
            hnd.EnsureNotNull();
            //
            var locSetAccessor = hnd.Value.GetSetMethod(true);

            if (locSetAccessor is null)
            {
                setAccessor = null;
                return(false);
            }
            else
            {
                setAccessor = locSetAccessor;
                return(true);
            }
        }
Ejemplo n.º 13
0
 // TODO: Put strings into the resources.
 //
 static bool P_TryDeconstructManifestResourceUri(ArgumentUtilitiesHandle <Uri> uri, bool partial, out AssemblyName assemblyName, out string name, out Exception exception)
 {
     uri.EnsureNotNull();
     //
     try {
         uri
         .EnsureAbsolute()
         .EnsureScheme(scheme: UriUtilities.UriSchemeAsemblyManifestResource)
         .EnsureComponentsOnly(components: UriComponents.Scheme | UriComponents.Path)
         .EnsureFixedSegmentCount(count: partial ? 2 : 3);
         try {
             var    locAssemblyNameString = Uri.UnescapeDataString(stringToUnescape: uri.Value.Segments[1].TrimEndSingle('/'));
             var    locAssemblyName       = new AssemblyName(assemblyName: locAssemblyNameString);
             string locName;
             if (partial)
             {
                 locName = null;
             }
             else
             {
                 locName = Uri.UnescapeDataString(uri.Value.Segments[2]);
                 if (string.IsNullOrEmpty(locName))
                 {
                     throw new EonException(message: "В указанном URI отсутствует имя ресурса.");
                 }
             }
             assemblyName = locAssemblyName;
             name         = locName;
             exception    = null;
             return(true);
         }
         catch (Exception locException) {
             throw
                 new ArgumentException(paramName: uri.Name, message: "Ошибка обработки компонентов URI.", innerException: locException);
         }
     }
     catch (Exception locException) {
         exception    = locException;
         assemblyName = default;
         name         = default;
         return(false);
     }
 }
Ejemplo n.º 14
0
        public static bool IsNonStatic(this ArgumentUtilitiesHandle <PropertyInfo> hnd, out MethodInfo getAccessor, out MethodInfo setAccessor)
        {
            hnd.EnsureNotNull();
            //
            var locGetAccessor = hnd.Value.GetGetMethod(true);
            var locSetAccessor = hnd.Value.GetSetMethod(true);
            var isStatic       = locGetAccessor?.IsStatic ?? locSetAccessor.IsStatic;

            if (isStatic)
            {
                getAccessor = null;
                setAccessor = null;
                return(false);
            }
            else
            {
                getAccessor = locGetAccessor;
                setAccessor = locSetAccessor;
                return(true);
            }
        }
Ejemplo n.º 15
0
 /// <summary>
 /// Выполняет парсинг строки <paramref name="metadataPathName"/> и возвращает объект пути метаданных — <seealso cref="MetadataPathName"/>.
 /// </summary>
 /// <param name="metadataPathName">
 /// Входная строка, представляющая путь метаданных.
 /// <para>Может быть null. В этом случае метод возвращает null.</para>
 /// </param>
 /// <returns>Объект <seealso cref="MetadataPathName"/>.</returns>
 public static MetadataPathName Parse(ArgumentUtilitiesHandle <string> metadataPathName)
 {
     if (metadataPathName.Value == null)
     {
         return(null);
     }
     else
     {
         MetadataPathName result;
         if (P_TryGetFromCache(metadataPathName.Value, out result))
         {
             return(result);
         }
         else
         {
             return
                 (new MetadataPathName(
                      metadataPathName: metadataPathName));
         }
     }
 }
Ejemplo n.º 16
0
 public static MetadataPropertyHandle <TMetadata, string> EnsureNotEquals <TMetadata>(
     this MetadataPropertyHandle <TMetadata, string> hnd,
     ArgumentUtilitiesHandle <string> operand,
     StringComparison comparison)
     where TMetadata : class, IMetadata
 {
     //
     hnd.EnsureHandleValid();
     //
     try {
         hnd
         .PropertyValue
         .ArgProp(nameof(hnd.PropertyValue))
         .EnsureNotEquals(operand, comparison);
     }
     catch (ArgumentException firstException) {
         throw hnd.P_CreateMetadataValidationException(firstException);
     }
     //
     return(hnd);
 }
Ejemplo n.º 17
0
        // TODO: Put strings into the resources.
        //
        public static string RequireSingleValue(this ArgumentUtilitiesHandle <NameValueCollection> collection, string name)
        {
            collection.EnsureNotNull();
            name.EnsureNotNull(nameof(name));
            //
            var values = collection.Value.GetValues(name: name);

            if (values is null)
            {
                var message = $"The required named value is missing.{Environment.NewLine}\tName:{name.FmtStr().GNLI2()}";
                throw collection.ExceptionFactory?.Invoke(message: message) ?? new ArgumentException(message: message, paramName: collection.Name);
            }
            else if (values.Length == 1)
            {
                return(values[0]);
            }
            else
            {
                var message = $"The specified name maps to more than one values.{Environment.NewLine}\tName:{name.FmtStr().GNLI2()}";
                throw collection.ExceptionFactory?.Invoke(message: message) ?? new ArgumentException(message: message, paramName: collection.Name);
            }
        }
Ejemplo n.º 18
0
        public static T RequireSingleParameter <T>(this ArgumentUtilitiesHandle <NameValueCollection> collection, string name, Func <string, T> converter)
        {
            collection.EnsureNotNull();
            converter.EnsureNotNull(nameof(converter));
            //
            string valueString;

            try {
                valueString = collection.RequireSingleValue(name: name);
            }
            catch (Exception exception) {
                throw new OperationIllegalParameterException(message: $"Parameter reading error.{Environment.NewLine}Parameter name:{name.FmtStr().GNLI2()}", innerException: exception);
            }
            T value;

            try {
                value = converter(arg: valueString);
            }
            catch (Exception exception) {
                throw new OperationIllegalParameterException(message: $"An exception occurred while converting the string value of the specified parameter to the value of type '{typeof(T)}'.{Environment.NewLine}Parameter name:{name.FmtStr().GNLI2()}", innerException: exception);
            }
            return(value);
        }
Ejemplo n.º 19
0
 public DependencyServiceScope(ArgumentUtilitiesHandle <IServiceScope> serviceScope, bool ownsServiceScope = default)
     : base(outerServiceScope: serviceScope, ownsOuterServiceScope: ownsServiceScope)
 {
 }
Ejemplo n.º 20
0
 public static TContext Set <TContext, T>(this TContext ctx, ContextProperty <T> prop, ArgumentUtilitiesHandle <T> value)
     where TContext : class, IContext
 {
     //
     if (ctx is null)
     {
         throw new ArgumentNullException(paramName: nameof(ctx));
     }
     else if (prop is null)
     {
         throw new ArgumentNullException(paramName: nameof(prop));
     }
     //
     prop.SetLocalValue(ctx: ctx, value: value);
     return(ctx);
 }
Ejemplo n.º 21
0
 public static Task <IList <ITriggerXInstance> > CreateInitializeAsync(ArgumentUtilitiesHandle <IEnumerable <ITriggerDescription> > descriptions, IXAppScopeInstance scope, IContext ctx = default)
 => XInstanceFactoryUtilities.CreateInitializeAppScopeInstanceAsync <ITriggerXInstance>(scope: scope, ctx: ctx, descriptions: descriptions.AsBase <IEnumerable <ITriggerDescription>, IEnumerable <IDescription> >());
Ejemplo n.º 22
0
 public static bool TryDeconstructManifestResourceUri(ArgumentUtilitiesHandle <Uri> uri, out AssemblyName assemblyName, out Exception exception)
 => P_TryDeconstructManifestResourceUri(uri: uri, partial: true, assemblyName: out assemblyName, name: out var name, exception: out exception);
Ejemplo n.º 23
0
 public static PersistenceEntityReferenceKeyTypeDescriptor GetReferenceKeyTypeDescriptor(ArgumentUtilitiesHandle <Type> entityType)
 {
     entityType.EnsureNotNull();
     //
     return
         (__ReferenceKeyTypeDescriptorCache
          .GetOrAdd(
              spinLock: __ReferenceKeyTypeDescriptorCacheSpinLock,
              key: entityType.Value,
              factory:
              (locEntityType) => {
         locEntityType.Arg(name: entityType.Name).EnsureClass().EnsureNotContainsGenericParameters();
         //
         var locEntityTypeInfo = locEntityType.GetTypeInfo();
         var locFoundInterfaces =
             locEntityTypeInfo
             .FindInterfaces(
                 filter: (locT, locCriteria) => {
             var locTInfo = locT.GetTypeInfo();
             return locTInfo.IsGenericType && locTInfo.GetGenericTypeDefinition() == __IPersistenceEntityType2GenericDefinition;
         },
                 filterCriteria: null);
         if (locFoundInterfaces.Length == 0)
         {
             throw
             new ArgumentException(
                 paramName: entityType.Name,
                 message: FormatXResource(locator: typeof(Type), subpath: "NoImplementationOfT", args: new object[] { locEntityType, __IPersistenceEntityType2GenericDefinition }));
         }
         else if (locFoundInterfaces.Length > 1)
         {
             throw
             new ArgumentException(
                 paramName: entityType.Name,
                 message: FormatXResource(locator: typeof(Type), subpath: "AmbiguousImplementationOfT", args: new object[] { locEntityType, __IPersistenceEntityType2GenericDefinition }));
         }
         else
         {
             return new PersistenceEntityReferenceKeyTypeDescriptor(entityType: locEntityType, referenceKeyType: locFoundInterfaces[0].GetTypeInfo().GetGenericArguments()[0]);
         }
     }));
 }
Ejemplo n.º 24
0
 /// <summary>
 /// Создает дескриптор доступа к утилитам одиночного узла к.л. дерева.
 /// </summary>
 /// <typeparam name="T">Тип узла дерева.</typeparam>
 /// <param name="hnd">Дескриптор доступа к утилитам аргумента, представляющий узел дерева (см. <see cref="ArgumentUtilitiesHandle{T}.Value"/>).</param>
 /// <returns>Значение <seealso cref="SingleTreeNodeUtilitiesHandle{T}"/>.</returns>
 public static SingleTreeNodeUtilitiesHandle <T> TreeNode <T>(this ArgumentUtilitiesHandle <T> hnd)
 => new SingleTreeNodeUtilitiesHandle <T>(source: hnd.Value);
Ejemplo n.º 25
0
 public static bool IsNonStaticRead(this ArgumentUtilitiesHandle <PropertyInfo> hnd)
 => IsNonStaticRead(hnd, out _);
Ejemplo n.º 26
0
 public static bool HasIndexParameters(this ArgumentUtilitiesHandle <PropertyInfo> hnd)
 => hnd.EnsureNotNull().Value.GetIndexParameters().Length > 0;
Ejemplo n.º 27
0
 public static Stats Calculate(ArgumentUtilitiesHandle <IEnumerable <int> > values, Stats entire = default)
 => Calculate(values: values.EnsureNotNull().Select(locValue => (double)locValue), entire: entire);
Ejemplo n.º 28
0
 public static DurationStats Calculate(ArgumentUtilitiesHandle <IEnumerable <TimeSpan> > values, DurationStats entire = default)
 => new DurationStats(stats: Stats.Calculate(values: values.Select(selector: locValue => locValue.TotalMilliseconds), entire: entire?._stats), entire: entire);