static void ValidateDisplayColumnAttribute(DisplayColumnAttribute displayColumnAttribute, PropertyInfo?displayColumnProperty, Type modelType)
        {
            if (displayColumnProperty is null)
            {
                throw new InvalidOperationException(
                          String.Format(
                              CultureInfo.CurrentCulture,
                              MvcResources.DataAnnotationsModelMetadataProvider_UnknownProperty,
                              modelType.FullName, displayColumnAttribute.DisplayColumn));
            }

            if (displayColumnProperty.GetGetMethod() is null)
            {
                throw new InvalidOperationException(
                          String.Format(
                              CultureInfo.CurrentCulture,
                              MvcResources.DataAnnotationsModelMetadataProvider_UnreadableProperty,
                              modelType.FullName, displayColumnAttribute.DisplayColumn));
            }
        }
Exemplo n.º 2
0
        public static void ThrowInvalidOperationException_SerializationConverterOnAttributeNotCompatible(Type classTypeAttributeIsOn, PropertyInfo?propertyInfo, Type typeToConvert)
        {
            string location = classTypeAttributeIsOn.ToString();

            if (propertyInfo != null)
            {
                location += $".{propertyInfo.Name}";
            }

            throw new InvalidOperationException(SR.Format(SR.SerializationConverterOnAttributeNotCompatible, location, typeToConvert));
        }
        private static Func <string, CancellationToken, byte[]>?CreateDownloadBytesFunc()
        {
            try
            {
                // Use reflection to access System.Net.Http:
                // Since System.Net.Http.dll explicitly depends on System.Security.Cryptography.X509Certificates.dll,
                // the latter can't in turn have an explicit dependency on the former.

                // Get the relevant types needed.
                Type?socketsHttpHandlerType  = Type.GetType("System.Net.Http.SocketsHttpHandler, System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", throwOnError: false);
                Type?httpClientType          = Type.GetType("System.Net.Http.HttpClient, System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", throwOnError: false);
                Type?httpRequestMessageType  = Type.GetType("System.Net.Http.HttpRequestMessage, System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", throwOnError: false);
                Type?httpResponseMessageType = Type.GetType("System.Net.Http.HttpResponseMessage, System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", throwOnError: false);
                Type?httpContentType         = Type.GetType("System.Net.Http.HttpContent, System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", throwOnError: false);
                if (socketsHttpHandlerType == null || httpClientType == null || httpRequestMessageType == null || httpResponseMessageType == null || httpContentType == null)
                {
                    Debug.Fail("Unable to load required type.");
                    return(null);
                }

                // Get the methods on those types.
                PropertyInfo?   pooledConnectionIdleTimeoutProp = socketsHttpHandlerType.GetProperty("PooledConnectionIdleTimeout");
                PropertyInfo?   requestUriProp         = httpRequestMessageType.GetProperty("RequestUri");
                ConstructorInfo?httpRequestMessageCtor = httpRequestMessageType.GetConstructor(Type.EmptyTypes);
                MethodInfo?     sendMethod             = httpClientType.GetMethod("Send", new Type[] { httpRequestMessageType, typeof(CancellationToken) });
                PropertyInfo?   responseContentProp    = httpResponseMessageType.GetProperty("Content");
                MethodInfo?     readAsStreamMethod     = httpContentType.GetMethod("ReadAsStream", Type.EmptyTypes);
                if (pooledConnectionIdleTimeoutProp == null || requestUriProp == null || httpRequestMessageCtor == null || sendMethod == null || responseContentProp == null || readAsStreamMethod == null)
                {
                    Debug.Fail("Unable to load required member.");
                    return(null);
                }

                // Only keep idle connections around briefly, as a compromise between resource leakage and port exhaustion.
                const int PooledConnectionIdleTimeoutSeconds = 15;

                // Equivalent of:
                // var socketsHttpHandler = new SocketsHttpHandler() { PooledConnectionIdleTimeout = TimeSpan.FromSeconds(PooledConnectionIdleTimeoutSeconds) };
                // var httpClient = new HttpClient(socketsHttpHandler);
                object?socketsHttpHandler = Activator.CreateInstance(socketsHttpHandlerType);
                pooledConnectionIdleTimeoutProp.SetValue(socketsHttpHandler, TimeSpan.FromSeconds(PooledConnectionIdleTimeoutSeconds));
                object?httpClient = Activator.CreateInstance(httpClientType, new object?[] { socketsHttpHandler });

                // Return a delegate for getting the byte[] for a uri. This delegate references the HttpClient object and thus
                // all accesses will be through that singleton.
                return((string uri, CancellationToken cancellationToken) =>
                {
                    // Equivalent of:
                    // HttpResponseMessage resp = httpClient.Send(new HttpRequestMessage() { RequestUri = new Uri(uri) });
                    // using Stream responseStream = resp.Content.ReadAsStream();
                    // Note: using a ConstructorInfo instead of Activator.CreateInstance, so the ILLinker can see the usage through the lambda method.
                    object requestMessage = httpRequestMessageCtor.Invoke(null);
                    requestUriProp.SetValue(requestMessage, new Uri(uri));
                    object responseMessage = sendMethod.Invoke(httpClient, new object[] { requestMessage, cancellationToken }) !;
                    object content = responseContentProp.GetValue(responseMessage) !;
                    using Stream responseStream = (Stream)readAsStreamMethod.Invoke(content, null) !;

                    var result = new MemoryStream();
                    responseStream.CopyTo(result);
                    return result.ToArray();
                });
            }
            catch
            {
                // We shouldn't have any exceptions, but if we do, ignore them all.
                return(null);
            }
        }
Exemplo n.º 4
0
        private static Func <string, CancellationToken, bool, ValueTask <byte[]?> >?CreateDownloadBytesFunc()
        {
            try
            {
                // Use reflection to access System.Net.Http:
                // Since System.Net.Http.dll explicitly depends on System.Security.Cryptography.X509Certificates.dll,
                // the latter can't in turn have an explicit dependency on the former.

                // Get the relevant types needed.
                Type?socketsHttpHandlerType  = Type.GetType("System.Net.Http.SocketsHttpHandler, System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", throwOnError: false);
                Type?httpMessageHandlerType  = Type.GetType("System.Net.Http.HttpMessageHandler, System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", throwOnError: false);
                Type?httpClientType          = Type.GetType("System.Net.Http.HttpClient, System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", throwOnError: false);
                Type?httpRequestMessageType  = Type.GetType("System.Net.Http.HttpRequestMessage, System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", throwOnError: false);
                Type?httpResponseMessageType = Type.GetType("System.Net.Http.HttpResponseMessage, System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", throwOnError: false);
                Type?httpResponseHeadersType = Type.GetType("System.Net.Http.Headers.HttpResponseHeaders, System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", throwOnError: false);
                Type?httpContentType         = Type.GetType("System.Net.Http.HttpContent, System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", throwOnError: false);

                if (socketsHttpHandlerType == null || httpMessageHandlerType == null || httpClientType == null || httpRequestMessageType == null ||
                    httpResponseMessageType == null || httpResponseHeadersType == null || httpContentType == null)
                {
                    Debug.Fail("Unable to load required type.");
                    return(null);
                }

                Type taskOfHttpResponseMessageType = typeof(Task <>).MakeGenericType(httpResponseMessageType);

                // Get the methods on those types.
                ConstructorInfo?socketsHttpHandlerCtor          = socketsHttpHandlerType.GetConstructor(Type.EmptyTypes);
                PropertyInfo?   pooledConnectionIdleTimeoutProp = socketsHttpHandlerType.GetProperty("PooledConnectionIdleTimeout");
                PropertyInfo?   allowAutoRedirectProp           = socketsHttpHandlerType.GetProperty("AllowAutoRedirect");
                ConstructorInfo?httpClientCtor                      = httpClientType.GetConstructor(new Type[] { httpMessageHandlerType });
                PropertyInfo?   requestUriProp                      = httpRequestMessageType.GetProperty("RequestUri");
                ConstructorInfo?httpRequestMessageCtor              = httpRequestMessageType.GetConstructor(Type.EmptyTypes);
                MethodInfo?     sendMethod                          = httpClientType.GetMethod("Send", new Type[] { httpRequestMessageType, typeof(CancellationToken) });
                MethodInfo?     sendAsyncMethod                     = httpClientType.GetMethod("SendAsync", new Type[] { httpRequestMessageType, typeof(CancellationToken) });
                PropertyInfo?   responseContentProp                 = httpResponseMessageType.GetProperty("Content");
                PropertyInfo?   responseStatusCodeProp              = httpResponseMessageType.GetProperty("StatusCode");
                PropertyInfo?   responseHeadersProp                 = httpResponseMessageType.GetProperty("Headers");
                PropertyInfo?   responseHeadersLocationProp         = httpResponseHeadersType.GetProperty("Location");
                MethodInfo?     readAsStreamMethod                  = httpContentType.GetMethod("ReadAsStream", Type.EmptyTypes);
                PropertyInfo?   taskOfHttpResponseMessageResultProp = taskOfHttpResponseMessageType.GetProperty("Result");

                if (socketsHttpHandlerCtor == null || pooledConnectionIdleTimeoutProp == null ||
                    allowAutoRedirectProp == null || httpClientCtor == null ||
                    requestUriProp == null || httpRequestMessageCtor == null ||
                    sendMethod == null || sendAsyncMethod == null ||
                    responseContentProp == null || responseStatusCodeProp == null ||
                    responseHeadersProp == null || responseHeadersLocationProp == null ||
                    readAsStreamMethod == null || taskOfHttpResponseMessageResultProp == null)
                {
                    Debug.Fail("Unable to load required members.");
                    return(null);
                }

                // Only keep idle connections around briefly, as a compromise between resource leakage and port exhaustion.
                const int PooledConnectionIdleTimeoutSeconds = 15;
                const int MaxRedirections = 10;

                // Equivalent of:
                // var socketsHttpHandler = new SocketsHttpHandler() {
                //     PooledConnectionIdleTimeout = TimeSpan.FromSeconds(PooledConnectionIdleTimeoutSeconds),
                //     AllowAutoRedirect = false
                // };
                // var httpClient = new HttpClient(socketsHttpHandler);
                // Note: using a ConstructorInfo instead of Activator.CreateInstance, so the ILLinker can see the usage through the lambda method.
                object?socketsHttpHandler = socketsHttpHandlerCtor.Invoke(null);
                pooledConnectionIdleTimeoutProp.SetValue(socketsHttpHandler, TimeSpan.FromSeconds(PooledConnectionIdleTimeoutSeconds));
                allowAutoRedirectProp.SetValue(socketsHttpHandler, false);
                object?httpClient = httpClientCtor.Invoke(new object?[] { socketsHttpHandler });

                return(async(string uriString, CancellationToken cancellationToken, bool async) =>
                {
                    Uri uri = new Uri(uriString);

                    if (!IsAllowedScheme(uri.Scheme))
                    {
                        return null;
                    }

                    // Equivalent of:
                    // HttpRequestMessage requestMessage = new HttpRequestMessage() { RequestUri = new Uri(uri) };
                    // HttpResponseMessage responseMessage = httpClient.Send(requestMessage, cancellationToken);
                    // Note: using a ConstructorInfo instead of Activator.CreateInstance, so the ILLinker can see the usage through the lambda method.
                    object requestMessage = httpRequestMessageCtor.Invoke(null);
                    requestUriProp.SetValue(requestMessage, uri);
                    object responseMessage;

                    if (async)
                    {
                        Task sendTask = (Task)sendAsyncMethod.Invoke(httpClient, new object[] { requestMessage, cancellationToken }) !;
                        await sendTask.ConfigureAwait(false);

                        responseMessage = taskOfHttpResponseMessageResultProp.GetValue(sendTask) !;
                    }
                    else
                    {
                        responseMessage = sendMethod.Invoke(httpClient, new object[] { requestMessage, cancellationToken }) !;
                    }

                    int redirections = 0;
                    Uri?redirectUri;
                    bool hasRedirect;
                    while (true)
                    {
                        int statusCode = (int)responseStatusCodeProp.GetValue(responseMessage) !;
                        object responseHeaders = responseHeadersProp.GetValue(responseMessage) !;
                        Uri?location = (Uri?)responseHeadersLocationProp.GetValue(responseHeaders);
                        redirectUri = GetUriForRedirect((Uri)requestUriProp.GetValue(requestMessage) !, statusCode, location, out hasRedirect);
                        if (redirectUri == null)
                        {
                            break;
                        }

                        ((IDisposable)responseMessage).Dispose();

                        redirections++;
                        if (redirections > MaxRedirections)
                        {
                            ReportRedirectsExceeded();

                            return null;
                        }

                        ReportRedirected(redirectUri);

                        // Equivalent of:
                        // requestMessage = new HttpRequestMessage() { RequestUri = redirectUri };
                        // requestMessage.RequestUri = redirectUri;
                        // responseMessage = httpClient.Send(requestMessage, cancellationToken);
                        requestMessage = httpRequestMessageCtor.Invoke(null);
                        requestUriProp.SetValue(requestMessage, redirectUri);

                        if (async)
                        {
                            Task sendTask = (Task)sendAsyncMethod.Invoke(httpClient, new object[] { requestMessage, cancellationToken }) !;
                            await sendTask.ConfigureAwait(false);

                            responseMessage = taskOfHttpResponseMessageResultProp.GetValue(sendTask) !;
                        }
                        else
                        {
                            responseMessage = sendMethod.Invoke(httpClient, new object[] { requestMessage, cancellationToken }) !;
                        }
                    }

                    if (hasRedirect && redirectUri == null)
                    {
                        return null;
                    }

                    // Equivalent of:
                    // using Stream responseStream = resp.Content.ReadAsStream();
                    object content = responseContentProp.GetValue(responseMessage) !;
                    using Stream responseStream = (Stream)readAsStreamMethod.Invoke(content, null) !;

                    var result = new MemoryStream();
                    if (async)
                    {
                        await responseStream.CopyToAsync(result).ConfigureAwait(false);
                    }
                    else
                    {
                        responseStream.CopyTo(result);
                    }
                    ((IDisposable)responseMessage).Dispose();
                    return result.ToArray();
                });
            }
            catch
            {
                // We shouldn't have any exceptions, but if we do, ignore them all.
                return(null);
            }
        }
Exemplo n.º 5
0
        public static void ThrowInvalidOperationException_CannotSerializeInvalidType(Type type, Type?parentClassType, PropertyInfo?propertyInfo)
        {
            if (parentClassType == null)
            {
                Debug.Assert(propertyInfo == null);
                throw new InvalidOperationException(SR.Format(SR.CannotSerializeInvalidType, type));
            }

            Debug.Assert(propertyInfo != null);
            throw new InvalidOperationException(SR.Format(SR.CannotSerializeInvalidMember, type, propertyInfo.Name, parentClassType));
        }
Exemplo n.º 6
0
 public static bool IsVirtual(this PropertyInfo?propertyInfo)
 {
     Debug.Assert(propertyInfo != null);
     return(propertyInfo != null && (propertyInfo.GetMethod?.IsVirtual == true || propertyInfo.SetMethod?.IsVirtual == true));
 }
Exemplo n.º 7
0
        private static ICommand GetCommand(object viewModel, MethodInfo method, MethodInfo?validateM, PropertyInfo?foundProperty)
        {
            var item = method.GetCustomAttribute <CommandAttribute>();

            if (item == null)
            {
                throw new BasicBlankException("Was not even a custom command.  Rethink");
            }
            ICommand?output;

            if (!(viewModel is IBlankGameVM blank))
            {
                throw new BasicBlankException("This is not a blank game view model.  Rethink");
            }
            if (blank.CommandContainer == null)
            {
                throw new BasicBlankException("The command container for command not there.  Rethink");
            }
            switch (item.Category)
            {
            case EnumCommandCategory.Plain:
                if (foundProperty == null && validateM != null)
                {
                    output = new PlainCommand(viewModel, method, validateM, blank.CommandContainer);
                }
                else
                {
                    output = new PlainCommand(viewModel, method, foundProperty !, blank.CommandContainer);
                }
                break;

            case EnumCommandCategory.Game:
                if (!(viewModel is IBasicEnableProcess basics))
                {
                    throw new BasicBlankException("You need to implement the IEnableAlways in order to use out of turn command.  Rethink");
                }
                if (foundProperty == null && validateM != null)
                {
                    output = new BasicGameCommand(basics, method, validateM, blank.CommandContainer);
                }
                else
                {
                    output = new BasicGameCommand(basics, method, foundProperty !, blank.CommandContainer);
                }
                break;

            case EnumCommandCategory.Limited:
                if (!(viewModel is IBasicEnableProcess basics2))
                {
                    throw new BasicBlankException("You need to implement the IEnableAlways in order to use out of turn command.  Rethink");
                }
                if (foundProperty == null && validateM != null)
                {
                    output = new LimitedGameCommand(basics2, method, validateM, blank.CommandContainer);
                }
                else
                {
                    output = new LimitedGameCommand(basics2, method, foundProperty !, blank.CommandContainer);
                }
                break;

            case EnumCommandCategory.OutOfTurn:

                if (!(viewModel is IEnableAlways enables))
                {
                    throw new BasicBlankException("You need to implement the IEnableAlways in order to use out of turn command.  Rethink");
                }

                output = new OutOfTurnCommand(enables, method, blank.CommandContainer);
                break;

            case EnumCommandCategory.Open:
                if (foundProperty == null && validateM != null)
                {
                    output = new OpenCommand(viewModel, method, validateM, blank.CommandContainer);
                }
                else
                {
                    output = new OpenCommand(viewModel, method, foundProperty !, blank.CommandContainer);
                }
                break;

            case EnumCommandCategory.Control:
                if (!(viewModel is IControlObservable control))
                {
                    throw new BasicBlankException("You need to implement the IControlVM in order to use control command.  Rethink");
                }
                output = new ControlCommand(control, method, blank.CommandContainer);
                break;

            case EnumCommandCategory.Old:
                if (foundProperty == null && validateM != null)
                {
                    output = new ReflectiveCommand(viewModel, method, validateM);
                }
                else
                {
                    output = new ReflectiveCommand(viewModel, method, foundProperty !);
                }
                break;

            default:
                throw new BasicBlankException("Not supported");
            }
            if (output == null)
            {
                throw new BasicBlankException("No command.   Rethink");
            }
            return(output);
        }
Exemplo n.º 8
0
 public IEnumerable <IOclElement> ToElements(OclConversionContext context, PropertyInfo?propertyInfo, object value)
 => throw new NotSupportedException();
Exemplo n.º 9
0
 public static bool PropertyEquals(PropertyInfo?p1, PropertyInfo?p2)
 {
     return(MemeberEquals(p1, p2));
 }
Exemplo n.º 10
0
        ///<summary>
        /// Gets the Type of a list item.
        ///</summary>
        /// <param name="list">A <see cref="System.Object"/> instance. </param>
        ///<returns>The Type instance that represents the exact runtime type of a list item.</returns>
        public static Type GetListItemType(this IEnumerable?list)
        {
            var typeOfObject = typeof(object);

            if (list == null)
            {
                return(typeOfObject);
            }

            if (list is Array)
            {
                return(list.GetType().GetElementType() !);
            }

            var type = list.GetType();

            if (list is IList || list is ITypedList || list is IListSource)
            {
                PropertyInfo?last = null;

                foreach (var pi in type.GetPropertiesEx())
                {
                    if (pi.GetIndexParameters().Length > 0 && pi.PropertyType != typeOfObject)
                    {
                        if (pi.Name == "Item")
                        {
                            return(pi.PropertyType);
                        }

                        last = pi;
                    }
                }

                if (last != null)
                {
                    return(last.PropertyType);
                }
            }

            if (list is IList list1)
            {
                foreach (var o in list1)
                {
                    if (o != null && o.GetType() != typeOfObject)
                    {
                        return(o.GetType());
                    }
                }
            }
            else
            {
                foreach (var o in list)
                {
                    if (o != null && o.GetType() != typeOfObject)
                    {
                        return(o.GetType());
                    }
                }
            }

            return(typeOfObject);
        }
Exemplo n.º 11
0
        public PoseFile Upgrade(Appearance.Races race)
        {
            PoseFile file       = new PoseFile();
            Type     legacyType = this.GetType();

            if (this.Race == null)
            {
                throw new Exception("Legacy pose file has no race specified");
            }

            Appearance.Races fileRace = (Appearance.Races) byte.Parse(this.Race);
            file.Bones = new Dictionary <string, PoseFile.Bone?>();

            PropertyInfo[] props = this.GetType().GetProperties(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance);
            foreach (PropertyInfo propertyInfo in props)
            {
                string boneName = propertyInfo.Name;

                if (boneName == "Race")
                {
                    continue;
                }

                if (boneName.EndsWith("Size"))
                {
                    continue;
                }

                if (boneName == "Type")
                {
                    continue;
                }

                PropertyInfo?rotProp   = legacyType.GetProperty(boneName);
                PropertyInfo?scaleProp = legacyType.GetProperty(boneName + "Size");

                if (boneName.StartsWith(@"Hroth") && fileRace != Appearance.Races.Hrothgar)
                {
                    continue;
                }

                if (boneName.StartsWith("Viera") && fileRace != Appearance.Races.Viera)
                {
                    continue;
                }

                boneName = boneName.Replace(@"Hroth", string.Empty);
                boneName = boneName.Replace(@"Viera", string.Empty);

                string?rotString   = null;
                string?scaleString = null;

                if (rotProp != null)
                {
                    rotString = (string?)rotProp.GetValue(this);
                }

                if (scaleProp != null)
                {
                    scaleString = (string?)scaleProp.GetValue(this);
                }

                if (rotString == null && scaleString == null)
                {
                    continue;
                }

                PoseFile.Bone bone = StringToBone(rotString, scaleString);

                if (file.Bones.ContainsKey(boneName))
                {
                    file.Bones.Remove(boneName);
                }

                file.Bones.Add(boneName, bone);
            }

            return(file);
        }
Exemplo n.º 12
0
        public static object?GetObjectPropertyValue(object?item, string propertyName, out PropertyInfo?prop)
        {
            prop = null;
            if (item == null)
            {
                return(null);
            }

            var type = item.GetType();

            prop = type.GetProperty(propertyName);
            if (prop == null)
            {
                throw new Exception(String.Format("The object of type {0} does not have a property named {1}!", type, propertyName));     // TODO: exception handling
            }
            return(prop.GetValue(item));
        }
Exemplo n.º 13
0
 public static Type?TryGetEnumerableArgumentUnderlyingType(this PropertyInfo?property)
 {
     return(property != null && property.PropertyType != typeof(string)
                ? property.PropertyType.TryGetEnumerableUnderlyingType()
                : null);
 }
        public static object?Read(ref Utf8JsonReader reader,
                                  Type typeToConvert,
                                  JsonSerializerOptions nestedOptions,
                                  Func <Type, JsonSerializerOptions, IEnumerable <PropertyInfo> >?getPropertiesToRead = null)
        {
            getPropertiesToRead ??= GetDefaultPropertiesToRead;
            switch (reader.TokenType)
            {
            case JsonTokenType.StartObject:
            {
                var obj        = Activator.CreateInstance(typeToConvert);
                var properties = getPropertiesToRead(typeToConvert, nestedOptions)
                                 .ToDictionary(keySelector: p => p.Name.ToLower(), StringComparer.CurrentCultureIgnoreCase);
                var extensionProperties = getPropertiesToRead(typeToConvert, nestedOptions).Where(p => p.HasAttribute <JsonExtensionDataAttribute>())
                                          .Take(2)
                                          .ToList();
                PropertyInfo?extensionProperty = null;
                if (extensionProperties.Count == 2)
                {
                    throw new InvalidOperationException("Multiple properties decorated with 'JsonExtensionDataAttribute' found");
                }
                else if (extensionProperties.Count == 1)
                {
                    extensionProperty = extensionProperties[0];
                    if (!typeof(IDictionary <string, object>).IsAssignableFrom(extensionProperty.PropertyType))
                    {
                        throw new InvalidOperationException($"Property '{extensionProperty.Name}' decorated with 'JsonExtensionDataAttribute' is not assignable to `IDictionary<string, object>`");
                    }
                }

                IDictionary <string, object?>?extensionDictionary = null;
                if (extensionProperty != null)
                {
                    extensionDictionary = new Dictionary <string, object?>();
                    extensionProperty.SetValue(obj, extensionDictionary);
                }
                while (true)
                {
                    reader.Read();
                    if (reader.TokenType == JsonTokenType.EndObject)
                    {
                        break;
                    }
                    Contract.Assert(reader.TokenType == JsonTokenType.PropertyName);

                    string propertyName = reader.GetString() ?? throw new ContractException();

                    if (properties.TryGetValue(propertyName, out PropertyInfo? property))
                    {
                        var    copy = reader;
                        object?value;
                        try
                        {
                            value = JsonSerializer.Deserialize(ref reader, property.PropertyType, nestedOptions);
                        }
                        catch (JsonException)
                        {
                            var token = copy.GetTokenAsJson();
                            throw new JsonException($"Cannot deserialize type '{property.PropertyType}' from: \n\n" + token);
                        }
                        property.SetValue(obj, value);
                    }
                    else if (extensionDictionary != null)
                    {
                        var value = JsonSerializer.Deserialize <object?>(ref reader, nestedOptions);
                        extensionDictionary[propertyName] = value;
                    }
                    else
                    {
                        Global.AddDebugObject("Ignoring property " + propertyName);
                    }
                }
                return(obj);
            }

            case JsonTokenType.StartArray:
                throw new NotImplementedException();

            case JsonTokenType.False:
            case JsonTokenType.True:
                return(reader.GetBoolean());

            case JsonTokenType.Number:
                return(reader.GetSingle());

            case JsonTokenType.None:
                return(null);

            case JsonTokenType.String:
                return(reader.GetString());

            case JsonTokenType.Comment:
                reader.Read();
                return(Read(ref reader, typeToConvert, nestedOptions));

            default:
                throw new Exception("Unknown tokentype");
            }
        }
Exemplo n.º 15
0
        private static async Task <BuilderOptions> SetToolOptionsAsync(string path)
        {
            Stopwatch stopWatch = new Stopwatch();

            stopWatch.Start();
            const string tool = "TOOL OPTIONS: ";

            if (File.Exists(path))
            {
                Console.WriteLine($"{tool}File \"{path}\" found.\nSet DotNetBuildTool options from {path} ->");
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.DarkRed;
                Console.WriteLine($"{tool}Cant find \"{path}\" file.\nSorry, command line arguments not Implement yet.");
                Console.ResetColor();
                if (_errorIfToolConfigNotExists)
                {
                    throw new Exception($"{tool}Can't configure build tool.");
                }
            }
            BuilderOptions result = new BuilderOptions();

            await foreach (KeyValuePair <string, string> item in LoadToolConfig(path))
            {
                PropertyInfo?property = typeof(BuilderOptions)
                                        .GetProperties()
                                        .FirstOrDefault(x => x.Name.ToUpper() == item.Key.ToUpper());
                if (property == null)
                {
                    Console.ForegroundColor = ConsoleColor.DarkYellow;
                    Console.WriteLine($"    {tool}Can't find and set: \"{item.Key}\"  -> Done.");
                    Console.ResetColor();
                }
                else
                {
                    bool isParsed = Enum.TryParse(property.PropertyType.Name.ToUpper(), out OptionType optionType);
                    if (!isParsed)
                    {
                        optionType = property.PropertyType.IsEnum ? OptionType.ENUM : OptionType.Unknown;
                    }
                    try
                    {
                        object givenObj = optionType switch
                        {
                            OptionType.BOOLEAN => ParseBool(item.Value),
                            OptionType.STRING => item.Value,
                            OptionType.ENUM => ParseEnum(property.PropertyType, item.Value),
                            _ => throw new ArgumentException($"Unknown type: {property.PropertyType}")
                        };
                        property.SetValue(result, givenObj);
                    }
                    catch (ArgumentException ex)
                    {
                        throw new ArgumentException($"{item.Key} option can't be parsed", ex);
                    }
                    Console.WriteLine($"    {tool}{item.Key} \"{item.Value}\"  -> Done.");
                }
            }
            stopWatch.Stop();
            Console.WriteLine($"{tool}Done. Elapsed time: {((float)stopWatch.ElapsedTicks / (float)Stopwatch.Frequency).ToString("0.0000")}s.");
            return(result);

            bool ParseBool(string str)
            {
                return(str switch
                {
                    "0" => false,
                    "1" => true,
                    _ => throw new ArgumentException($"Can't parse value: {str}")
                });
            }
Exemplo n.º 16
0
 void AssertProp(PropertyInfo?pi, Type type, string name)
 {
     Assert.That(pi, Is.Not.Null);
     Assert.That(pi !.Name, Is.EqualTo(name));
     Assert.That(pi !.PropertyType, Is.EqualTo(type));
 }
Exemplo n.º 17
0
 public CommandParameterSchema(PropertyInfo?property, int order, string name, string?description, Type?converter = null)
     : base(property, description, converter)
 {
     Order = order;
     Name  = name;
 }
Exemplo n.º 18
0
 static ThrottleFilter()
 {
     PrivateAddressProperty = typeof(IPAddress).GetProperty("PrivateAddress", BindingFlags.Instance | BindingFlags.NonPublic);
     NumbersField           = typeof(IPAddress).GetField("_numbers", BindingFlags.Instance | BindingFlags.NonPublic);
 }
Exemplo n.º 19
0
        private static void BindStandardCommands(CustomBasicList <VisualElement> controls, object viewModel, IEnumerable <MethodInfo> methods, IEnumerable <PropertyInfo> properties, IEnumerable <MethodInfo> predicates)
        {
            Type          type = viewModel.GetType();
            VisualElement view = controls.First();
            //i can use classid.  can't do name this time
            //the best i can do is classid.

            CustomBasicList <MethodInfo> specialList = methods.Where(x => x.HasOpenAttribute()).ToCustomBasicList();

            if (specialList.Count > 1)
            {
                throw new BasicBlankException("You had more than one open child attribute.  Rethink");
            }
            MethodInfo?  openRealMethod  = specialList.SingleOrDefault();
            PropertyInfo?openFunProperty = null;

            if (openRealMethod != null)
            {
                openFunProperty = properties.Where(x => x.Name == "CanOpenChild").SingleOrDefault();
                if (openFunProperty == null)
                {
                    throw new BasicBlankException("Did not detect CanOpenChild function in the view model.  Rethink");
                }
            }
            foreach (var method in methods)
            {
                if (method.ReturnType.Name != "Task" && method.ReturnType.Name != "Void")
                {
                    continue; //do more in the loop but can't consider this one because only void and task are supported.
                }
                bool   isOpenChild = method.Equals(openRealMethod);
                string searchName;
                searchName = GetSearchName(method);
                var controlList = controls.Where(x => x.GetName().Equals(searchName, StringComparison.InvariantCultureIgnoreCase) || x.GetName().Equals(method.Name, StringComparison.InvariantCultureIgnoreCase)).ToCustomBasicList();
                foreach (var foundControl in controlList)
                {
                    if (foundControl == null)
                    {
                        continue;
                    }
                    var        foundProperty = properties.FirstOrDefault(x => x.Name == "Can" + searchName);
                    MethodInfo?validateM     = null;
                    ICommand   command;
                    if (foundProperty == null && isOpenChild == false)
                    {
                        validateM = predicates.FirstOrDefault(x => x.Name == "Can" + searchName);
                    }
                    else if (isOpenChild == true && openFunProperty != null)
                    {
                        foundProperty = openFunProperty;
                    }
                    if (foundProperty != null && validateM != null)
                    {
                        throw new BasicBlankException("Cannot have the can for both property and method.  Rethink");
                    }

                    command = GetCommand(viewModel, method, validateM, foundProperty);


                    //if (foundControl is Button button)
                    //{
                    //    button.Command = command;
                    //}
                    //else if (foundControl is GraphicsCommand gg)
                    //{
                    //    gg.Command = command;
                    //}
                    TrySetCommand(foundControl, command);
                }
            }
        }
Exemplo n.º 20
0
        public virtual IEnumerable <IOclElement> ToElements(OclConversionContext context, PropertyInfo?propertyInfo, object obj)
        {
            var element = ConvertInternal(context, propertyInfo, obj);

            return(element != null
                ? new[] { element }
                : Array.Empty <IOclElement>());
        }
Exemplo n.º 21
0
 /// <summary>
 /// Initializes an instance of <see cref="CommandParameterSchema"/>.
 /// </summary>
 public CommandParameterSchema(PropertyInfo?property, int order, string name, string?description)
     : base(property, description)
 {
     Order = order;
     Name  = name;
 }
Exemplo n.º 22
0
 protected abstract IOclElement ConvertInternal(OclConversionContext context, PropertyInfo?propertyInfo, object obj);
Exemplo n.º 23
0
        private void DetermineStaticType(Type previousType)
        {
            PropertyInfo?property = previousType.GetProperty(Identifier, BindingFlags.Public | BindingFlags.Instance);

            Type = property == null ? DataModelPathSegmentType.Invalid : DataModelPathSegmentType.Static;
        }
Exemplo n.º 24
0
 protected virtual string GetName(OclConversionContext context, PropertyInfo?propertyInfo, object obj)
 => propertyInfo != null                                 // If the object is the value of a property, then base the name on the property name
         ? context.Namer.GetName(propertyInfo)
         : context.Namer.FormatName(obj.GetType().Name); // Otherwise base it on the type name
Exemplo n.º 25
0
        public static void ThrowInvalidOperationException_SerializationConverterOnAttributeInvalid(Type classType, PropertyInfo?propertyInfo)
        {
            string location = classType.ToString();

            if (propertyInfo != null)
            {
                location += $".{propertyInfo.Name}";
            }

            throw new InvalidOperationException(SR.Format(SR.SerializationConverterOnAttributeInvalid, location));
        }
Exemplo n.º 26
0
        protected override PropertyInfo?GetPropertyImpl(string name, BindingFlags bindingAttr, Binder?binder, Type?returnType, Type[]?types, ParameterModifier[]?modifiers)
        {
            PropertyInfo?property = base.GetPropertyImpl(name, bindingAttr, binder, returnType, types, modifiers);

            bool getIgnoreCase   = (bindingAttr & BindingFlags.IgnoreCase) == BindingFlags.IgnoreCase;
            bool getDeclaredOnly = (bindingAttr & BindingFlags.DeclaredOnly) == BindingFlags.DeclaredOnly;
            bool getInstance     = (bindingAttr & BindingFlags.Instance) == BindingFlags.Instance;
            bool getPublic       = (bindingAttr & BindingFlags.Public) == BindingFlags.Public;

            // If the ReflectionContext adds a property with identical name and type to an existing property,
            // the behavior is unspecified.
            // In this implementation, we return the existing property.
            if (!getPublic || !getInstance)
            {
                return(property);
            }

            // Adding indexer properties is currently not supported.
            if (types != null && types.Length > 0)
            {
                return(property);
            }

            List <PropertyInfo> matchingProperties = new List <PropertyInfo>();

            if (property != null)
            {
                matchingProperties.Add(property);
            }

            // If the ReflectionContext adds two or more properties with the same name and type,
            // the behavior is unspecified.
            // In this implementation, we throw AmbiguousMatchException even if the two properties are
            // defined on different types (base and sub classes).

            StringComparison comparison = getIgnoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;

            CustomType?type = this;

            foreach (PropertyInfo newDeclaredProperty in type.NewProperties)
            {
                if (string.Equals(newDeclaredProperty.Name, name, comparison))
                {
                    matchingProperties.Add(newDeclaredProperty);
                }
            }

            if (!getDeclaredOnly)
            {
                while ((type = type.BaseType as CustomType) != null)
                {
                    foreach (PropertyInfo newBaseProperty in type.NewProperties)
                    {
                        if (string.Equals(newBaseProperty.Name, name, comparison))
                        {
                            matchingProperties.Add(new InheritedPropertyInfo(newBaseProperty, this));
                        }
                    }
                }
            }

            if (matchingProperties.Count == 0)
            {
                return(null);
            }

            if (binder == null)
            {
                binder = Type.DefaultBinder;
            }

            return(binder.SelectProperty(bindingAttr, matchingProperties.ToArray(), returnType, types, modifiers));
        }
        public static object ToObject(this IDictionary <string, object?> source, Type type, IGraphType?mappedType = null)
        {
            // Given Field(x => x.FName).Name("FirstName") and key == "FirstName" returns "FName"
            string GetPropertyName(string key, out FieldType?field)
            {
                var complexType = mappedType?.GetNamedType() as IComplexGraphType;

                // type may not contain mapping information
                field = complexType?.GetField(key);
                return(field?.GetMetadata(ComplexGraphType <object> .ORIGINAL_EXPRESSION_PROPERTY_NAME, key) ?? key);
            }

            // Returns values (from source or defaults) that match constructor signature + used keys from source
            (List <object>?, List <string>?) GetValuesAndUsedKeys(ParameterInfo[] parameters)
            {
                // parameterless constructors are the most common use case
                if (parameters.Length == 0)
                {
                    return(_emptyValues, null);
                }

                // otherwise we have to iterate over the parameters - worse performance but this is rather rare case
                List <object>?values = null;
                List <string>?keys   = null;

                if (parameters.All(p =>
                {
                    // Source values take precedence
                    if (source.Any(keyValue =>
                    {
                        bool matched = string.Equals(GetPropertyName(keyValue.Key, out var _), p.Name, StringComparison.InvariantCultureIgnoreCase);
                        if (matched)
                        {
                            (values ??= new List <object>()).Add(keyValue.Value);
                            (keys ??= new List <string>()).Add(keyValue.Key);
                        }
                        return(matched);
                    }))
                    {
                        return(true);
                    }

                    // Then check for default values if any
                    if (p.HasDefaultValue)
                    {
                        (values ??= new List <object>()).Add(p.DefaultValue);
                        return(true);
                    }

                    return(false);
                }))
                {
                    return(values, keys);
                }

                return(null, null);
            }

            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            // force sourceType to be IDictionary<string, object>
            if (ValueConverter.TryConvertTo(source, type, out object?result, typeof(IDictionary <string, object>)))
            {
                return(result !);
            }

            // attempt to use the most specific constructor sorting in decreasing order of parameters number
            var ctorCandidates = _types.GetOrAdd(type, t => t.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).OrderByDescending(ctor => ctor.GetParameters().Length).ToArray());

            ConstructorInfo?targetCtor = null;

            ParameterInfo[]? ctorParameters = null;
            List <object>?values   = null;
            List <string>?usedKeys = null;

            foreach (var ctor in ctorCandidates)
            {
                var parameters = ctor.GetParameters();
                (values, usedKeys) = GetValuesAndUsedKeys(parameters);
                if (values != null)
                {
                    targetCtor     = ctor;
                    ctorParameters = parameters;
                    break;
                }
            }

            if (targetCtor == null || ctorParameters == null || values == null)
            {
                throw new ArgumentException($"Type '{type}' does not contain a constructor that could be used for current input arguments.", nameof(type));
            }

            object?[] ctorArguments = ctorParameters.Length == 0 ? Array.Empty <object>() : new object[ctorParameters.Length];

            for (int i = 0; i < ctorParameters.Length; ++i)
            {
                object?arg = GetPropertyValue(values[i], ctorParameters[i].ParameterType);
                ctorArguments[i] = arg;
            }

            object obj;

            try
            {
                obj = targetCtor.Invoke(ctorArguments);
            }
            catch (TargetInvocationException ex)
            {
                ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
                return(""); // never executed, necessary only for intellisense
            }

            foreach (var item in source)
            {
                // these parameters have already been used in the constructor, no need to set property
                if (usedKeys?.Any(k => k == item.Key) == true)
                {
                    continue;
                }

                string       propertyName = GetPropertyName(item.Key, out var field);
                PropertyInfo?propertyInfo = null;

                try
                {
                    propertyInfo = type.GetProperty(propertyName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
                }
                catch (AmbiguousMatchException)
                {
                    propertyInfo = type.GetProperty(propertyName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
                }

                if (propertyInfo != null && propertyInfo.CanWrite)
                {
                    object?value = GetPropertyValue(item.Value, propertyInfo.PropertyType, field?.ResolvedType);
                    propertyInfo.SetValue(obj, value, null); //issue: this works even if propertyInfo is ValueType and value is null
                }
            }

            return(obj);
        }
Exemplo n.º 28
0
            public override SqlInfo[] ConvertToSql(Expression?expression, int level, ConvertFlags flags)
            {
                if (expression == null)
                {
                    if (flags == ConvertFlags.Field && !_key.IsScalar)
                    {
                        return(Element.ConvertToSql(null, 0, flags));
                    }
                    var keys = _key.ConvertToSql(null, 0, flags);
                    for (var i = 0; i < keys.Length; i++)
                    {
                        var key = keys[i];
                        keys[i] = key.AppendMember(_keyProperty !);
                    }

                    return(keys);
                }

                if (level == 0 && expression.NodeType == ExpressionType.MemberAccess)
                {
                    level += 1;
                }
                if (level > 0)
                {
                    switch (expression.NodeType)
                    {
                    case ExpressionType.Call:
                    {
                        var e = (MethodCallExpression)expression;

                        if (e.IsQueryable() || e.IsAggregate(Builder.MappingSchema))
                        {
                            return(new[] { new SqlInfo(ConvertEnumerable(e)) });
                        }

                        break;
                    }

                    case ExpressionType.MemberAccess:
                    {
                        var levelExpression = expression.GetLevelExpression(Builder.MappingSchema, level);

                        if (levelExpression.NodeType == ExpressionType.MemberAccess)
                        {
                            var e = (MemberExpression)levelExpression;

                            if (e.Member.Name == "Key")
                            {
                                if (_keyProperty == null)
                                {
                                    _keyProperty = _groupingType.GetProperty("Key");
                                }

                                if (e.Member == _keyProperty)
                                {
                                    if (ReferenceEquals(levelExpression, expression))
                                    {
                                        return(_key.ConvertToSql(null, 0, flags));
                                    }

                                    return(_key.ConvertToSql(expression, level + 1, flags));
                                }
                            }

                            return(Sequence.ConvertToSql(expression, level, flags));
                        }

                        break;
                    }
                    }
                }

                throw new LinqException("Expression '{0}' cannot be converted to SQL.", expression);
            }
 public void Complete(IEqualityComparerResolver resolver, PropertyInfo?pi)
 {
     ElementComparer = (IEqualityComparer <T>)resolver.GetEqualityComparer(typeof(T), pi);
 }
        internal JsonConverter DetermineConverter(Type?parentClassType, Type runtimePropertyType, PropertyInfo?propertyInfo)
        {
            JsonConverter converter = null !;

            // Priority 1: attempt to get converter from JsonConverterAttribute on property.
            if (propertyInfo != null)
            {
                Debug.Assert(parentClassType != null);

                JsonConverterAttribute?converterAttribute = (JsonConverterAttribute?)
                                                            GetAttributeThatCanHaveMultiple(parentClassType !, typeof(JsonConverterAttribute), propertyInfo);

                if (converterAttribute != null)
                {
                    converter = GetConverterFromAttribute(converterAttribute, typeToConvert: runtimePropertyType, classTypeAttributeIsOn: parentClassType !, propertyInfo);
                }
            }

            if (converter == null)
            {
                converter = GetConverter(runtimePropertyType);
                Debug.Assert(converter != null);
            }

            if (converter is JsonConverterFactory factory)
            {
                converter = factory.GetConverterInternal(runtimePropertyType, this);

                // A factory cannot return null; GetConverterInternal checked for that.
                Debug.Assert(converter != null);
            }

            return(converter);
        }