Beispiel #1
0
 public bool TryGetFromat(ref string name, Type type, out ShaderFieldFormat format)
 {
     if (TargetType.IsAssignableFrom(type))
     {
         format = Format;
         return(true);
     }
     format = ShaderFieldFormat.None;
     return(false);
 }
Beispiel #2
0
        protected override object ConvertValue(object value)
        {
            if (Converter != null)
            {
                value = Converter(value, Parameter, EffectiveCulture);
            }
            if (Format != null)
            {
                value = string.Format(EffectiveCulture, Format, value);
            }

            if (TargetType == null)
            {
                throw new InvalidOperationException("TargetType cannot be null.");
            }
            if (value == null) // TODO ???
            {
                return(null);
            }
            // Check whether value can be assigned to the property
            Type valueType = value.GetType();

            if (TargetType.IsAssignableFrom(valueType))
            {
                return(value);
            }
            // Try converting using Convert class
            if (typeof(IConvertible).IsAssignableFrom(TargetType) && typeof(IConvertible).IsAssignableFrom(valueType))
            {
                return(Convert.ChangeType(value, TargetType, EffectiveCulture));
            }
            // Try converting with value's TypeConverter
            TypeConverter valueConverter = TypeDescriptor.GetConverter(valueType);

            if (valueConverter.CanConvertTo(TargetType))
            {
                return(valueConverter.ConvertTo(ValueConverterContext.Context, EffectiveCulture, value, TargetType));
            }
            // Try converting with target's TypeConverter
            TypeConverter targetConverter = TypeDescriptor.GetConverter(TargetType);

            if (targetConverter.CanConvertFrom(valueType))
            {
                return(targetConverter.ConvertFrom(ValueConverterContext.Context, EffectiveCulture, value));
            }

            throw new InvalidOperationException($"Cannot convert from '{valueType}' to '{TargetType}'.");
        }
Beispiel #3
0
        internal void CheckTargetType(object element)
        {
            // In the most common case TargetType is Default
            // and we can avoid a call to IsAssignableFrom() who's performance is unknown.
            if (DefaultTargetType == TargetType)
            {
                return;
            }

            Type elementType = element.GetType();

            if (!TargetType.IsAssignableFrom(elementType))
            {
                throw new InvalidOperationException(SR.Get(SRID.StyleTargetTypeMismatchWithElement,
                                                           this.TargetType.Name,
                                                           elementType.Name));
            }
        }
Beispiel #4
0
        protected override SelectorMatch Evaluate(IStyleable control, bool subscribe)
        {
            if (TargetType != null)
            {
                var controlType = control.StyleKey ?? control.GetType();

                if (IsConcreteType)
                {
                    if (controlType != TargetType)
                    {
                        return(SelectorMatch.NeverThisType);
                    }
                }
                else
                {
                    if (!TargetType.IsAssignableFrom(controlType))
                    {
                        return(SelectorMatch.NeverThisType);
                    }
                }
            }

            if (Name != null && control.Name != Name)
            {
                return(SelectorMatch.NeverThisInstance);
            }

            if (_classes.IsValueCreated && _classes.Value.Count > 0)
            {
                if (subscribe)
                {
                    var observable = new StyleClassActivator(control.Classes, _classes.Value);

                    return(new SelectorMatch(observable));
                }

                if (!StyleClassActivator.AreClassesMatching(control.Classes, Classes))
                {
                    return(SelectorMatch.NeverThisInstance);
                }
            }

            return(Name == null ? SelectorMatch.AlwaysThisType : SelectorMatch.AlwaysThisInstance);
        }
Beispiel #5
0
        internal void CheckTargetType(object element)
        {
            // Note: we do not do this verification in CSHTML5 in order to remain compatible
            // with old applications created with prior versions of CSHTML5 (eg. Client_FB).
#if OPENSILVER
            if (TargetType == null)
            {
                throw new InvalidOperationException("Must have non-null value for TargetType.");
            }

            Type elementType = element.GetType();
            if (!TargetType.IsAssignableFrom(elementType))
            {
                throw new InvalidOperationException(string.Format("'{0}' TargetType does not match type of element '{1}'.",
                                                                  this.TargetType.Name,
                                                                  elementType.Name));
            }
#endif
        }
Beispiel #6
0
        /// <summary>
        /// This is called when the server is starting.
        /// </summary>
        public void LoadPlugins()
        {
            //Fetch all types that implement the interface IPlugin and are a class
            foreach (var file in Directory.GetFiles(FolderPath))
            {
                if (file.EndsWith(".dll"))
                {
                    Assembly.LoadFile(Path.GetFullPath(file));
                }
            }
            var assemblies  = AppDomain.CurrentDomain.GetAssemblies();
            var implemented = assemblies.SelectMany(a => a.GetTypes()).Where(p => TargetType.IsAssignableFrom(p) && p.IsClass).ToArray();

            for (int i = 0; i < implemented.Length; i++)
            {
                var type     = implemented[i];
                var instance = ((IPlugin)Activator.CreateInstance(type));
                if (instance != null)
                {
                    if (instance.HqVersion != ApiVersion)
                    {
                        //I will still go ahead, but the user should know that errors may appear.
                        Master.UnsafeDirectReference.ConsolePluginWarning($"The plugin \"{instance.Name}\" is built on a different API version (current: {ApiVersion}, target: {instance.HqVersion}). This may induce unwanted behavior and/or errors.");
                        Master.UnsafeDirectReference.LogPlugin(instance.Name, $"Warning: The plugin is targeting version {instance.HqVersion}. Current API version: {ApiVersion}.");
                    }
                    Plugins.Add(new PluginInstance()
                    {
                        Main      = type,
                        MainClass = instance,
                    });
                    Master.UnsafeDirectReference.ConsolePluginStatus($"Loaded \"{instance.Name}\" by \"{instance.Author}\"");
                }
            }
            Stores = new string[Plugins.Count];

            for (int i = 0; i < Plugins.Count; i++)
            {
                var pfs = new PluginFileSystem(Path.Combine("hqplugins", "data"), Plugins[i].MainClass.Name, this);
                Plugins[i].MainClass.Load(Master, pfs);
                Stores[i] = pfs.Store;
            }
            Master.UnsafeDirectReference.ConsolePluginStatus($"Loaded {Plugins.Count} plugins.");
        }
Beispiel #7
0
        internal void CheckTargetType(object element)
        {
#if OPENSILVER // Note: we do not do this verification in CSHTML5 in order to remain compatible with old applications created with prior versions of CSHTML5 (eg. Client_FB).
            // In the most common case TargetType is Default
            // and we can avoid a call to IsAssignableFrom() who's performance is unknown.
            if (DefaultTargetType == TargetType)
            {
                return;
            }

            Type elementType = element.GetType();
            if (!TargetType.IsAssignableFrom(elementType))
            {
                throw new InvalidOperationException(string.Format("'{0}' TargetType does not match type of element '{1}'.",
                                                                  this.TargetType.Name,
                                                                  elementType.Name));
            }
#endif
        }
        /// <inheritdoc />
        public virtual bool BindModel([NotNull] HttpActionContext actionContext, [NotNull] ModelBindingContext bindingContext)
        {
            if (!TargetType.IsAssignableFrom(bindingContext.ModelType))
            {
                throw new TypeInitializationException(bindingContext.ModelType.FullName, new InvalidCastException($"Type {TargetType.FullName} is not assignable from type {bindingContext.ModelType.FullName}."));
            }

            JsonLoadSettings             jsonLoadSettings = JsonHelper.CreateLoadSettings();
            IDictionary <string, string> values           = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            try
            {
                HttpRequestMessage request   = actionContext.Request;
                IHttpRouteData     routeData = actionContext.RequestContext.RouteData;

                /*
                 * Route data
                 * FormData/Body
                 * Query string
                 */
                if (routeData != null)
                {
                    foreach (KeyValuePair <string, object> pair in routeData.Values)
                    {
                        Type type = pair.Value?.GetType();
                        if (type != null && !type.IsPrimitive())
                        {
                            continue;
                        }
                        values[pair.Key] = Convert.ToString(pair.Value);
                    }
                }

                string contentType = request.Content.Headers.ContentType.MediaType.ToLowerInvariant();

                switch (contentType)
                {
                case "application/x-www-form-urlencoded":
                    HandleFormData(request.Content.ReadAsStringAsync().Execute().TrimStart('?'));
                    break;

                case "application/json":
                case "text/json":
                    HandleJson(request.Content.ReadAsStringAsync().Execute().Trim());
                    break;

                case "application/xml":
                case "text/xml":
                    HandleXml(request.Content.ReadAsStringAsync().Execute().Trim());
                    break;
                }

                // Query string
                HandleQuery(request);

                //Initiate primary object
                object obj = Activator.CreateInstance(bindingContext.ModelType);

                //First call for processing primary object
                SetPropertyValues(values, obj);

                //Assign completed object tree to Model
                bindingContext.Model = obj;
                return(true);
            }
            catch (Exception ex)
            {
                bindingContext.ModelState.AddModelError(bindingContext.ModelName, ex.CollectMessages());
                return(false);
            }

            void HandleQuery(HttpRequestMessage request)
            {
                if (string.IsNullOrEmpty(request.RequestUri.Query))
                {
                    return;
                }

                foreach (KeyValuePair <string, string> pair in request.GetQueryNameValuePairs())
                {
                    string data = pair.Value == null ? null : WebUtility.UrlDecode(pair.Value.Trim());

                    if (!string.IsNullOrEmpty(data))
                    {
                        if (data.StartsWith('{') || data.StartsWith('['))
                        {
                            JObject bodyJson = JObject.Parse(data, jsonLoadSettings);
                            AddJsonProperties(values, bodyJson);
                        }
                        else if (data.StartsWith("<?xml", StringComparison.OrdinalIgnoreCase))
                        {
                            XDocument xml = XmlHelper.XParse(data);
                            AddXProperties(values, xml?.Root);
                        }
                        else
                        {
                            values[pair.Key] = data;
                        }
                    }
                    else if (!values.ContainsKey(pair.Key))
                    {
                        values.Add(pair.Key, null);
                    }
                }
            }

            void HandleFormData(string formData)
            {
                if (string.IsNullOrEmpty(formData))
                {
                    return;
                }

                string[] elements = formData.Split('=', '&');

                for (int i = 0; i < elements.Length; i += 2)
                {
                    string key   = elements[i];
                    string value = i < elements.Length - 1
                                                                                ? elements[i + 1]
                                                                                : null;

                    if (!string.IsNullOrEmpty(value))
                    {
                        values[key] = value;
                    }
                    else if (!values.ContainsKey(key))
                    {
                        values.Add(key, null);
                    }
                }
            }

            void HandleJson(string jsonData)
            {
                if (string.IsNullOrEmpty(jsonData))
                {
                    return;
                }
                jsonData = WebUtility.UrlDecode(jsonData);
                JObject bodyJson = JObject.Parse(jsonData, jsonLoadSettings);

                AddJsonProperties(values, bodyJson);
            }

            void HandleXml(string xmlData)
            {
                if (string.IsNullOrEmpty(xmlData))
                {
                    return;
                }
                xmlData = WebUtility.UrlDecode(xmlData);
                XDocument xml = XmlHelper.XParse(xmlData, true);

                AddXProperties(values, xml?.Root);
            }
        }
Beispiel #9
0
 public override bool IsAssignableFrom(IType type)
 {
     return(TargetType.IsAssignableFrom(type));
 }
Beispiel #10
0
 public virtual bool CanSetValue(object value)
 {
     return
         ((TargetType.IsValueType && value != null && TargetType.IsAssignableFrom(value.GetType())) ||
          (!TargetType.IsValueType && (value == null || TargetType.IsAssignableFrom(value.GetType()))));
 }
Beispiel #11
0
        /// <inheritdoc />
        public virtual Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (!TargetType.IsAssignableFrom(bindingContext.ModelType))
            {
                throw new TypeInitializationException(bindingContext.ModelType.FullName, null);
            }

            CancellationToken token = bindingContext.HttpContext.RequestAborted;

            if (token.IsCancellationRequested)
            {
                return(Task.FromCanceled(token));
            }

            Dictionary <string, string> values = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            try
            {
                HttpRequest request     = bindingContext.HttpContext.Request;
                string      contentType = request.ContentType.ToLowerInvariant();

                /*
                 * bindingContext.ValueProvider
                 * Route data
                 * FormData/Body
                 * Query string
                 */
                // Try to fetch the value of the argument by name
                ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

                if (valueProviderResult != ValueProviderResult.None)
                {
                    bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);

                    switch (contentType)
                    {
                    case "application/x-www-form-urlencoded":
                        HandleFromData(valueProviderResult.FirstValue.ToNullIfEmpty());
                        break;

                    case "application/json":
                    case "text/json":
                        HandleJson(valueProviderResult.FirstValue.ToNullIfEmpty());
                        break;

                    case "application/xml":
                    case "text/xml":
                        HandleXml(valueProviderResult.FirstValue.ToNullIfEmpty());
                        break;
                    }
                }

                if (token.IsCancellationRequested)
                {
                    return(Task.FromCanceled(token));
                }

                RouteData routeData = bindingContext.HttpContext.GetRouteData();

                foreach ((string key, object value) in routeData.Values)
                {
                    Type type = value?.GetType();
                    if (type == null || !type.IsPrimitive())
                    {
                        continue;
                    }
                    values[key] = Convert.ToString(value);
                }

                switch (contentType)
                {
                case "application/x-www-form-urlencoded":
                    HandleFromData(ReadRequestBodyLocal(request)?.TrimStart('?'));
                    break;

                case "application/json":
                case "text/json":
                    HandleJson(ReadRequestBodyLocal(request)?.TrimStart('?'));
                    break;

                case "application/xml":
                case "text/xml":
                    HandleXml(ReadRequestBodyLocal(request));
                    break;
                }

                // Query string
                HandleQueryString(request.Query);

                //Initiate primary object
                object obj = Activator.CreateInstance(bindingContext.ModelType) ?? throw new TypeInitializationException(bindingContext.ModelType.FullName, null);

                //First call for processing primary object
                SetPropertyValues(values, obj);

                //Assign completed object tree to Model
                bindingContext.Result = ModelBindingResult.Success(obj);
                return(Task.CompletedTask);
            }
            catch (Exception ex)
            {
                bindingContext.ModelState.AddModelError(bindingContext.ModelName, ex.CollectMessages());
                bindingContext.Result = ModelBindingResult.Failed();
                return(Task.FromException(ex));
            }

            string ReadRequestBodyLocal(HttpRequest request)
            {
                if (token.IsCancellationRequested)
                {
                    return(null);
                }

                if (!request.Body.CanSeek)
                {
                    request.EnableBuffering();
                    request.Body.DrainAsync(token).Wait(token);
                    if (token.IsCancellationRequested)
                    {
                        return(null);
                    }
                    request.Body.Seek(0L, SeekOrigin.Begin);
                }

                using (StreamReader reader = new StreamReader(request.Body))
                {
                    return(reader.ReadToEnd());
                }
            }

            void HandleQueryString(IQueryCollection query)
            {
                if (token.IsCancellationRequested || query == null || query.Count == 0)
                {
                    return;
                }

                foreach ((string key, StringValues value) in query)
                {
                    string data = value.FirstOrDefault();

                    if (!string.IsNullOrEmpty(data))
                    {
                        if (StringExtension.StartsWith(data, "%7B") || StringExtension.StartsWith(data, "%5B"))
                        {
                            HandleJson(data);
                        }
                        else if (StringExtension.StartsWith(data, "%3C%3Fxml"))
                        {
                            HandleXml(data);
                        }
                        else
                        {
                            values[key] = data;
                        }
                    }
                    else if (!values.ContainsKey(key))
                    {
                        values.Add(key, null);
                    }
                }
            }

            void HandleFromData(string formData)
            {
                if (token.IsCancellationRequested || string.IsNullOrEmpty(formData))
                {
                    return;
                }

                string[] elements = formData.Split('=', '&');

                for (int i = 0; i < elements.Length; i += 2)
                {
                    string key   = elements[i];
                    string value = i < elements.Length - 1
                                                                                ? elements[i + 1]
                                                                                : null;

                    if (!string.IsNullOrEmpty(value))
                    {
                        values[key] = value;
                    }
                    else if (!values.ContainsKey(key))
                    {
                        values.Add(key, null);
                    }
                }
            }

            void HandleJson(string jsonData)
            {
                if (token.IsCancellationRequested || string.IsNullOrEmpty(jsonData))
                {
                    return;
                }
                jsonData = WebUtility.UrlDecode(jsonData);
                _serializer.Populate(jsonData, values);
            }

            void HandleXml(string xmlData)
            {
                if (token.IsCancellationRequested || string.IsNullOrEmpty(xmlData))
                {
                    return;
                }
                xmlData = WebUtility.UrlDecode(xmlData);
                XDocument xml = XmlHelper.XParse(xmlData, true);

                AddXProperties(values, xml?.Root);
            }
        }