public object Restore() { var type = TypeProvider.GetType(assemblyQualifiedName); var ctor = type.GetConstructor(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, new [] { typeof(SerializationInfo), typeof(StreamingContext) }, null); var serializationInfo = new SerializationInfo(type, new FormatterConverter()); serializationInfo.SetType(type); for (var i = 0; i < keys.Length; i++) { serializationInfo.AddValue(keys[i], values[i]); } var streamingContext = new StreamingContext(StreamingContextStates.Clone); var result = ctor.Invoke(new object[] { serializationInfo, streamingContext }); var onDeserialization = result as IDeserializationCallback; if (onDeserialization != null) { onDeserialization.OnDeserialization(this); } return(result); }
/// <inheritdoc /> /// <exception cref="ArgumentException">Thrown when <paramref name="propertyTemplate" /> is null, empty string or whitespace</exception> /// <exception cref="InvalidTemplateException"></exception> /// <exception cref="MemberNotFoundException"></exception> /// <exception cref="InvalidOperationException"></exception> public virtual object GetValue(string propertyTemplate) { if (string.IsNullOrWhiteSpace(propertyTemplate)) { throw new ArgumentException(ArgumentHelper.EmptyStringParamMessage, nameof(propertyTemplate)); } propertyTemplate = propertyTemplate.Trim(); MemberTemplateParts templateParts = ParseTemplate(propertyTemplate); if (string.IsNullOrWhiteSpace(templateParts.MemberName)) { throw new InvalidTemplateException(string.Format(Constants.InvalidTemplateMessage, propertyTemplate)); } Type type = TypeProvider.GetType(templateParts.TypeName); string[] props = templateParts.MemberName.Split(PropertiesSeparator); MemberInfo member = GetFirstMember(props[0], type); object firstMemberValue = GetFirstMemberValue(member, type); if (props.Length == 1) { return(firstMemberValue ?? _reflectionHelper.GetNullValueAttributeValue(member)); } return(_reflectionHelper.GetValueOfPropertiesChain(string.Join(PropertiesSeparator.ToString(), props.Skip(1)), firstMemberValue)); }
public IXmlSerializable Restore() { using (var stream = new MemoryStream(bytes)) { var xmlSerializer = new XmlSerializer(TypeProvider.GetType(assemblyQualifiedName)); return((IXmlSerializable)xmlSerializer.Deserialize(stream)); } }
public System.Type GetType(TypeName typeName) { if (Context != null) { return(Context.GetType(typeName)); } return(TypeProvider.GetType(typeName.FullName)); }
public override void Read(ObjectReader reader) { var size = reader.PrimitiveReader.ReadInt32(); nameAsByteArray = reader.PrimitiveReader.ReadBytes(size); Name = Encoding.UTF8.GetString(nameAsByteArray); UnderlyingType = TypeProvider.GetType(Name); }
static void Main(string[] args) { var unit = BuildHelloWorldGraph(); var typeProvider = new TypeProvider(null); typeProvider.AddCodeCompileUnit(unit); var t = typeProvider.GetType("Samples.Class1"); Console.WriteLine(t.GUID); // prints GUID for design time type instance. Console.WriteLine(Marshal.GenerateGuidForType(t)); // throws ArgumentException. }
internal static void AddTypeProviderAssembliesFromRegistry(TypeProvider typeProvider, IServiceProvider serviceProvider) { if (typeProvider == null) { throw new ArgumentNullException("typeProvider"); } if (serviceProvider == null) { throw new ArgumentNullException("serviceProvider"); } RegistryKey key = Registry.CurrentUser.OpenSubKey(TypeProviderRegistryKeyPath); if (key != null) { ITypeProviderCreator service = serviceProvider.GetService(typeof(ITypeProviderCreator)) as ITypeProviderCreator; foreach (string str in (string[])key.GetValue(TypeProviderAssemblyRegValueName)) { try { if (service != null) { bool flag = true; Assembly transientAssembly = service.GetTransientAssembly(AssemblyName.GetAssemblyName(str)); if (transientAssembly == null) { continue; } System.Type[] types = transientAssembly.GetTypes(); int index = 0; while (index < types.Length) { System.Type type = types[index]; if (typeProvider.GetType(type.AssemblyQualifiedName) != null) { flag = false; } break; } if (flag) { typeProvider.AddAssembly(transientAssembly); } continue; } typeProvider.AddAssemblyReference(str); } catch { } } key.Close(); } }
/// <inheritdoc /> /// <exception cref="ArgumentException">Thrown when <paramref name="methodCallTemplate" /> is null, empty string or whitespace</exception> /// <exception cref="InvalidTemplateException"></exception> /// <exception cref="MethodNotFoundException"></exception> /// <exception cref="NotSupportedException"></exception> /// <exception cref="InvalidOperationException"></exception> public object CallMethod(string methodCallTemplate, Type concreteType, ITemplateProcessor templateProcessor, HierarchicalDataItem dataItem) { if (string.IsNullOrWhiteSpace(methodCallTemplate)) { throw new ArgumentException(ArgumentHelper.EmptyStringParamMessage, nameof(methodCallTemplate)); } _templateStack.Push(methodCallTemplate.Trim()); try { MethodCallTemplateParts templateParts = ParseTemplate(MethodCallTemplate); Type type = concreteType ?? TypeProvider.GetType(templateParts.TypeName); IList <InputParameter> inputParams = GetInputParametersValues(templateParts.MethodParams, templateProcessor, dataItem); MethodInfo method = GetMethod(type, templateParts.MemberName, inputParams); object instance = GetInstance(type, method.IsStatic); return(CallMethod(instance, method, inputParams)); } finally { _templateStack.Pop(); } }
internal object GetContentItemModel(Type t, JToken item, JToken modularContent, Dictionary <string, object> processedItems = null) { processedItems = processedItems ?? new Dictionary <string, object>(); var system = item["system"].ToObject <ContentItemSystemAttributes>(); if (t == typeof(object)) { // Try to find a specific type t = TypeProvider?.GetType(system.Type); if (t == null) { throw new Exception($"No corresponding CLR type found for the '{system.Type}' content type. Provide a correct implementation of '{nameof(ICodeFirstTypeProvider)}' to the '{nameof(TypeProvider)}' property."); } } object instance = Activator.CreateInstance(t); if (!processedItems.ContainsKey(system.Codename)) { processedItems.Add(system.Codename, instance); } foreach (var property in instance.GetType().GetProperties()) { var propertyType = property.PropertyType; if (property.SetMethod != null) { if (propertyType == typeof(ContentItemSystemAttributes)) { // Handle the system metadata if (system != null) { property.SetValue(instance, system); } } else { object value = null; var propValue = ((JObject)item["elements"]).Properties() ?.FirstOrDefault(p => PropertyMapper.IsMatch(property, p.Name, system?.Type)) ?.FirstOrDefault()["value"]; if (propertyType == typeof(string)) { var links = ((JObject)propValue?.Parent?.Parent)?.Property("links")?.Value; // Handle rich_text link resolution if (links != null && propValue != null && _client.ContentLinkResolver != null) { value = _client.ContentLinkResolver.ResolveContentLinks(propValue?.ToObject <string>(), links); } else { value = propValue?.ToObject(propertyType); } } else if (propertyType == typeof(IEnumerable <MultipleChoiceOption>) || propertyType == typeof(IEnumerable <Asset>) || propertyType == typeof(IEnumerable <TaxonomyTerm>) || propertyType.GetTypeInfo().IsValueType) { // Handle non-hierarchical fields value = propValue?.ToObject(propertyType); } else if (propertyType.GetTypeInfo().IsGenericType && ((propertyType.GetInterfaces().Any(gt => gt.GetTypeInfo().IsGenericType&& gt.GetTypeInfo().GetGenericTypeDefinition() == typeof(ICollection <>)) && propertyType.GetTypeInfo().IsClass) || propertyType.GetGenericTypeDefinition() == typeof(IEnumerable <>))) { // Handle modular content var contentItemCodenames = propValue?.ToObject <IEnumerable <string> >(); var modularContentNode = (JObject)modularContent; var genericArgs = propertyType.GetGenericArguments(); // Create a List<T> based on the generic parameter of the input type (IEnumerable<T> or derived types) Type collectionType = propertyType.GetTypeInfo().IsInterface ? typeof(List <>).MakeGenericType(genericArgs) : propertyType; object contentItems = Activator.CreateInstance(collectionType); if (contentItemCodenames != null && contentItemCodenames.Any()) { foreach (string codename in contentItemCodenames) { var modularContentItemNode = modularContentNode.Properties().FirstOrDefault(p => p.Name == codename)?.First; if (modularContentItemNode != null) { object contentItem = null; if (processedItems.ContainsKey(codename)) { // Avoid infinite recursion by re-using already processed content items contentItem = processedItems[codename]; } else { if (genericArgs.First() == typeof(ContentItem)) { contentItem = new ContentItem(modularContentItemNode, modularContentNode, _client); } else { contentItem = GetContentItemModel(genericArgs.First(), modularContentItemNode, modularContentNode, processedItems); } if (!processedItems.ContainsKey(codename)) { processedItems.Add(codename, contentItem); } } // It certain that the instance is of the ICollection<> type at this point, we can call "Add" contentItems.GetType().GetMethod("Add").Invoke(contentItems, new[] { contentItem }); } } } value = contentItems; } if (value != null) { property.SetValue(instance, value); } } } } return(instance); }
internal object GetContentItemModel(Type t, JToken item, JToken modularContent, Dictionary <string, object> processedItems = null, HashSet <RichTextContentElements> currentlyResolvedRichStrings = null) { processedItems = processedItems ?? new Dictionary <string, object>(); currentlyResolvedRichStrings = currentlyResolvedRichStrings ?? new HashSet <RichTextContentElements>(); var richTextPropertiesToBeProcessed = new List <PropertyInfo>(); var system = item["system"].ToObject <ContentItemSystemAttributes>(); if (t == typeof(object)) { // Try to find a specific type t = TypeProvider?.GetType(system.Type); if (t == null) { throw new Exception($"No corresponding CLR type found for the '{system.Type}' content type. Provide a correct implementation of '{nameof(ICodeFirstTypeProvider)}' to the '{nameof(TypeProvider)}' property."); } } object instance = Activator.CreateInstance(t); if (!processedItems.ContainsKey(system.Codename)) { processedItems.Add(system.Codename, instance); } foreach (var property in instance.GetType().GetProperties()) { var propertyType = property.PropertyType; if (property.SetMethod != null) { if (propertyType == typeof(ContentItemSystemAttributes)) { // Handle the system metadata if (system != null) { property.SetValue(instance, system); } } else { object value = null; var propValue = ((JObject)item["elements"]).Properties() ?.FirstOrDefault(p => PropertyMapper.IsMatch(property, p.Name, system?.Type)) ?.FirstOrDefault()["value"]; if (propertyType == typeof(string)) { value = propValue?.ToObject <string>(); var links = ((JObject)propValue?.Parent?.Parent)?.Property("links")?.Value; var modularContentInRichText = ((JObject)propValue?.Parent?.Parent)?.Property("modular_content")?.Value; // Handle rich_text link resolution if (links != null && propValue != null && ContentLinkResolver != null) { value = ContentLinkResolver.ResolveContentLinks((string)value, links); } if (modularContentInRichText != null && propValue != null && _client.InlineContentItemsProcessor != null) { // At this point it's clear it's richtext because it contains modular content richTextPropertiesToBeProcessed.Add(property); } } else if (propertyType == typeof(IEnumerable <MultipleChoiceOption>) || propertyType == typeof(IEnumerable <Asset>) || propertyType == typeof(IEnumerable <TaxonomyTerm>) || propertyType.GetTypeInfo().IsValueType) { // Handle non-hierarchical fields value = propValue?.ToObject(propertyType); } else if (propertyType.GetTypeInfo().IsGenericType && ((propertyType.GetInterfaces().Any(gt => gt.GetTypeInfo().IsGenericType&& gt.GetTypeInfo().GetGenericTypeDefinition() == typeof(ICollection <>)) && propertyType.GetTypeInfo().IsClass) || propertyType.GetGenericTypeDefinition() == typeof(IEnumerable <>))) { // Handle modular content var contentItemCodenames = propValue?.ToObject <IEnumerable <string> >(); var modularContentNode = (JObject)modularContent; var genericArgs = propertyType.GetGenericArguments(); // Create a List<T> based on the generic parameter of the input type (IEnumerable<T> or derived types) Type collectionType = propertyType.GetTypeInfo().IsInterface ? typeof(List <>).MakeGenericType(genericArgs) : propertyType; object contentItems = Activator.CreateInstance(collectionType); if (contentItemCodenames != null && contentItemCodenames.Any()) { foreach (string codename in contentItemCodenames) { var modularContentItemNode = modularContentNode.Properties().FirstOrDefault(p => p.Name == codename)?.First; if (modularContentItemNode != null) { object contentItem = null; if (processedItems.ContainsKey(codename)) { // Avoid infinite recursion by re-using already processed content items contentItem = processedItems[codename]; } else { if (genericArgs.First() == typeof(ContentItem)) { contentItem = new ContentItem(modularContentItemNode, modularContentNode, _client); } else { contentItem = GetContentItemModel(genericArgs.First(), modularContentItemNode, modularContentNode, processedItems); } if (!processedItems.ContainsKey(codename)) { processedItems.Add(codename, contentItem); } } // It certain that the instance is of the ICollection<> type at this point, we can call "Add" contentItems.GetType().GetMethod("Add").Invoke(contentItems, new[] { contentItem }); } } } value = contentItems; } if (value != null) { property.SetValue(instance, value); } } } } // Richtext elements need to be processed last, so in case of circular dependency, content items resolved by // resolvers would have all elements already processed foreach (var property in richTextPropertiesToBeProcessed) { var value = property.GetValue(instance).ToString(); var propValue = ((JObject)item["elements"]).Properties() ?.FirstOrDefault(p => PropertyMapper.IsMatch(property, p.Name, system?.Type)) ?.FirstOrDefault()["value"]; var modularContentInRichText = ((JObject)propValue?.Parent?.Parent)?.Property("modular_content")?.Value; var currentlyProcessedString = new RichTextContentElements() { ContentItemCodeName = system.Codename, RichTextElementCodeName = property.Name }; if (currentlyResolvedRichStrings.Contains(currentlyProcessedString)) { // If this element is already being processed it's necessary to to use it as is (with removed inline content items) // otherwise resolving would be stuck in an infinite loop value = RemoveInlineContentItems(value); } else { currentlyResolvedRichStrings.Add(currentlyProcessedString); value = ProcessInlineContentItems(modularContent, processedItems, value, modularContentInRichText, currentlyResolvedRichStrings); currentlyResolvedRichStrings.Remove(currentlyProcessedString); } if (value != null) { property.SetValue(instance, value); } } return(instance); }
public TypeContext OnlyMethodsWithAttribute(string attributeName) { return(OnlyMethodsWithAttribute(TypeProvider.GetType(attributeName))); }
public TypeContext SetClassList(string attributeName) { var attributeType = TypeProvider.GetType(attributeName); return(SetClassList(attributeType)); }