Esempio n. 1
0
        object ConvertToObject(IDictionary <string, object> dict, Type type)
        {
            if (_typeResolver != null)
            {
                if (dict.Keys.Contains(SerializedTypeNameKey))
                {
                    // already Evaluated
                    type = _typeResolver.ResolveType((string)dict [SerializedTypeNameKey]);
                }
            }

            if (type.IsGenericType)
            {
                if (type.GetGenericTypeDefinition().IsAssignableFrom(typeof(IDictionary <,>)))
                {
                    Type[] arguments = type.GetGenericArguments();
                    if (arguments == null || arguments.Length != 2 || (arguments [0] != typeof(object) && arguments [0] != typeof(string)))
                    {
                        throw new InvalidOperationException(
                                  "Type '" + type + "' is not not supported for serialization/deserialization of a dictionary, keys must be strings or objects.");
                    }
                    if (type.IsAbstract)
                    {
                        Type dictType = typeof(Dictionary <,>);
                        type = dictType.MakeGenericType(arguments [0], arguments [1]);
                    }
                }
            }
            else if (type.IsAssignableFrom(typeof(IDictionary)))
            {
                type = typeof(Dictionary <string, object>);
            }

            object target = Activator.CreateInstance(type, true);

            foreach (KeyValuePair <string, object> entry in dict)
            {
                object value = entry.Value;
                if (target is IDictionary)
                {
                    Type valueType = ReflectionUtils.GetTypedDictionaryValueType(type);
                    if (value != null && valueType == typeof(System.Object))
                    {
                        valueType = value.GetType();
                    }

                    ((IDictionary)target).Add(entry.Key, ConvertToType(value, valueType));
                    continue;
                }
                MemberInfo [] memberCollection = type.GetMember(entry.Key, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
                if (memberCollection == null || memberCollection.Length == 0)
                {
                    //must evaluate value
                    Evaluate(value);
                    continue;
                }

                MemberInfo member = memberCollection [0];

                if (!ReflectionUtils.CanSetMemberValue(member))
                {
                    //must evaluate value
                    Evaluate(value);
                    continue;
                }

                Type memberType = ReflectionUtils.GetMemberUnderlyingType(member);

                if (memberType.IsInterface)
                {
                    if (memberType.IsGenericType)
                    {
                        memberType = ResolveGenericInterfaceToType(memberType);
                    }
                    else
                    {
                        memberType = ResolveInterfaceToType(memberType);
                    }

                    if (memberType == null)
                    {
                        throw new InvalidOperationException("Unable to deserialize a member, as its type is an unknown interface.");
                    }
                }

                ReflectionUtils.SetMemberValue(member, target, ConvertToType(value, memberType));
            }

            return(target);
        }
Esempio n. 2
0
        /// <summary>
        /// Writes the JSON representation of the object.
        /// </summary>
        /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
        /// <param name="value">The value.</param>
        /// <param name="serializer">The calling serializer.</param>
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            string text;

            if (value is DateTime)
            {
                DateTime dateTime = (DateTime)value;

                if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal ||
                    (_dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal)
                {
                    dateTime = dateTime.ToUniversalTime();
                }

                text = dateTime.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture);
            }
#if !NET20
            else if (value is DateTimeOffset)
            {
                DateTimeOffset dateTimeOffset = (DateTimeOffset)value;
                if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal ||
                    (_dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal)
                {
                    dateTimeOffset = dateTimeOffset.ToUniversalTime();
                }

                text = dateTimeOffset.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture);
            }
#endif
            else
            {
                throw new JsonSerializationException("Unexpected value when converting date. Expected DateTime or DateTimeOffset, got {0}.".FormatWith(CultureInfo.InvariantCulture, ReflectionUtils.GetObjectType(value)));
            }

            writer.WriteValue(text);
        }
        public void HandleCommandLineArguments()
        {
            string arg0;

            if (CommandArgs.Length < 1)
            {
                arg0 = "help";
            }
            else
            {
                arg0 = CommandArgs[0].ToLower().TrimStart('-');

                if (CommandArgs[0] == "-") // EXACT MATCH
                {
                    arg0 = "-";
                }
            }

            if (string.IsNullOrEmpty(arg0) || arg0 == "--help" || arg0 == "/?")
            {
                arg0 = "help";
            }

            HtmltoMarkdownProcessor converter;

            switch (arg0)
            {
            case "help":
                ShowHelp();
                break;

            case "version":
                // just display the header
                ConsoleHeader();
                ConsoleFooter();
                break;

            case "uninstall":
                UninstallSettings();

                ConsoleHeader();
                ColorConsole.WriteLine("Markdown Monster Machine Wide Settings uninstalled.", ConsoleColor.Green);
                ConsoleFooter();

                break;

            case "reset":
                // load old config and backup
                mmApp.Configuration.Backup();
                mmApp.Configuration.Reset();     // forces exit

                ConsoleHeader();
                ColorConsole.WriteLine("Markdown Monster Settings reset to defaults.", ConsoleColor.Green);
                ConsoleFooter();

                break;

            case "setportable":
                ConsoleHeader();

                // Note: Startup logic to handle portable startup is in AppConfiguration::FindCommonFolder
                try
                {
                    string portableSettingsFolder = Path.Combine(App.InitialStartDirectory, "PortableSettings");
                    bool   exists          = Directory.Exists(portableSettingsFolder);
                    string oldCommonFolder = mmApp.Configuration.CommonFolder;

                    File.WriteAllText("_IsPortable",
                                      @"forces the settings to be read from .\PortableSettings rather than %appdata%");

                    if (!exists &&
                        Directory.Exists(oldCommonFolder) &&
                        MessageBox.Show(
                            "Portable mode set. Do you want to copy settings from:\r\n\r\n" +
                            oldCommonFolder + "\r\n\r\nto the PortableSettings folder?",
                            "Markdown MonsterPortable Mode",
                            MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                    {
                        FileUtils.CopyDirectory(oldCommonFolder,
                                                portableSettingsFolder, recursive: true);

                        mmApp.Configuration.CommonFolder = portableSettingsFolder;
                        mmApp.Configuration.Read();
                    }


                    mmApp.Configuration.CommonFolder = portableSettingsFolder;
                    mmApp.Configuration.Write();
                }
                catch (Exception ex)
                {
                    ColorConsole.WriteLine("Unable to set portable mode: " + ex.Message, ConsoleColor.Red);
                }

                ConsoleFooter();
                break;

            case "unsetportable":
                ConsoleHeader();
                try
                {
                    File.Delete("_IsPortable");
                    var internalFolder = Path.Combine(
                        Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Markdown Monster");
                    ReflectionUtils.SetProperty(mmApp.Configuration, "InternalCommonFolder", internalFolder);
                    mmApp.Configuration.CommonFolder = internalFolder;
                    mmApp.Configuration.Write();

                    ColorConsole.WriteLine("Removed Portable settings for this installation. Use `mm SetPortable` to reenable.", ConsoleColor.Green);
                }
                catch (Exception ex)
                {
                    ColorConsole.WriteLine($"Unable to delete portable settings switch file\r\n_IsPortable\r\n\r\n{ex.Message}", ConsoleColor.Red);
                }

                break;

            case "register":
                ConsoleHeader();
                if (CommandArgs.Length < 2)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Missing registration code. Please pass a registration code.");
                }
                else
                {
                    if (!UnlockKey.Register(CommandArgs[1]))
                    {
                        ColorConsole.WriteLine("Invalid registration code. Please pass a valid registration code.", ConsoleColor.Red);
                    }
                    else
                    {
                        ColorConsole.WriteLine("Markdown Monster Registration successful.", ConsoleColor.Green);
                        ColorConsole.WriteLine("Thank you for playing fair!", ConsoleColor.Green);
                    }
                }

                ConsoleFooter();
                break;

            case "markdowntohtml":
            {
                int    parmCount  = CommandArgs.Length;
                string inputFile  = parmCount > 1 ? CommandArgs[1] : null;
                string outputFile = parmCount > 2 ? CommandArgs[2] : null;
                string renderMode = parmCount > 3 ? CommandArgs[3] : null;       // html,packagedhtml,zip

                if (outputFile.StartsWith("-"))
                {
                    outputFile = null;
                }
                if (inputFile.StartsWith("-"))
                {
                    inputFile = null;
                }
                if (renderMode.StartsWith("-"))
                {
                    renderMode = null;
                }

                bool openOutputFile =
                    Environment.CommandLine.Contains("-open", StringComparison.OrdinalIgnoreCase) ||
                    string.IsNullOrEmpty(outputFile);

                converter = new HtmltoMarkdownProcessor(this);
                converter.MarkdownToHtml();
                break;
            }

            case "htmltomarkdown":
            {
                converter = new HtmltoMarkdownProcessor(this);

                int    parmCount  = CommandArgs.Length;
                string inputFile  = parmCount > 0 ? CommandArgs[1] : null;
                string outputFile = parmCount > 1 ? CommandArgs[2] : null;
                if (outputFile.StartsWith("-"))
                {
                    outputFile = null;
                }
                if (inputFile.StartsWith("-"))
                {
                    inputFile = null;
                }

                bool openOutputFile =
                    Environment.CommandLine.Contains("-open", StringComparison.OrdinalIgnoreCase) ||
                    string.IsNullOrEmpty(outputFile);

                converter.HtmlToMarkdown();
                break;
            }

            case "markdowntopdf":
            {
                MarkdownToPdfProcessor pdfProcessor = new MarkdownToPdfProcessor(this);
                pdfProcessor.MarkdownToPdf();
                break;
            }
            }
        }
Esempio n. 4
0
 /// <summary>
 /// Returns a collection of all of the attributes, or an empty collection if there are no attributes.
 /// </summary>
 /// <param name="inherit">When true, look up the hierarchy chain for the inherited custom attribute.</param>
 /// <returns>A collection of <see cref="Attribute"/>s, or an empty collection.</returns>
 public IList <Attribute> GetAttributes(bool inherit)
 {
     return(ReflectionUtils.GetAttributes(_attributeProvider, null, inherit));
 }
Esempio n. 5
0
        /// <summary>
        /// Deserialize an object
        /// </summary>
        /// <param name="value">The object to deserialize</param>
        /// <param name="type">The type of object to deserialize</param>
        /// <param name="dateTimeStyles">The <see cref="DateTimeStyles"/> ton convert <see cref="DateTime"/> objects</param>
        /// <returns>A instance of <paramref name="type" /> deserialized from <paramref name="value"/></returns>
        public override object DeserializeObject(object value, Type type, DateTimeStyles dateTimeStyles)
        {
            var typeInfo = type.GetTypeInfo();

            if (typeInfo.IsEnum || (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type).GetTypeInfo().IsEnum))
            {
                var typeToParse = ReflectionUtils.IsNullableType(type)
                    ? Nullable.GetUnderlyingType(type)
                    : type;

                return(value == null
                    ? null
                    : Enum.Parse(typeToParse, value.ToString(), true));
            }

            var primitiveConverter = this.FindPrimitiveConverter(type);

            if (primitiveConverter != null)
            {
                return(primitiveConverter.Deserialize(value, type));
            }

            var valueDictionary = value as IDictionary <string, object>;

            if (valueDictionary == null)
            {
                return(base.DeserializeObject(value, type, dateTimeStyles));
            }

            var javascriptConverter = this.FindJavaScriptConverter(type);

            if (javascriptConverter != null)
            {
                return(javascriptConverter.Deserialize(valueDictionary, type));
            }

            if (!typeInfo.IsGenericType)
            {
                return(base.DeserializeObject(value, type, dateTimeStyles));
            }

            var genericType          = typeInfo.GetGenericTypeDefinition();
            var genericTypeConverter = this.FindJavaScriptConverter(genericType);

            if (genericTypeConverter == null)
            {
                return(base.DeserializeObject(value, type, dateTimeStyles));
            }

            var values           = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase);
            var genericArguments = type.GetGenericArguments();

            for (var i = 0; i < genericArguments.Length; i++)
            {
                var deserializedObject = this.DeserializeObject(valueDictionary.Values.ElementAt(i),
                                                                genericArguments[i], dateTimeStyles);

                values.Add(valueDictionary.Keys.ElementAt(i), deserializedObject);
            }

            return(genericTypeConverter.Deserialize(values, type));
        }
Esempio n. 6
0
        public void TestGetAllInstancePropertyInfosEmpty()
        {
            var properties = ReflectionUtils.GetTypeProperties(typeof(int));

            Assert.Empty(properties);
        }
Esempio n. 7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="JsonArrayContract"/> class.
        /// </summary>
        /// <param name="underlyingType">The underlying type for the contract.</param>
        public JsonArrayContract(Type underlyingType)
            : base(underlyingType)
        {
            ContractType = JsonContractType.Array;
            IsArray      = CreatedType.IsArray;

            bool canDeserialize;

            Type tempCollectionType;

            if (IsArray)
            {
                CollectionItemType               = ReflectionUtils.GetCollectionItemType(UnderlyingType);
                IsReadOnlyOrFixedSize            = true;
                _genericCollectionDefinitionType = typeof(List <>).MakeGenericType(CollectionItemType);

                canDeserialize          = true;
                IsMultidimensionalArray = (IsArray && UnderlyingType.GetArrayRank() > 1);
            }
            else if (typeof(IList).IsAssignableFrom(underlyingType))
            {
                if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(ICollection <>), out _genericCollectionDefinitionType))
                {
                    CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0];
                }
                else
                {
                    CollectionItemType = ReflectionUtils.GetCollectionItemType(underlyingType);
                }

                if (underlyingType == typeof(IList))
                {
                    CreatedType = typeof(List <object>);
                }

                if (CollectionItemType != null)
                {
                    _parametrizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType);
                }

                IsReadOnlyOrFixedSize = ReflectionUtils.InheritsGenericDefinition(underlyingType, typeof(ReadOnlyCollection <>));
                canDeserialize        = true;
            }
            else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(ICollection <>), out _genericCollectionDefinitionType))
            {
                CollectionItemType = _genericCollectionDefinitionType.GetGenericArguments()[0];

                if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(ICollection <>)) ||
                    ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IList <>)))
                {
                    CreatedType = typeof(List <>).MakeGenericType(CollectionItemType);
                }

#if !(NET20 || NET35 || PORTABLE40)
                if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(ISet <>)))
                {
                    CreatedType = typeof(HashSet <>).MakeGenericType(CollectionItemType);
                }
#endif

                _parametrizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType);
                canDeserialize           = true;
                ShouldCreateWrapper      = true;
            }
#if !(NET40 || NET35 || NET20 || PORTABLE40)
            else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IReadOnlyCollection <>), out tempCollectionType))
            {
                CollectionItemType = tempCollectionType.GetGenericArguments()[0];

                if (ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IReadOnlyCollection <>)) ||
                    ReflectionUtils.IsGenericDefinition(underlyingType, typeof(IReadOnlyList <>)))
                {
                    CreatedType = typeof(ReadOnlyCollection <>).MakeGenericType(CollectionItemType);
                }

                _genericCollectionDefinitionType = typeof(List <>).MakeGenericType(CollectionItemType);
                _parametrizedConstructor         = CollectionUtils.ResolveEnumerableCollectionConstructor(CreatedType, CollectionItemType);
                IsReadOnlyOrFixedSize            = true;
                canDeserialize = HasParametrizedCreator;
            }
#endif
            else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IEnumerable <>), out tempCollectionType))
            {
                CollectionItemType = tempCollectionType.GetGenericArguments()[0];

                if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IEnumerable <>)))
                {
                    CreatedType = typeof(List <>).MakeGenericType(CollectionItemType);
                }

                _parametrizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(underlyingType, CollectionItemType);

#if !(NET35 || NET20 || NETFX_CORE)
                if (!HasParametrizedCreator && underlyingType.Name == FSharpUtils.FSharpListTypeName)
                {
                    FSharpUtils.EnsureInitialized(underlyingType.Assembly());
                    _parametrizedCreator = FSharpUtils.CreateSeq(CollectionItemType);
                }
#endif

                if (underlyingType.IsGenericType() && underlyingType.GetGenericTypeDefinition() == typeof(IEnumerable <>))
                {
                    _genericCollectionDefinitionType = tempCollectionType;

                    IsReadOnlyOrFixedSize = false;
                    ShouldCreateWrapper   = false;
                    canDeserialize        = true;
                }
                else
                {
                    _genericCollectionDefinitionType = typeof(List <>).MakeGenericType(CollectionItemType);

                    IsReadOnlyOrFixedSize = true;
                    ShouldCreateWrapper   = true;
                    canDeserialize        = HasParametrizedCreator;
                }
            }
            else
            {
                // types that implement IEnumerable and nothing else
                canDeserialize      = false;
                ShouldCreateWrapper = true;
            }

            CanDeserialize = canDeserialize;

#if (NET20 || NET35)
            if (CollectionItemType != null && ReflectionUtils.IsNullableType(CollectionItemType))
            {
                // bug in .NET 2.0 & 3.5 that List<Nullable<T>> throws an error when adding null via IList.Add(object)
                // wrapper will handle calling Add(T) instead
                if (ReflectionUtils.InheritsGenericDefinition(CreatedType, typeof(List <>), out tempCollectionType) ||
                    (IsArray && !IsMultidimensionalArray))
                {
                    ShouldCreateWrapper = true;
                }
            }
#endif

#if !(NET20 || NET35 || NET40 || PORTABLE40)
            Type immutableCreatedType;
            ObjectConstructor <object> immutableParameterizedCreator;
            if (ImmutableCollectionsUtils.TryBuildImmutableForArrayContract(underlyingType, CollectionItemType, out immutableCreatedType, out immutableParameterizedCreator))
            {
                CreatedType           = immutableCreatedType;
                _parametrizedCreator  = immutableParameterizedCreator;
                IsReadOnlyOrFixedSize = true;
                CanDeserialize        = true;
            }
#endif
        }
Esempio n. 8
0
        private JsonSchema GenerateInternal(Type type, Required valueRequired, bool required)
        {
            ValidationUtils.ArgumentNotNull((object)type, "type");
            string typeId1 = this.GetTypeId(type, false);
            string typeId2 = this.GetTypeId(type, true);

            if (!string.IsNullOrEmpty(typeId1))
            {
                JsonSchema schema = this._resolver.GetSchema(typeId1);
                if (schema != null)
                {
                    if (valueRequired != Required.Always && !JsonSchemaGenerator.HasFlag(schema.Type, JsonSchemaType.Null))
                    {
                        JsonSchema     jsonSchema = schema;
                        JsonSchemaType?type1      = jsonSchema.Type;
                        JsonSchemaType?nullable   = type1.HasValue ? new JsonSchemaType?(type1.GetValueOrDefault() | JsonSchemaType.Null) : new JsonSchemaType?();
                        jsonSchema.Type = nullable;
                    }
                    if (required)
                    {
                        bool?required1 = schema.Required;
                        if ((!required1.GetValueOrDefault() ? 1 : (!required1.HasValue ? 1 : 0)) != 0)
                        {
                            schema.Required = new bool?(true);
                        }
                    }
                    return(schema);
                }
            }
            if (Enumerable.Any <JsonSchemaGenerator.TypeSchema>((IEnumerable <JsonSchemaGenerator.TypeSchema>) this._stack, (Func <JsonSchemaGenerator.TypeSchema, bool>)(tc => tc.Type == type)))
            {
                throw new JsonException(StringUtils.FormatWith("Unresolved circular reference for type '{0}'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.", (IFormatProvider)CultureInfo.InvariantCulture, (object)type));
            }
            JsonContract  jsonContract = this.ContractResolver.ResolveContract(type);
            JsonConverter jsonConverter;

            if ((jsonConverter = jsonContract.Converter) != null || (jsonConverter = jsonContract.InternalConverter) != null)
            {
                JsonSchema schema = jsonConverter.GetSchema();
                if (schema != null)
                {
                    return(schema);
                }
            }
            this.Push(new JsonSchemaGenerator.TypeSchema(type, new JsonSchema()));
            if (typeId2 != null)
            {
                this.CurrentSchema.Id = typeId2;
            }
            if (required)
            {
                this.CurrentSchema.Required = new bool?(true);
            }
            this.CurrentSchema.Title       = this.GetTitle(type);
            this.CurrentSchema.Description = this.GetDescription(type);
            if (jsonConverter != null)
            {
                this.CurrentSchema.Type = new JsonSchemaType?(JsonSchemaType.Any);
            }
            else
            {
                switch (jsonContract.ContractType)
                {
                case JsonContractType.Object:
                    this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Object, valueRequired));
                    this.CurrentSchema.Id   = this.GetTypeId(type, false);
                    this.GenerateObjectSchema(type, (JsonObjectContract)jsonContract);
                    break;

                case JsonContractType.Array:
                    this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Array, valueRequired));
                    this.CurrentSchema.Id   = this.GetTypeId(type, false);
                    JsonArrayAttribute jsonArrayAttribute = JsonTypeReflector.GetJsonContainerAttribute(type) as JsonArrayAttribute;
                    bool flag = jsonArrayAttribute == null || jsonArrayAttribute.AllowNullItems;
                    Type collectionItemType = ReflectionUtils.GetCollectionItemType(type);
                    if (collectionItemType != null)
                    {
                        this.CurrentSchema.Items = (IList <JsonSchema>) new List <JsonSchema>();
                        this.CurrentSchema.Items.Add(this.GenerateInternal(collectionItemType, !flag ? Required.Always : Required.Default, false));
                        break;
                    }
                    else
                    {
                        break;
                    }

                case JsonContractType.Primitive:
                    this.CurrentSchema.Type = new JsonSchemaType?(this.GetJsonSchemaType(type, valueRequired));
                    JsonSchemaType?type2 = this.CurrentSchema.Type;
                    if ((type2.GetValueOrDefault() != JsonSchemaType.Integer ? 0 : (type2.HasValue ? 1 : 0)) != 0 && TypeExtensions.IsEnum(type) && !type.IsDefined(typeof(FlagsAttribute), true))
                    {
                        this.CurrentSchema.Enum    = (IList <JToken>) new List <JToken>();
                        this.CurrentSchema.Options = (IDictionary <JToken, string>) new Dictionary <JToken, string>();
                        using (IEnumerator <EnumValue <long> > enumerator = EnumUtils.GetNamesAndValues <long>(type).GetEnumerator())
                        {
                            while (enumerator.MoveNext())
                            {
                                EnumValue <long> current = enumerator.Current;
                                JToken           key     = JToken.FromObject((object)current.Value);
                                this.CurrentSchema.Enum.Add(key);
                                this.CurrentSchema.Options.Add(key, current.Name);
                            }
                            break;
                        }
                    }
                    else
                    {
                        break;
                    }

                case JsonContractType.String:
                    this.CurrentSchema.Type = new JsonSchemaType?(!ReflectionUtils.IsNullable(jsonContract.UnderlyingType) ? JsonSchemaType.String : this.AddNullType(JsonSchemaType.String, valueRequired));
                    break;

                case JsonContractType.Dictionary:
                    this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Object, valueRequired));
                    Type keyType;
                    Type valueType;
                    ReflectionUtils.GetDictionaryKeyValueTypes(type, out keyType, out valueType);
                    if (keyType != null && ConvertUtils.IsConvertible(keyType))
                    {
                        this.CurrentSchema.AdditionalProperties = this.GenerateInternal(valueType, Required.Default, false);
                        break;
                    }
                    else
                    {
                        break;
                    }

                case JsonContractType.Serializable:
                    this.CurrentSchema.Type = new JsonSchemaType?(this.AddNullType(JsonSchemaType.Object, valueRequired));
                    this.CurrentSchema.Id   = this.GetTypeId(type, false);
                    this.GenerateISerializableContract(type, (JsonISerializableContract)jsonContract);
                    break;

                case JsonContractType.Linq:
                    this.CurrentSchema.Type = new JsonSchemaType?(JsonSchemaType.Any);
                    break;

                default:
                    throw new JsonException(StringUtils.FormatWith("Unexpected contract type: {0}", (IFormatProvider)CultureInfo.InvariantCulture, (object)jsonContract));
                }
            }
            return(this.Pop().Schema);
        }
Esempio n. 9
0
        //        /// <summary>
        //        /// Sets the flag that determines whether line numbers are shown
        //        /// </summary>
        //        /// <param name="showLineNumbers"></param>
        //        public void SetShowLineNumbers(bool showLineNumbers)
        //        {
        //            Invoke("setShowLineNumbers", showLineNumbers);
        //        }


        #region UndoManager

        /// <summary>
        /// Returns the JavaScript UndoManager
        /// </summary>
        /// <returns></returns>
        public object GetUndoManager()
        {
            var session = ReflectionUtils.GetPropertyExCom(Instance, "editor.session");

            return(ReflectionUtils.CallMethodCom(session, "getUndoManager", false));
        }
        public static string ToSourceCode(object value)
        {
            switch (value)
            {
            case null:
                return("null");

            case bool b:
                return(b.ToLowerCase());

            case string text:
                return($"$@\"{text.Replace("\"", "\"\"").Replace("{", "{{").Replace("}", "}}")}\"");

            case char c:
                return(c == '\\' ? "'\\\\'" : $"'{value}'");

            case float f:
                return(ToSourceCode(f));

            case double d:
                return(ToSourceCode(d));

            case decimal f:
                return(f.ToString("G", CultureInfo.InvariantCulture) + "m");

            case BigInteger bigInteger:
                return($"System.Numerics.BigInteger.Parse(\"{bigInteger.ToString(CultureInfo.InvariantCulture)}\", System.Globalization.CultureInfo.InvariantCulture)");

            case DateTime dateTime:
                return($"System.DateTime.Parse(\"{dateTime.ToString(CultureInfo.InvariantCulture)}\", System.Globalization.CultureInfo.InvariantCulture)");

            case Guid guid:
                return($"System.Guid.Parse(\"{guid.ToString()}\")");
            }
            if (ReflectionUtils.GetTypeInfo(value.GetType()).IsEnum)
            {
                return($"({value.GetType().GetCorrectCSharpTypeName()})({ToInvariantCultureString(value)})");
            }
            if (value is Type type)
            {
                return("typeof(" + type.GetCorrectCSharpTypeName() + ")");
            }
            if (!ReflectionUtils.GetTypeInfo(value.GetType()).IsValueType)
            {
                return("System.Activator.CreateInstance<" + value.GetType().GetCorrectCSharpTypeName() + ">()");
            }

            switch (value)
            {
            case TimeInterval interval:
                return("new BenchmarkDotNet.Horology.TimeInterval(" + ToSourceCode(interval.Nanoseconds) + ")");

            case IntPtr ptr:
                return($"new System.IntPtr({ptr})");

            case IFormattable formattable:
                return(formattable.ToString(null, CultureInfo.InvariantCulture));
            }

            return(value.ToString());
        }
Esempio n. 11
0
        private static Version GetFrameworkVersion(IAssemblyInfo assembly)
        {
            AssemblyName frameworkAssemblyName = ReflectionUtils.FindAssemblyReference(assembly, MbUnitFrameworkAssemblyDisplayName);

            return(frameworkAssemblyName != null ? frameworkAssemblyName.Version : null);
        }
Esempio n. 12
0
        public override bool Write(AppConfiguration config)
        {
            lock (syncWriteLock)
            {
                // Load the config file into DOM parser
                XmlDocument Dom = new XmlDocument();

                string configFile = ConfigurationFile;
                if (string.IsNullOrEmpty(configFile))
                {
                    configFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
                }

                try
                {
                    Dom.Load(configFile);
                }
                catch
                {
                    // Can't load the file - create an empty document
                    string Xml =
                        @"<?xml version='1.0'?>
		<configuration>
		</configuration>"        ;

                    Dom.LoadXml(Xml);
                }

                // Load up the Namespaces object so we can
                // reference the appropriate default namespace
                GetXmlNamespaceInfo(Dom);

                // Parse through each of hte properties of the properties
                Type         typeWebConfig = config.GetType();
                MemberInfo[] Fields        = typeWebConfig.GetMembers(BindingFlags.Instance | BindingFlags.GetField | BindingFlags.GetProperty | BindingFlags.Public);

                string fieldsToEncrypt = "," + PropertiesToEncrypt.ToLower() + ",";

                string ConfigSection = "appSettings";
                if (!string.IsNullOrEmpty(ConfigurationSection))
                {
                    ConfigSection = ConfigurationSection;
                }

                ConfigurationManager.RefreshSection(ConfigSection);

                foreach (MemberInfo Field in Fields)
                {
                    // If we can't find the key - write it out to the document
                    string Value    = null;
                    object RawValue = null;
                    if (Field.MemberType == MemberTypes.Field)
                    {
                        RawValue = ((FieldInfo)Field).GetValue(config);
                    }
                    else if (Field.MemberType == MemberTypes.Property)
                    {
                        RawValue = ((PropertyInfo)Field).GetValue(config, null);
                    }
                    else
                    {
                        continue; // not a property or field
                    }
                    // Don't persist ErrorMessage property
                    if (Field.Name == "ErrorMessage" || Field.Name == "Provider")
                    {
                        continue;
                    }

                    Value = ReflectionUtils.TypedValueToString(RawValue, CultureInfo.InvariantCulture);

                    // Encrypt the field if in list
                    if (fieldsToEncrypt.IndexOf("," + Field.Name.ToLower() + ",") > -1)
                    {
                        Value = Encryption.EncryptString(Value, EncryptionKey);
                    }

                    XmlNode Node = Dom.DocumentElement.SelectSingleNode(
                        XmlNamespacePrefix + ConfigSection + "/" +
                        XmlNamespacePrefix + "add[@key='" + Field.Name + "']", XmlNamespaces);

                    if (Node == null)
                    {
                        // Create the node and attributes and write it
                        Node = Dom.CreateNode(XmlNodeType.Element, "add", Dom.DocumentElement.NamespaceURI);

                        XmlAttribute Attr2 = Dom.CreateAttribute("key");
                        Attr2.Value = Field.Name;
                        XmlAttribute Attr = Dom.CreateAttribute("value");
                        Attr.Value = Value;

                        Node.Attributes.Append(Attr2);
                        Node.Attributes.Append(Attr);

                        XmlNode Parent = Dom.DocumentElement.SelectSingleNode(
                            XmlNamespacePrefix + ConfigSection, XmlNamespaces);

                        if (Parent == null)
                        {
                            Parent = CreateConfigSection(Dom, ConfigSection);
                        }

                        Parent.AppendChild(Node);
                    }
                    else
                    {
                        // just write the value into the attribute
                        Node.Attributes.GetNamedItem("value").Value = Value;
                    }


                    string XML = Node.OuterXml;
                } // for each


                try
                {
                    // this will fail if permissions are not there
                    Dom.Save(configFile);

                    ConfigurationManager.RefreshSection(ConfigSection);
                }
                catch
                {
                    return(false);
                }
            }
            return(true);
        }
Esempio n. 13
0
        /// <summary>
        /// Reads Configuration settings from an external file or explicitly from a file.
        /// Uses XML DOM to read values instead of using the native APIs.
        /// </summary>
        /// <typeparam name="TAppConfiguration"></typeparam>
        /// <param name="config">Configuration instance</param>
        /// <param name="filename">Filename to read from</param>
        /// <returns></returns>
        public override bool Read(AppConfiguration config, string filename)
        {
            Type typeWebConfig = config.GetType();

            MemberInfo[] Fields = typeWebConfig.GetMembers(BindingFlags.Public |
                                                           BindingFlags.Instance);

            // Set a flag for missing fields
            // If we have any we'll need to write them out
            bool missingFields = false;

            XmlDocument Dom = new XmlDocument();

            try
            {
                Dom.Load(filename);
            }
            catch
            {
                // Can't open or doesn't exist - so try to create it
                if (!Write(config))
                {
                    return(false);
                }

                // Now load again
                Dom.Load(filename);
            }

            // Retrieve XML Namespace information to assign default
            // Namespace explicitly.
            GetXmlNamespaceInfo(Dom);


            string ConfigSection = ConfigurationSection;

            if (ConfigSection == string.Empty)
            {
                ConfigSection = "appSettings";
            }

            string fieldsToEncrypt = "," + PropertiesToEncrypt.ToLower() + ",";

            foreach (MemberInfo Member in Fields)
            {
                FieldInfo    Field     = null;
                PropertyInfo Property  = null;
                Type         FieldType = null;
                string       TypeName  = null;

                if (Member.MemberType == MemberTypes.Field)
                {
                    Field     = (FieldInfo)Member;
                    FieldType = Field.FieldType;
                    TypeName  = Field.FieldType.Name.ToLower();
                }
                else if (Member.MemberType == MemberTypes.Property)
                {
                    Property  = (PropertyInfo)Member;
                    FieldType = Property.PropertyType;
                    TypeName  = Property.PropertyType.Name.ToLower();
                }
                else
                {
                    continue;
                }

                string Fieldname = Member.Name;
                if (Fieldname == "Provider" || Fieldname == "ErrorMessage")
                {
                    continue;
                }

                XmlNode Section = Dom.DocumentElement.SelectSingleNode(XmlNamespacePrefix + ConfigSection, XmlNamespaces);
                if (Section == null)
                {
                    Section = CreateConfigSection(Dom, ConfigurationSection);
                    Dom.DocumentElement.AppendChild(Section);
                }

                string Value = GetNamedValueFromXml(Dom, Fieldname, ConfigSection);
                if (Value == null)
                {
                    missingFields = true;
                    continue;
                }

                Fieldname = Fieldname.ToLower();

                // If we're encrypting decrypt any field that are encyrpted
                if (Value != string.Empty && fieldsToEncrypt.IndexOf("," + Fieldname + ",") > -1)
                {
                    Value = Encryption.DecryptString(Value, EncryptionKey);
                }

                // Assign the Property
                ReflectionUtils.SetPropertyEx(config, Fieldname,
                                              ReflectionUtils.StringToTypedValue(Value, FieldType, CultureInfo.InvariantCulture));
            }

            // We have to write any missing keys
            if (missingFields)
            {
                Write(config);
            }

            return(true);
        }
Esempio n. 14
0
        /// <summary>
        /// Reads configuration settings from the current configuration manager.
        /// Uses the internal APIs to write these values.
        /// </summary>
        /// <typeparam name="TAppConfiguration"></typeparam>
        /// <param name="config"></param>
        /// <returns></returns>
        public override bool Read(AppConfiguration config)
        {
            // Config reading from external files works a bit differently
            // so use a separate method to handle it
            if (!string.IsNullOrEmpty(ConfigurationFile))
            {
                return(Read(config, ConfigurationFile));
            }

            Type typeWebConfig = config.GetType();

            MemberInfo[] Fields = typeWebConfig.GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.GetField);

            // Set a flag for missing fields
            // If we have any we'll need to write them out into .config
            bool missingFields = false;

            string fieldsToEncrypt = "," + PropertiesToEncrypt.ToLower() + ",";


            // Refresh the sections - req'd after write operations
            // sometimes sections don't want to re-read
            if (string.IsNullOrEmpty(ConfigurationSection))
            {
                ConfigurationManager.RefreshSection("appSettings");
            }
            else
            {
                ConfigurationManager.RefreshSection(ConfigurationSection);
            }


            // Loop through all fields and properties
            foreach (MemberInfo Member in Fields)
            {
                string typeName = null;

                FieldInfo    field     = null;
                PropertyInfo property  = null;
                Type         fieldType = null;

                if (Member.MemberType == MemberTypes.Field)
                {
                    field     = (FieldInfo)Member;
                    fieldType = field.FieldType;
                    typeName  = fieldType.Name.ToLower();
                }
                else if (Member.MemberType == MemberTypes.Property)
                {
                    property  = (PropertyInfo)Member;
                    fieldType = property.PropertyType;
                    typeName  = fieldType.Name.ToLower();
                }
                else
                {
                    continue;
                }

                string fieldName = Member.Name.ToLower();

                // Error Message is an internal public property
                if (fieldName == "errormessage" || fieldName == "provider")
                {
                    continue;
                }

                string value = null;
                if (string.IsNullOrEmpty(ConfigurationSection))
                {
                    value = ConfigurationManager.AppSettings[fieldName];
                }
                else
                {
                    NameValueCollection Values =
                        ConfigurationManager.GetSection(ConfigurationSection) as NameValueCollection;
                    if (Values != null)
                    {
                        value = Values[fieldName];
                    }
                }

                if (value == null)
                {
                    missingFields = true;
                    continue;
                }

                // If we're encrypting decrypt any field that are encyrpted
                if (value != string.Empty && fieldsToEncrypt.IndexOf("," + fieldName + ",") > -1)
                {
                    value = Encryption.DecryptString(value, EncryptionKey);
                }

                try
                {
                    // Assign the value to the property
                    ReflectionUtils.SetPropertyEx(config, fieldName,
                                                  ReflectionUtils.StringToTypedValue(value, fieldType, CultureInfo.InvariantCulture));
                }
                catch {; }
            }

            // We have to write any missing keys
            if (missingFields)
            {
                Write(config);
            }

            return(true);
        }
Esempio n. 15
0
        /// <summary>
        /// Scans specified type for occurences of <see cref="QuerySqlFieldAttribute" />.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="fields">The fields.</param>
        /// <param name="indexes">The indexes.</param>
        /// <param name="parentPropName">Name of the parent property.</param>
        /// <param name="visitedTypes">The visited types.</param>
        /// <param name="isKey">Whether this is a key type.</param>
        /// <exception cref="System.InvalidOperationException">Recursive Query Field definition detected:  + type</exception>
        private static void ScanAttributes(Type type, List <QueryField> fields, List <QueryIndexEx> indexes,
                                           string parentPropName, ISet <Type> visitedTypes, bool isKey)
        {
            Debug.Assert(type != null);
            Debug.Assert(fields != null);
            Debug.Assert(indexes != null);

            if (visitedTypes.Contains(type))
            {
                throw new InvalidOperationException("Recursive Query Field definition detected: " + type);
            }

            visitedTypes.Add(type);

            foreach (var memberInfo in ReflectionUtils.GetFieldsAndProperties(type))
            {
                var customAttributes = memberInfo.Key.GetCustomAttributes(true);

                foreach (var attr in customAttributes.OfType <QuerySqlFieldAttribute>())
                {
                    var columnName = attr.Name ?? memberInfo.Key.Name;

                    // Dot notation is required for nested SQL fields.
                    if (parentPropName != null)
                    {
                        columnName = parentPropName + "." + columnName;
                    }

                    if (attr.IsIndexed)
                    {
                        indexes.Add(new QueryIndexEx(columnName, attr.IsDescending, QueryIndexType.Sorted,
                                                     attr.IndexGroups)
                        {
                            InlineSize = attr.IndexInlineSize,
                        });
                    }

                    fields.Add(new QueryField(columnName, memberInfo.Value)
                    {
                        IsKeyField   = isKey,
                        NotNull      = attr.NotNull,
                        DefaultValue = attr.DefaultValue,
                        Precision    = attr.Precision,
                        Scale        = attr.Scale
                    });

                    ScanAttributes(memberInfo.Value, fields, indexes, columnName, visitedTypes, isKey);
                }

                foreach (var attr in customAttributes.OfType <QueryTextFieldAttribute>())
                {
                    var columnName = attr.Name ?? memberInfo.Key.Name;

                    if (parentPropName != null)
                    {
                        columnName = parentPropName + "." + columnName;
                    }

                    indexes.Add(new QueryIndexEx(columnName, false, QueryIndexType.FullText, null));

                    fields.Add(new QueryField(columnName, memberInfo.Value)
                    {
                        IsKeyField = isKey
                    });

                    ScanAttributes(memberInfo.Value, fields, indexes, columnName, visitedTypes, isKey);
                }
            }

            visitedTypes.Remove(type);
        }
Esempio n. 16
0
 public void Redo()
 {
     ReflectionUtils.CallMethodExCom(Instance, "editor.redo", false);
 }
Esempio n. 17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DbMetadata"/> class.
        /// </summary>
        /// <param name="productName">Name of the product.</param>
        /// <param name="assemblyName">Name of the assembly.</param>
        /// <param name="connectionType">Type of the connection.</param>
        /// <param name="commandType">Type of the command.</param>
        /// <param name="parameterType">Type of the parameter.</param>
        /// <param name="dataAdapterType">Type of the data adapter.</param>
        /// <param name="commandBuilderType">Type of the command builder.</param>
        /// <param name="commandBuilderDeriveParametersMethod">The command builder derive parameters method.</param>
        /// <param name="parameterDbType">Type of the parameter db.</param>
        /// <param name="parameterDbTypeProperty">The parameter db type property.</param>
        /// <param name="parameterIsNullableProperty">The parameter is nullable property.</param>
        /// <param name="parameterNamePrefix">The parameter name prefix.</param>
        /// <param name="exceptionType">Type of the exception.</param>
        /// <param name="useParameterNamePrefixInParameterCollection">if set to <c>true</c> [use parameter name prefix in parameter collection].</param>
        /// <param name="useParameterPrefixInSql">if set to <c>true</c> [use parameter prefix in SQL].</param>
        /// <param name="bindByName">if set to <c>true</c> [bind by name].</param>
        /// <param name="errorCodeExceptionExpression">The error code exception expression.</param>
        public DbMetadata(string productName,
                          string assemblyName,
                          Type connectionType,
                          Type commandType,
                          Type parameterType,
                          Type dataAdapterType,
                          Type commandBuilderType,
                          string commandBuilderDeriveParametersMethod,
                          Type parameterDbType,
                          string parameterDbTypeProperty,
                          string parameterIsNullableProperty,
                          string parameterNamePrefix,
                          Type exceptionType,
                          bool useParameterNamePrefixInParameterCollection,
                          bool useParameterPrefixInSql,
                          bool bindByName,
                          string errorCodeExceptionExpression

                          )
        {
            AssertUtils.ArgumentHasText(productName, "ProductName");
            this.productName = productName;
            AssertUtils.ArgumentHasText(assemblyName, "assemblyName", GetErrorMessage());
            AssertUtils.ArgumentNotNull(connectionType, "connectionType", GetErrorMessage());
            AssertUtils.ArgumentNotNull(commandType, "commandType", GetErrorMessage());
            AssertUtils.ArgumentNotNull(parameterType, "parameterType", GetErrorMessage());
            AssertUtils.ArgumentNotNull(dataAdapterType, "dataAdapterType", GetErrorMessage());
            AssertUtils.ArgumentNotNull(commandBuilderType, "commandBuilderType", GetErrorMessage());
            AssertUtils.ArgumentHasText(commandBuilderDeriveParametersMethod, "commandBuilderDeriveParametersMethod", GetErrorMessage());
            AssertUtils.ArgumentNotNull(parameterDbType, "parameterDbType", GetErrorMessage());
            AssertUtils.ArgumentHasText(parameterDbTypeProperty, "parameterDbTypeProperty", GetErrorMessage());
            AssertUtils.ArgumentHasText(parameterIsNullableProperty, "parameterIsNullableProperty", GetErrorMessage());
            AssertUtils.ArgumentHasText(parameterNamePrefix, "parameterNamePrefix", GetErrorMessage());
            AssertUtils.ArgumentNotNull(exceptionType, "exceptionType", GetErrorMessage());

            this.assemblyName = assemblyName;

            this.connectionType     = connectionType;
            this.commandType        = commandType;
            this.parameterType      = parameterType;
            this.dataAdapterType    = dataAdapterType;
            this.commandBuilderType = commandBuilderType;

            if (commandBuilderDeriveParametersMethod.ToLower().Trim().Equals("not supported"))
            {
                supportsDeriveParametersMethod = false;
            }

            if (supportsDeriveParametersMethod)
            {
                this.commandBuilderDeriveParametersMethod =
                    ReflectionUtils.GetMethod(this.commandBuilderType, commandBuilderDeriveParametersMethod,
                                              new Type[] { this.commandType });

                AssertUtils.ArgumentNotNull(this.commandBuilderDeriveParametersMethod,
                                            "commandBuilderDeriveParametersMethod", GetErrorMessage() +
                                            ", could not resolve commandBuilderDeriveParametersMethod " +
                                            commandBuilderDeriveParametersMethod +
                                            " to MethodInfo.  Please check dbproviders.xml entry for correct metadata listing.");
            }

            this.commandType = commandType;

            this.parameterDbType = parameterDbType;

            this.parameterDbTypeProperty = this.parameterType.GetProperty(parameterDbTypeProperty,
                                                                          BindingFlags.Instance | BindingFlags.Public);
            AssertUtils.ArgumentNotNull(this.parameterDbTypeProperty, "parameterDbTypeProperty", GetErrorMessage() +
                                        ", could not resolve parameterDbTypeProperty " +
                                        parameterDbTypeProperty +
                                        " to PropertyInfo.  Please check dbproviders.xml entry for correct metadata listing.");

            this.parameterIsNullableProperty = this.parameterType.GetProperty(parameterIsNullableProperty,
                                                                              BindingFlags.Instance | BindingFlags.Public);

            AssertUtils.ArgumentNotNull(this.parameterIsNullableProperty, "parameterIsNullableProperty", GetErrorMessage() +
                                        ", could not resolve parameterIsNullableProperty " +
                                        parameterIsNullableProperty +
                                        " to PropertyInfo.  Please check dbproviders.xml entry for correct metadata listing.");

            this.parameterNamePrefix = parameterNamePrefix;
            this.exceptionType       = exceptionType;

            this.useParameterNamePrefixInParameterCollection = useParameterNamePrefixInParameterCollection;
            this.useParameterPrefixInSql = useParameterPrefixInSql;
            this.bindByName = bindByName;

            this.errorCodeExceptionExpression = errorCodeExceptionExpression;


            errorCodes = new ErrorCodes();
        }
Esempio n. 18
0
    private void Disassemble()
    {
        GameObjectAssembler     _assembler         = new GameObjectAssembler();
        TurretAssemblyAssembler _assemblyAssembler = new TurretAssemblyAssembler();

        string path = Paths.StreamingAssets;
        string name = string.Empty;
        string data = "";

        switch (Type)
        {
        case TargetType.Assembly:
            data = ObjectPipeline.SerializeObject(_assemblyAssembler.Disassemble((Object as GameObject).GetComponent <TurretAssembly>())).ToString();
            name = Object.name;
            break;

        case TargetType.GameObject:
            data = ObjectPipeline.SerializeObject(_assembler.Disassemble(Object as GameObject)).ToString();
            name = Object.name;
            break;

        case TargetType.Object:
            data = ObjectPipeline.UnbuildObject(Object == null ? Activator.CreateInstance(ReflectionUtils.GetType(_objectTypeName)) : Object, Implicit).ToString();
            name = Object == null?_objectTypeName.Replace(".", "") : Object.name;

            break;
        }

        path = path + Path + name + ".json";


        File.WriteAllText(path, data);
    }
Esempio n. 19
0
        public void TestGetAllInstancePropertyInfosObject()
        {
            var properties = ReflectionUtils.GetTypeProperties(typeof(MyClass));

            Assert.Equal(4, properties.Count);
        }
Esempio n. 20
0
        public void PopulateWithNonDefaultValues(object to, object from)
        {
            var nonDefaultPredicate = (Func <object, Type, bool>)((x, t) =>
                                                                  x != null && !Equals(x, ReflectionUtils.GetDefaultValue(t))
                                                                  );

            Populate(to, from, null, nonDefaultPredicate);
        }
Esempio n. 21
0
        public void CollectionWithAbstractItems()
        {
            HolderClass testObject = new HolderClass();

            testObject.TestMember        = new ContentSubClass("First One");
            testObject.AnotherTestMember = new Dictionary <int, IList <ContentBaseClass> >();
            testObject.AnotherTestMember.Add(1, new List <ContentBaseClass>());
            testObject.AnotherTestMember[1].Add(new ContentSubClass("Second One"));
            testObject.AThirdTestMember = new ContentSubClass("Third One");


            JsonSerializer serializingTester = new JsonSerializer();

            serializingTester.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

            StringWriter sw = new StringWriter();

            using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
            {
                jsonWriter.Formatting = Formatting.Indented;
                serializingTester.TypeNameHandling = TypeNameHandling.Auto;
                serializingTester.Serialize(jsonWriter, testObject);
            }

            string json = sw.ToString();

            string contentSubClassRef = ReflectionUtils.GetTypeName(typeof(ContentSubClass), FormatterAssemblyStyle.Simple);
            string dictionaryRef      = ReflectionUtils.GetTypeName(typeof(Dictionary <int, IList <ContentBaseClass> >), FormatterAssemblyStyle.Simple);
            string listRef            = ReflectionUtils.GetTypeName(typeof(List <ContentBaseClass>), FormatterAssemblyStyle.Simple);


            Assert.AreEqual(@"{
  ""TestMember"": {
    ""$type"": """ + contentSubClassRef + @""",
    ""SomeString"": ""First One""
  },
  ""AnotherTestMember"": {
    ""$type"": """ + dictionaryRef + @""",
    ""1"": {
      ""$type"": """ + listRef + @""",
      ""$values"": [
        {
          ""$type"": """ + contentSubClassRef + @""",
          ""SomeString"": ""Second One""
        }
      ]
    }
  },
  ""AThirdTestMember"": {
    ""$type"": """ + contentSubClassRef + @""",
    ""SomeString"": ""Third One""
  }
}", json);
            Console.WriteLine(json);

            StringReader sr = new StringReader(json);

            JsonSerializer deserializingTester = new JsonSerializer();

            HolderClass anotherTestObject;

            using (JsonTextReader jsonReader = new JsonTextReader(sr))
            {
                deserializingTester.TypeNameHandling = TypeNameHandling.Auto;

                anotherTestObject = deserializingTester.Deserialize <HolderClass>(jsonReader);
            }

            Assert.IsNotNull(anotherTestObject);
            Assert.IsInstanceOfType(typeof(ContentSubClass), anotherTestObject.TestMember);
            Assert.IsInstanceOfType(typeof(Dictionary <int, IList <ContentBaseClass> >), anotherTestObject.AnotherTestMember);
            Assert.AreEqual(1, anotherTestObject.AnotherTestMember.Count);

            IList <ContentBaseClass> list = anotherTestObject.AnotherTestMember[1];

            Assert.IsInstanceOfType(typeof(List <ContentBaseClass>), list);
            Assert.AreEqual(1, list.Count);
            Assert.IsInstanceOfType(typeof(ContentSubClass), list[0]);
        }
Esempio n. 22
0
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            var listModelHost = modelHost.WithAssertAndCast <ListModelHost>("modelHost", value => value.RequireNotNull());
            var definition    = model.WithAssertAndCast <ListViewDefinition>("model", value => value.RequireNotNull());

            var list = listModelHost.HostList;

            var context = list.Context;

            context.Load(list, l => l.Fields);
            context.Load(list, l => l.Views.Include(
                             v => v.ViewFields,
                             o => o.Title,
                             o => o.DefaultView,
                             o => o.ViewQuery,
                             o => o.RowLimit,
                             o => o.Paged,
                             o => o.Hidden,
                             o => o.JSLink,
                             o => o.ServerRelativeUrl,
                             o => o.DefaultViewForContentType,
                             o => o.ContentTypeId,
                             o => o.ViewType,
                             o => o.ViewData,
                             v => v.Title));
            context.ExecuteQueryWithTrace();

            var spObject = FindViewByTitle(list.Views, definition.Title);
            var assert   = ServiceFactory.AssertService
                           .NewAssert(definition, spObject)
                           .ShouldNotBeNull(spObject)
                           .ShouldBeEqual(m => m.Title, o => o.Title)
                           .ShouldBeEqual(m => m.IsDefault, o => o.DefaultView)
                           .ShouldBeEqual(m => m.Hidden, o => o.Hidden)
                           //.ShouldBeEqual(m => m.Query, o => o.ViewQuery)
                           .ShouldBeEqual(m => m.RowLimit, o => (int)o.RowLimit)
                           .ShouldBeEqual(m => m.IsPaged, o => o.Paged);

            if (!string.IsNullOrEmpty(definition.ViewData))
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(def => def.ViewData);
                    var dstProp = d.GetExpressionValue(o => o.ViewData);

                    var srcViewDate = assert.Src.ViewData.Replace(System.Environment.NewLine, string.Empty).Replace(" /", "/");
                    var dstViewDate = assert.Dst.ViewData.Replace(System.Environment.NewLine, string.Empty).Replace(" /", "/");

                    var isValid = srcViewDate.ToUpper() == dstViewDate.ToUpper();

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = dstProp,
                        IsValid = isValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(m => m.ViewData);
            }

            if (!string.IsNullOrEmpty(definition.Type))
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(def => def.Type);
                    var dstProp = d.GetExpressionValue(o => o.ViewType);

                    var isValid = srcProp.Value.ToString().ToUpper() ==
                                  dstProp.Value.ToString().ToUpper();

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = dstProp,
                        IsValid = isValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(m => m.Type);
            }

            assert.SkipProperty(m => m.ViewStyleId, "ViewStyleId unsupported by SP CSOM  API yet. Skipping.");

            if (!string.IsNullOrEmpty(definition.JSLink))
            {
                assert.ShouldBePartOf(m => m.JSLink, o => o.JSLink);
            }
            else
            {
                assert.SkipProperty(m => m.JSLink, "JSLink is null or empty. Skipping.");
            }

            if (!string.IsNullOrEmpty(definition.Query))
            {
                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(def => def.Query);
                    var dstProp = d.GetExpressionValue(o => o.ViewQuery);

                    var srcViewDate = assert.Src.Query.Replace(System.Environment.NewLine, string.Empty).Replace(" /", "/");
                    var dstViewDate = assert.Dst.ViewQuery.Replace(System.Environment.NewLine, string.Empty).Replace(" /", "/");

                    var isValid = srcViewDate.ToUpper() == dstViewDate.ToUpper();

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = dstProp,
                        IsValid = isValid
                    });
                });
            }
            else
            {
                assert.SkipProperty(m => m.Query, "Query is null or empty. Skipping.");
            }

            if (definition.DefaultViewForContentType.HasValue)
            {
                assert.ShouldBeEqual(m => m.DefaultViewForContentType, o => o.DefaultViewForContentType);
            }
            else
            {
                assert.SkipProperty(m => m.DefaultViewForContentType, "DefaultViewForContentType is null or empty. Skipping.");
            }

            if (string.IsNullOrEmpty(definition.ContentTypeName))
            {
                assert.SkipProperty(m => m.ContentTypeName, "ContentTypeName is null or empty. Skipping.");
            }
            else
            {
                var contentTypeId = LookupListContentTypeByName(list, definition.ContentTypeName);

                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(def => def.ContentTypeName);
                    var dstProp = d.GetExpressionValue(ct => ct.ContentTypeId);

                    var isValis = contentTypeId.StringValue == d.ContentTypeId.StringValue;

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = dstProp,
                        IsValid = isValis
                    });
                });
            }

            if (string.IsNullOrEmpty(definition.ContentTypeId))
            {
                assert.SkipProperty(m => m.ContentTypeId, "ContentTypeId is null or empty. Skipping.");
            }
            else
            {
                var contentTypeId = LookupListContentTypeById(list, definition.ContentTypeId);

                assert.ShouldBeEqual((p, s, d) =>
                {
                    var srcProp = s.GetExpressionValue(def => def.ContentTypeId);
                    var dstProp = d.GetExpressionValue(ct => ct.ContentTypeId);

                    var isValis = contentTypeId.StringValue == d.ContentTypeId.StringValue;

                    return(new PropertyValidationResult
                    {
                        Tag = p.Tag,
                        Src = srcProp,
                        Dst = dstProp,
                        IsValid = isValis
                    });
                });
            }

            if (string.IsNullOrEmpty(definition.Url))
            {
                assert.SkipProperty(m => m.Url, "Url is null or empty. Skipping.");
            }
            else
            {
                assert.ShouldBePartOf(m => m.Url, o => o.ServerRelativeUrl);
            }

            assert.ShouldBeEqual((p, s, d) =>
            {
                var srcProp = s.GetExpressionValue(def => def.Fields);
                var dstProp = d.GetExpressionValue(ct => ct.ViewFields);

                var hasAllFields = true;

                foreach (var srcField in s.Fields)
                {
                    var listField = list.Fields.ToList().FirstOrDefault(f => f.StaticName == srcField);

                    // if list-scoped field we need to check by internal name
                    // internal name is changed for list scoped-fields
                    // that's why to check by BOTH, definition AND real internal name

                    if (!d.ViewFields.ToList().Contains(srcField) &&
                        !d.ViewFields.ToList().Contains(listField.InternalName))
                    {
                        hasAllFields = false;
                    }
                }

                return(new PropertyValidationResult
                {
                    Tag = p.Tag,
                    Src = srcProp,
                    Dst = dstProp,
                    IsValid = hasAllFields
                });
            });

            var supportsLocalization = ReflectionUtils.HasProperties(spObject, new[]
            {
                "TitleResource"
            });

            if (supportsLocalization)
            {
                if (definition.TitleResource.Any())
                {
                    assert.ShouldBeEqual((p, s, d) =>
                    {
                        var srcProp = s.GetExpressionValue(def => def.TitleResource);
                        var isValid = true;

                        foreach (var userResource in s.TitleResource)
                        {
                            var culture        = LocalizationService.GetUserResourceCultureInfo(userResource);
                            var resourceObject = ReflectionUtils.GetPropertyValue(spObject, "TitleResource");

                            var value = ReflectionUtils.GetMethod(resourceObject, "GetValueForUICulture")
                                        .Invoke(resourceObject, new[] { culture.Name }) as ClientResult <string>;

                            context.ExecuteQuery();

                            isValid = userResource.Value == value.Value;

                            if (!isValid)
                            {
                                break;
                            }
                        }

                        return(new PropertyValidationResult
                        {
                            Tag = p.Tag,
                            Src = srcProp,
                            Dst = null,
                            IsValid = isValid
                        });
                    });
                }
                else
                {
                    assert.SkipProperty(m => m.TitleResource, "TitleResource is NULL or empty. Skipping.");
                }
            }
            else
            {
                TraceService.Critical((int)LogEventId.ModelProvisionCoreCall,
                                      "CSOM runtime doesn't have Web.TitleResource and Web.DescriptionResource() methods support. Skipping validation.");

                assert.SkipProperty(m => m.TitleResource, "TitleResource is null or empty. Skipping.");
            }
        }
Esempio n. 23
0
 /// <summary>
 /// Returns a collection of attributes, identified by type, or an empty collection if there are no attributes.
 /// </summary>
 /// <param name="attributeType">The type of the attributes.</param>
 /// <param name="inherit">When true, look up the hierarchy chain for the inherited custom attribute.</param>
 /// <returns>A collection of <see cref="Attribute"/>s, or an empty collection.</returns>
 public IList <Attribute> GetAttributes(Type attributeType, bool inherit)
 {
     return(ReflectionUtils.GetAttributes(_attributeProvider, attributeType, inherit));
 }
Esempio n. 24
0
        public static string ReplaceDirectMethods(string script, Control seed)
        {
            if (TokenUtils.IsDirectMethodsToken(script))
            {
                string ns = ResourceManager.GlobalNormalizedDirectMethodNamespace;
#if MVC
                if (Ext.Net.MVC.MvcResourceManager.IsMVC || (seed is BaseControl && ((BaseControl)seed).IsMVC))
                {
                    if (HttpContext.Current != null && HttpContext.Current.Request.RequestContext.RouteData.DataTokens["area"] != null)
                    {
                        return(script.Replace(TokenUtils.Settings.DirectMethodsPattern, ns.ConcatWith(".", HttpContext.Current.Request.RequestContext.RouteData.DataTokens["area"].ToString())));
                    }

                    return(script.Replace(TokenUtils.Settings.DirectMethodsPattern, ns));
                }
#endif

                UserControl parent = seed as UserControl;

                if (parent == null)
                {
                    parent = ReflectionUtils.GetTypeOfParent(seed, typeof(System.Web.UI.UserControl)) as UserControl;
                }

                ResourceManager sm = null;

                if (parent != null && !(parent is MasterPage && seed.Parent is System.Web.UI.WebControls.ContentPlaceHolder))
                {
                    string id = ResourceManager.GetControlIdentification(parent, null);

                    if (id.IsNotEmpty())
                    {
                        id = ".".ConcatWith(id);
                    }

                    sm = ResourceManager.GetInstance(HttpContext.Current);

                    if (sm != null)
                    {
                        ns = sm.NormalizedDirectMethodNamespace;
                    }

                    return(script.Replace(TokenUtils.Settings.DirectMethodsPattern, ns.ConcatWith(id)));
                }
                else
                {
                    Page parentPage = seed as Page;

                    if (parentPage == null)
                    {
                        parentPage = ReflectionUtils.GetTypeOfParent(seed, typeof(System.Web.UI.Page)) as System.Web.UI.Page;
                    }


                    sm = ResourceManager.GetInstance();

                    if (sm != null)
                    {
                        ns = sm.NormalizedDirectMethodNamespace;
                    }

                    return(script.Replace(TokenUtils.Settings.DirectMethodsPattern, ns));
                }
            }

            return(script);
        }
Esempio n. 25
0
        /// <summary>
        /// Reads the JSON representation of the object.
        /// </summary>
        /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
        /// <param name="objectType">Type of the object.</param>
        /// <param name="existingValue">The existing value of object being read.</param>
        /// <param name="serializer">The calling serializer.</param>
        /// <returns>The object value.</returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            bool nullable = ReflectionUtils.IsNullableType(objectType);
            Type t        = (nullable)
                ? Nullable.GetUnderlyingType(objectType)
                : objectType;

            if (reader.TokenType == JsonToken.Null)
            {
                if (!ReflectionUtils.IsNullableType(objectType))
                {
                    throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
                }

                return(null);
            }

            if (reader.TokenType == JsonToken.Date)
            {
#if !NET20
                if (t == typeof(DateTimeOffset))
                {
                    return(reader.Value is DateTimeOffset ? reader.Value : new DateTimeOffset((DateTime)reader.Value));
                }
#endif

                return(reader.Value);
            }

            if (reader.TokenType != JsonToken.String)
            {
                throw JsonSerializationException.Create(reader, "Unexpected token parsing date. Expected String, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
            }

            string dateText = reader.Value.ToString();

            if (string.IsNullOrEmpty(dateText) && nullable)
            {
                return(null);
            }

#if !NET20
            if (t == typeof(DateTimeOffset))
            {
                if (!string.IsNullOrEmpty(_dateTimeFormat))
                {
                    return(DateTimeOffset.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles));
                }
                else
                {
                    return(DateTimeOffset.Parse(dateText, Culture, _dateTimeStyles));
                }
            }
#endif

            if (!string.IsNullOrEmpty(_dateTimeFormat))
            {
                return(DateTime.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles));
            }
            else
            {
                return(DateTime.Parse(dateText, Culture, _dateTimeStyles));
            }
        }
Esempio n. 26
0
        public static string ReplaceIDTokens(string script, Control seed)
        {
            script = TokenUtils.ReplaceDirectMethods(script, seed);

            Control control = null;

            string[] parts = null;

            if (!TokenUtils.Settings.IDParsingDisable)
            {
                foreach (Match match in TokenUtils.Settings.ID_Pattern_RE.Matches(script))
                {
                    parts = match.Value.Between("{", "}").Split('.');

                    control = ControlUtils.FindControl(seed, parts[0]);

                    if (control != null)
                    {
                        if (parts.Length == 2)
                        {
                            PropertyInfo prop = control.GetType().GetProperty(parts[1]);

                            if (prop != null)
                            {
                                object value = prop.GetValue(control, null);

                                if (value == null)
                                {
                                    value = ReflectionUtils.GetDefaultValue(prop);
                                }

                                if (value is string)
                                {
                                    string val = TokenUtils.ParseTokens(value.ToString(), control);

                                    if (TokenUtils.IsRawToken(val))
                                    {
                                        val = JSON.Serialize(TokenUtils.ReplaceRawToken(val)).Chop();
                                    }
                                    else
                                    {
                                        val = JSON.Serialize(val);
                                    }

                                    script = script.Replace(match.Value, val);
                                }
                                else
                                {
                                    script = script.Replace(match.Value, JSON.Serialize(value));
                                }
                            }
                        }
                        else
                        {
                            if (control is Observable || control is UserControl)
                            {
                                script = script.Replace(match.Value, control.ClientID);
                            }
                            else
                            {
                                script = script.Replace(match.Value, "Ext.get(\"" + control.ClientID + "\")");
                            }
                        }
                    }
                    else
                    {
                        script = script.Replace(match.Value, "Ext.get(\"" + parts[0] + "\")");
                    }
                }
            }

            return(script);
        }
        private JsonSchema GenerateInternal(Type type, Required valueRequired, bool required)
        {
            ValidationUtils.ArgumentNotNull(type, "type");

            string resolvedId = GetTypeId(type, false);
            string explicitId = GetTypeId(type, true);

            if (!string.IsNullOrEmpty(resolvedId))
            {
                JsonSchema resolvedSchema = _resolver.GetSchema(resolvedId);
                if (resolvedSchema != null)
                {
                    // resolved schema is not null but referencing member allows nulls
                    // change resolved schema to allow nulls. hacky but what are ya gonna do?
                    if (valueRequired != Required.Always && !HasFlag(resolvedSchema.Type, JsonSchemaType.Null))
                    {
                        resolvedSchema.Type |= JsonSchemaType.Null;
                    }
                    if (required && resolvedSchema.Required != true)
                    {
                        resolvedSchema.Required = true;
                    }

                    return(resolvedSchema);
                }
            }

            // test for unresolved circular reference
            if (_stack.Any(tc => tc.Type == type))
            {
                throw new JsonException("Unresolved circular reference for type '{0}'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.".FormatWith(CultureInfo.InvariantCulture, type));
            }

            JsonContract  contract = ContractResolver.ResolveContract(type);
            JsonConverter converter;

            if ((converter = contract.Converter) != null || (converter = contract.InternalConverter) != null)
            {
                JsonSchema converterSchema = converter.GetSchema();
                if (converterSchema != null)
                {
                    return(converterSchema);
                }
            }

            Push(new TypeSchema(type, new JsonSchema()));

            if (explicitId != null)
            {
                CurrentSchema.Id = explicitId;
            }

            if (required)
            {
                CurrentSchema.Required = true;
            }
            CurrentSchema.Title       = GetTitle(type);
            CurrentSchema.Description = GetDescription(type);

            if (converter != null)
            {
                // todo: Add GetSchema to JsonConverter and use here?
                CurrentSchema.Type = JsonSchemaType.Any;
            }
            else
            {
                switch (contract.ContractType)
                {
                case JsonContractType.Object:
                    CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired);
                    CurrentSchema.Id   = GetTypeId(type, false);
                    GenerateObjectSchema(type, (JsonObjectContract)contract);
                    break;

                case JsonContractType.Array:
                    CurrentSchema.Type = AddNullType(JsonSchemaType.Array, valueRequired);

                    CurrentSchema.Id = GetTypeId(type, false);

                    JsonArrayAttribute arrayAttribute = JsonTypeReflector.GetJsonContainerAttribute(type) as JsonArrayAttribute;
                    bool allowNullItem = (arrayAttribute == null || arrayAttribute.AllowNullItems);

                    Type collectionItemType = ReflectionUtils.GetCollectionItemType(type);
                    if (collectionItemType != null)
                    {
                        CurrentSchema.Items = new List <JsonSchema>();
                        CurrentSchema.Items.Add(GenerateInternal(collectionItemType, (!allowNullItem) ? Required.Always : Required.Default, false));
                    }
                    break;

                case JsonContractType.Primitive:
                    CurrentSchema.Type = GetJsonSchemaType(type, valueRequired);

                    if (CurrentSchema.Type == JsonSchemaType.Integer && type.IsEnum() && !type.IsDefined(typeof(FlagsAttribute), true))
                    {
                        CurrentSchema.Enum = new List <JToken>();

                        EnumValues <long> enumValues = EnumUtils.GetNamesAndValues <long>(type);
                        foreach (EnumValue <long> enumValue in enumValues)
                        {
                            JToken value = JToken.FromObject(enumValue.Value);

                            CurrentSchema.Enum.Add(value);
                        }
                    }
                    break;

                case JsonContractType.String:
                    JsonSchemaType schemaType = (!ReflectionUtils.IsNullable(contract.UnderlyingType))
                                          ? JsonSchemaType.String
                                          : AddNullType(JsonSchemaType.String, valueRequired);

                    CurrentSchema.Type = schemaType;
                    break;

                case JsonContractType.Dictionary:
                    CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired);

                    Type keyType;
                    Type valueType;
                    ReflectionUtils.GetDictionaryKeyValueTypes(type, out keyType, out valueType);

                    if (keyType != null)
                    {
                        JsonContract keyContract = ContractResolver.ResolveContract(keyType);

                        // can be converted to a string
                        if (keyContract.ContractType == JsonContractType.Primitive)
                        {
                            CurrentSchema.AdditionalProperties = GenerateInternal(valueType, Required.Default, false);
                        }
                    }
                    break;

                case JsonContractType.Dynamic:
                case JsonContractType.Linq:
                    CurrentSchema.Type = JsonSchemaType.Any;
                    break;

                default:
                    throw new JsonException("Unexpected contract type: {0}".FormatWith(CultureInfo.InvariantCulture, contract));
                }
            }

            return(Pop().Schema);
        }
Esempio n. 28
0
        /// <summary>
        /// Creates the proxy type.
        /// </summary>
        /// <returns>The generated proxy class.</returns>
        public override Type BuildProxyType()
        {
            IDictionary targetMethods = new Hashtable();
            IDictionary proxyMethods  = new Hashtable();

            TypeBuilder typeBuilder = CreateTypeBuilder(Name, BaseType);

            // apply custom attributes to the proxy type.
            ApplyTypeAttributes(typeBuilder, TargetType);

            // declare fields
            DeclareAdvisedProxyInstanceField(typeBuilder);

            // implement ISerializable if possible
            if (advised.IsSerializable)
            {
                typeBuilder.SetCustomAttribute(
                    ReflectionUtils.CreateCustomAttribute(typeof(SerializableAttribute)));
                ImplementSerializationConstructor(typeBuilder);
                ImplementGetObjectDataMethod(typeBuilder);
            }

            // create constructors
            ImplementConstructors(typeBuilder);

            // implement interfaces
            IDictionary interfaceMap = advised.InterfaceMap;

            foreach (Type intf in Interfaces)
            {
                object target = interfaceMap[intf];
                if (target == null)
                {
                    // implement interface (proxy only final methods)
                    ImplementInterface(typeBuilder,
                                       new BaseAopProxyMethodBuilder(typeBuilder, this, targetMethods, proxyMethods),
                                       intf, TargetType, false);
                }
                else if (target is IIntroductionAdvisor)
                {
                    // implement introduction
                    ImplementInterface(typeBuilder,
                                       new IntroductionProxyMethodBuilder(typeBuilder, this, targetMethods, advised.IndexOf((IIntroductionAdvisor)target)),
                                       intf, TargetType);
                }
            }

            // inherit from target type
            InheritType(typeBuilder,
                        new BaseAopProxyMethodBuilder(typeBuilder, this, targetMethods, proxyMethods),
                        TargetType, ProxyDeclaredMembersOnly);

            // implement IAdvised interface
            ImplementInterface(typeBuilder,
                               new IAdvisedProxyMethodBuilder(typeBuilder, this),
                               typeof(IAdvised), TargetType);

            // implement IAopProxy interface
            ImplementIAopProxy(typeBuilder);

            Type proxyType;

            proxyType = typeBuilder.CreateType();

            // set target method references
            foreach (DictionaryEntry entry in targetMethods)
            {
                FieldInfo field = proxyType.GetField((string)entry.Key, BindingFlags.NonPublic | BindingFlags.Static);
                field.SetValue(proxyType, (MethodInfo)entry.Value);
            }

            // set proxy method references
            foreach (DictionaryEntry entry in proxyMethods)
            {
                FieldInfo field = proxyType.GetField((string)entry.Key, BindingFlags.NonPublic | BindingFlags.Static);
                field.SetValue(proxyType, FindProxyMethod(proxyType, (MethodInfo)entry.Value));
            }

            return(proxyType);
        }
Esempio n. 29
0
 private static bool ShouldCache(MethodInfo info)
 {
     return(!ReflectionUtils.IsDynamicMethod(info));
 }
Esempio n. 30
0
        object ConvertToList(ArrayList col, Type type)
        {
            Type elementType = null;

            if (type != null && type.HasElementType)
            {
                elementType = type.GetElementType();
            }

            IList list;

            if (type == null || type.IsArray || typeofObject == type || typeof(ArrayList).IsAssignableFrom(type))
            {
                list = new ArrayList();
            }
            else if (ReflectionUtils.IsInstantiatableType(type))
            {
                // non-generic typed list
                list = (IList)Activator.CreateInstance(type, true);
            }
            else if (ReflectionUtils.IsAssignable(type, typeofGenList))
            {
                if (type.IsGenericType)
                {
                    Type [] genArgs = type.GetGenericArguments();
                    elementType = genArgs [0];
                    // generic list
                    list = (IList)Activator.CreateInstance(typeofGenList.MakeGenericType(genArgs));
                }
                else
                {
                    list = new ArrayList();
                }
            }
            else
            {
                throw new InvalidOperationException(String.Format("Deserializing list type '{0}' not supported.", type.GetType().Name));
            }

            if (list.IsReadOnly)
            {
                EvaluateList(col);
                return(list);
            }

            if (elementType == null)
            {
                elementType = typeof(object);
            }

            foreach (object value in col)
            {
                list.Add(ConvertToType(value, elementType));
            }

            if (type != null && type.IsArray)
            {
                list = ((ArrayList)list).ToArray(elementType);
            }

            return(list);
        }