public void DefineProvider(QualifiedName name, Type providerType, Type providerInstanceType, object metadata = null) { if (providerType == null) { throw new ArgumentNullException("providerType"); } if (providerInstanceType == null) { throw new ArgumentNullException("providerInstanceType"); } if (providerInstanceType.GetTypeInfo().IsAbstract || !providerType.GetTypeInfo().IsAssignableFrom(providerInstanceType)) { throw RuntimeFailure.InvalidProviderInstanceType("providerInstanceType"); } var qn = GetName(name, providerInstanceType, providerInstanceType.Name); var tr = new ProviderType(providerInstanceType, providerType, qn); tr.ProviderMetadata = ProviderMetadataWrapper.Create(ApplyCompleter(providerInstanceType, providerType, metadata)); tr.ProviderMetadata.Source = tr; AppendResult(tr); }
private void EnterText(string line) { int equalsIndex = line.IndexOf('='); if (equalsIndex < 0) { throw RuntimeFailure.PropertyDeclarationMissingKey(); } string newKey = null; string newValue = null; if (equalsIndex == line.Length - 1) { newKey = line.Substring(0, line.Length - 1); newValue = string.Empty; } else { newKey = line.Substring(0, equalsIndex); newValue = line.Substring(equalsIndex + 1).Trim(); } _key = newKey; _value = StringUnescaper.Unescape(newValue); _nodeKind = PropertyNodeKind.Property; }
public override object CreateInstance(Type type, IEnumerable <KeyValuePair <string, object> > values, IServiceProvider serviceProvider, params Attribute[] attributes) { if (type == null) { throw new ArgumentNullException("type"); } object result = null; Type builderType = Adaptable.GetBuilderType(type); if (builderType == null) { return(Default.CreateInstance(type, values, serviceProvider, attributes)); } else { result = Default.CreateInstance(builderType, values, serviceProvider, attributes); MethodInfo mi; result = Adaptable.InvokeBuilder(result, out mi, serviceProvider); InitializeCoreHelper(result, mi.ReturnType, values, serviceProvider); } if (result == null) { throw RuntimeFailure.CannotActivateNoConstructorOrBuilder("type", type); } return(result); }
public static object FromStreamContext(Type componentType, StreamContext streamContext, Encoding encoding = null) { if (componentType == null) { throw new ArgumentNullException("componentType"); } if (streamContext == null) { throw new ArgumentNullException("streamContext"); } StreamingSource ss = StreamingSource.Create( componentType, streamContext.ContentType, streamContext.Extension ); if (ss == null) { throw RuntimeFailure.NoAcceptableStreamingSource(componentType); } if (ss is TextSource text) { text.Encoding = encoding; } return(ss.Load(streamContext, componentType)); }
public virtual object CreateInstance(Type type, IEnumerable <KeyValuePair <string, object> > values = null, IServiceProvider serviceProvider = null, params Attribute[] attributes) { if (type == null) { throw new ArgumentNullException(nameof(type)); } try { ServiceProvider.PushCurrent(serviceProvider); serviceProvider = serviceProvider ?? ServiceProvider.Root; type = GetActivationType(type); object result = ActivateCoreHelper(type, ref values, serviceProvider); if (result == null) { throw RuntimeFailure.CannotActivateNoConstructor("type", type); } InitializeCoreHelper(result, type, values, serviceProvider); return(result); } finally { ServiceProvider.PopCurrent(); } }
public void DefineProvider(QualifiedName name, Type providerType, MethodInfo factoryMethod, object metadata = null) { if (providerType == null) { throw new ArgumentNullException("providerType"); } if (factoryMethod == null) { throw new ArgumentNullException("factoryMethod"); } if (!factoryMethod.IsStatic || !providerType.IsAssignableFrom(factoryMethod.ReturnType)) { throw RuntimeFailure.InvalidProviderFieldOrMethod("factoryMethod"); } var qn = GetName(name, factoryMethod.DeclaringType, factoryMethod.Name); var methodResult = new ProviderMethod(factoryMethod, providerType, qn); methodResult.ProviderMetadata = ProviderMetadataWrapper.Create(metadata); methodResult.ProviderMetadata.Source = methodResult; AppendResult(methodResult); }
void ICollection <KeyValuePair <string, object> > .Add(KeyValuePair <string, object> item) { if (string.IsNullOrEmpty(item.Key)) { throw RuntimeFailure.CannotSpecifyNullKey("item"); } SetProperty(item.Key, item.Value); }
static T Required <T>(T obj, Type providerType) { if (Equals(obj, default(T))) { throw RuntimeFailure.ProviderNotFound(providerType); } return(obj); }
public static StreamContext FromSource(Uri source) { if (source == null) { throw new ArgumentNullException("source"); } // Look for native providers (file, res, iso, mem, stream) if (source.IsAbsoluteUri) { switch (source.Scheme) { case "file": return(new FileSystemStreamContext(source, null)); case "data": return(new DataStreamContext(source)); case "invalid": return(StreamContext.Invalid); case "null": return(StreamContext.Null); case "stdout": // TODO Consider implementing an alternative using Console stream return(new StreamStreamContext(new Uri("stdout://"), Console.OpenStandardOutput(), Console.OutputEncoding)); case "stderr": return(new StreamStreamContext(new Uri("stderr://"), Console.OpenStandardError(), Console.OutputEncoding)); case "stdin": return(new StreamStreamContext(new Uri("stdin://"), Console.OpenStandardInput(), Console.InputEncoding)); case "stream": throw RuntimeFailure.ForbiddenStreamStreamContext(); case "https": case "http": return(new HttpClientStreamContext(source)); default: throw RuntimeFailure.StreamContextUriSchemeNotSupported(); } } else { // Relative URIs must be handled in this way return(FromFile(source.ToString())); } }
public override Assembly Load() { if (!_fileExists(RelatedAssemblyLocation)) { throw RuntimeFailure.UnableToLoadRelatedAssembly(_name, _requestor, new [] { _assemblyDirectory }, RelatedAssemblyLocation); } return(_loadFile(RelatedAssemblyLocation)); }
public ProviderRegistrationAttribute(ProviderRegistrationType knownType) { if (knownType == ProviderRegistrationType.Custom) { throw RuntimeFailure.UseProviderRegistrationAttributeOverload("knownType", knownType); } this.registration = ProviderRegistration.FromKind(knownType); }
public void Apply(object value) { if (value is T) { _source.Apply(value); } else { throw RuntimeFailure.TemplateDoesNotSupportOperand("value"); } }
static T CreateInstanceSafe <T>(ITemplate temp, string name) { if (temp == null) { throw RuntimeFailure.TemplateNotFound(name); } var result = Activation.CreateInstance <T>(); temp.Apply(result); return(result); }
public Type Resolve() { var result = Resolver.Resolve(); if (result == null) { // RuntimeWarning.LateBoundTypeFailure(OriginalString, Resolver.ResolveError); // throw Resolver.ResolveError ?? RuntimeFailure.TypeMissing(this); throw RuntimeFailure.TypeMissing(this); } return(result); }
protected virtual void Initialize(object component, IEnumerable <KeyValuePair <string, object> > values, IServiceProvider serviceProvider = null) { if (component == null) { throw new ArgumentNullException(nameof(component)); } if (values == null) { return; } serviceProvider = serviceProvider ?? ServiceProvider.Null; var exceptionHandler = serviceProvider.GetServiceOrDefault( Activation.IgnoreErrors ); var props = Template.GetPropertyCache(component); foreach (var kvp in values.Distinct(KeyComparer)) { PropertyInfo pd = props.GetValueOrDefault(kvp.Key); if (pd == null) { exceptionHandler(null, RuntimeFailure.PropertyMissing(kvp.Key)); continue; } if (pd.SetMethod == null || !pd.SetMethod.IsPublic) { var dest = pd.GetValue(component); Template.DefaultCopyContent(kvp.Value, dest); continue; } object defaultValue = kvp.Value; try { // Conversion from string var text = defaultValue as string; if (text != null) { defaultValue = Activation.FromText(pd.PropertyType, text); } pd.SetValue(component, defaultValue); } catch (Exception ex) { exceptionHandler(null, ex); } } }
public IPropertyProvider AddNew(string name, object value = null, TypeReference type = null) { if (value == null && type == null) { throw RuntimeFailure.DataProviderTypeOrValueNotBoth(); } if (value != null) { return(AddOne(name, PropertyProvider.FromValue(value))); } return(AddOne(name, PropertyProvider.LateBound(type))); }
public void SetProperty(string property, object value) { PropertyProvider.CheckProperty(property); PropertyInfo pd = _GetProperty(property); if (pd == null) { throw RuntimeFailure.PropertyNotFound(nameof(property), property); } if (pd.GetValue(ObjectContext) != value) { pd.SetValue(ObjectContext, value); } }
internal static Type VerifyConcreteClass(Type sourceType, Type resultType) { if (resultType == null) { return(null); } var result = resultType.GetTypeInfo(); if (result != null && (result.IsAbstract || result.IsInterface || !sourceType.GetTypeInfo().IsAssignableFrom(result))) { throw RuntimeFailure.ConcreteClassError(resultType); } return(resultType); }
bool ICollection <KeyValuePair <string, object> > .Remove(KeyValuePair <string, object> item) { if (string.IsNullOrEmpty(item.Key)) { throw RuntimeFailure.CannotSpecifyNullKey("item"); } object result; if (InnerMap.TryGetValue(item.Key, out result) && Equals(result, item.Value)) { ClearProperty(item.Key); return(true); } return(false); }
internal static IReadOnlyList <AssemblyReference> GetRelatedAssemblyReferences( Assembly assembly, Func <string, bool> fileExists, Func <string, Assembly> loadFile ) { if (assembly == null) { throw new ArgumentNullException(nameof(assembly)); } if (assembly.IsDynamic || assembly.ReflectionOnly || string.IsNullOrEmpty(assembly.CodeBase)) { return(Array.Empty <AssemblyReference>()); } var attributes = assembly.GetCustomAttributes <RelatedAssemblyAttribute>().ToArray(); if (attributes.Length == 0) { return(Array.Empty <AssemblyReference>()); } var assemblyName = assembly.GetName().Name; var assemblyLocation = GetAssemblyLocation(assembly); var assemblyDirectory = Path.GetDirectoryName(assemblyLocation); var relatedAssemblies = new List <AssemblyReference>(attributes.Length); foreach (var attribute in attributes) { if (string.Equals(assemblyName, attribute.AssemblyFileName, StringComparison.OrdinalIgnoreCase)) { throw RuntimeFailure.InvalidSelfRelatedAssembly(assemblyName); } relatedAssemblies.Add(new RelatedAssemblyReference( assembly.GetName(), assemblyDirectory, attribute.AssemblyFileName, fileExists, loadFile )); } return(relatedAssemblies); }
internal static IEnumerable <KeyValuePair <string, string> > ParseKeyValuePairs(string text) { var tokens = ParseTokenizer(text); bool atKey = true; string key = null; string value = null; foreach (var s in tokens) { switch (s) { case "=": atKey = false; if (key == null) { throw RuntimeFailure.PropertiesParseKeyNameExpected(); } break; case ";": atKey = true; if (key != null) { yield return(new KeyValuePair <string, string>(key, value ?? string.Empty)); key = value = null; } break; default: if (atKey) { key = s; } else { value = s; } break; } } if (key != null) { yield return(new KeyValuePair <string, string>(key, value ?? string.Empty)); } }
public static QualifiedName GetQualifiedName(this Type type) { if (type == null) { throw new ArgumentNullException(nameof(type)); } var tt = type.GetTypeInfo(); if (tt.IsGenericParameter || (tt.IsGenericType && !tt.IsGenericTypeDefinition)) { throw RuntimeFailure.QualifiedNameCannotBeGeneratedFromConstructed("type"); } AssemblyInfo ai = AssemblyInfo.GetAssemblyInfo(tt.Assembly); NamespaceUri xmlns = ai.GetXmlNamespace(tt.Namespace); return(xmlns + QualName(type)); }
static Exception CheckArguments(string type, string subtype, IEnumerable <KeyValuePair <string, string> > parameters) { if (string.IsNullOrEmpty(type)) { throw Failure.NullOrEmptyString(nameof(type)); } if (!VALID_TYPES.Contains(type)) { return(RuntimeFailure.ContentTypeNotStandard("type", type)); } if (string.IsNullOrEmpty(subtype)) { throw Failure.NullOrEmptyString(nameof(subtype)); } return(null); }
public DataStreamContext(Uri u) { string[] parts = u.PathAndQuery.Split(new [] { ',' }, 2); if (parts.Length != 2) { throw RuntimeFailure.NotValidDataUri(); } var ct = Regex.Replace(parts[0], ";base64", string.Empty); if (ct.Length == 0) { _contentType = new ContentType("text", "plain"); } else { _contentType = ContentType.Parse(ct); } byte[] buffer; _isBase64 = ct.Length < parts[0].Length; // implied by replacement if (_isBase64) { buffer = Convert.FromBase64String(parts[1]); } else { buffer = System.Text.Encoding.ASCII.GetBytes(WebUtility.UrlDecode(parts[1])); } _baseUri = string.Concat("data:", _contentType, _isBase64 ? ";base64" : string.Empty, ","); _data = new MemoryStream(buffer.Length); _data.Write(buffer, 0, buffer.Length); }
public static object ApplyProperties(this MethodInfo method, object thisArg, IProperties properties) { if (method == null) { throw new ArgumentNullException(nameof(method)); } properties = properties ?? Properties.Empty; var methodParameters = method.GetParameters(); var parms = new object[methodParameters.Length]; int paramIndex = 0; if (method.IsStatic) { if (methodParameters.Length == 0) { throw RuntimeFailure.ApplyPropertiesStaticMethodRequiresArg("method"); } if (thisArg == null) { throw new ArgumentNullException(nameof(thisArg)); } parms[0] = thisArg; paramIndex = 1; if (!methodParameters[0].ParameterType.IsInstanceOfType(thisArg)) { throw RuntimeFailure.ThisArgumentIncorrectType(thisArg.GetType()); } } for (; paramIndex < methodParameters.Length; paramIndex++) { var pi = methodParameters[paramIndex]; parms[paramIndex] = properties.GetProperty(pi.Name); } return(method.Invoke(thisArg, parms)); }
private bool TryBasicFactories <T>(Type type, string adapterRoleName, Func <IAdapterFactory, T> func, out T result) { var roleAsm = AdapterFactory.GetAssemblyThatDefines(adapterRoleName); if (roleAsm == null) { throw RuntimeFailure.AdapterRoleNotDefined("adapterRoleName", adapterRoleName); } // Try assembly factory, factory where the role is defined, then provider factories var asm = AdapterFactory.FromAssembly(type.GetTypeInfo().Assembly) ?? AdapterFactory.Null; result = func(asm); if (result != null) { return(true); } result = func(AdapterFactory.FromAssembly(roleAsm)); if (result != null) { return(true); } // Exclude self, otherwise would be recursive var right = App.GetProviders <IAdapterFactory>().Where(t => t != this); foreach (var m in right) { result = func(m); if (result != null) { return(true); } } return(false); }
public bool TryConvertFromText(string text, Type componentType, IServiceProvider sp, CultureInfo culture, out object result) { result = null; throw RuntimeFailure.NoAvailableTextConversion(componentType); }
public bool Read() { string line = BaseReader.ReadLine(); if (line == null) { return(false); } // This removes preceeding whitespace on continued lines line = line.Trim(); // Skip blank lines while (line.Length == 0) { line = BaseReader.ReadLine(); if (line == null) { return(false); } line = line.Trim(); } // This is a category line if (line.StartsWith("[", StringComparison.Ordinal)) { if (line.EndsWith("]", StringComparison.Ordinal)) { EnterCategory(line); } else { throw RuntimeFailure.PropertiesCategoryMissingBrackets(); } } else { // Either pick this as a comment or a property if (line[0] == ';' || line[0] == '!' || line[0] == '#') { EnterComment(line); } else { StringBuilder buffer = new StringBuilder(); // Deal with line continuations \ // New to 1.3: assume that if a equals sign is missing, it is part // of the previous line while (line != null && line.EndsWith("\\", StringComparison.Ordinal)) { buffer.Append(line, 0, line.Length - 1); line = this.BaseReader.ReadLine(); if (line != null) { line = line.Trim(); } } if (line != null) { buffer.AppendLine(line); } EnterText(buffer.ToString()); } } return(true); }