public void Parse_should_throw_oninvalid_names() { Assert.Throws <ArgumentException>(() => { QualifiedName.Parse("*&Ma^^rio"); }); Assert.Throws <ArgumentException>(() => { QualifiedName.Parse(""); }); Assert.Throws <ArgumentException>(() => { QualifiedName.Parse("[unclosed:curie"); }); Assert.Throws <ArgumentException>(() => { QualifiedName.Parse("unclosed:curie]"); }); }
/// <summary> /// Returns a qualified name from a string /// </summary> /// <param name="value"></param> /// <param name="context"></param> /// <returns></returns> public static QualifiedName ToQualifiedName(this string value, ServiceMessageContext context) { if (string.IsNullOrEmpty(value)) { return(QualifiedName.Null); } if (Uri.TryCreate(value, UriKind.Absolute, out var uri)) { if (string.IsNullOrEmpty(uri.Fragment)) { value = string.Empty; } else { value = uri.Fragment.TrimStart('#'); } var nsUri = uri.NoQueryAndFragment().AbsoluteUri; return(new QualifiedName(string.IsNullOrEmpty(value) ? null : value.UrlDecode(), context.NamespaceUris.GetIndexOrAppend(nsUri))); } try { return(QualifiedName.Parse(value.UrlDecode())); } catch { // Give up return(new QualifiedName(value)); } }
/// <summary> /// Determines PHP type name of an exported PHP type. /// Gets default<QualifiedName> if type is not exported PHP type. /// </summary> public static QualifiedName GetPhpTypeNameOrNull(this PENamedTypeSymbol s) { var attrs = s.GetAttributes(); if (attrs.Length != 0) { for (int i = 0; i < attrs.Length; i++) { if (attrs[i].AttributeClass.MetadataName == "PhpTypeAttribute") { var ctorargs = attrs[i].ConstructorArguments; var tname = ctorargs[0]; var tnamestr = tname.IsNull ? null : tname.DecodeValue <string>(SpecialType.System_String); const string InheritName = "[name]"; if (tnamestr == null) { return(s.MakeQualifiedName()); } else if (tnamestr == InheritName) { return(new QualifiedName(new Name(s.Name))); } else { return(QualifiedName.Parse(tnamestr.Replace(InheritName, s.Name), true)); } } } } return(default(QualifiedName)); }
static Exception _TryParse(string text, IServiceProvider serviceProvider, out TypeReference result) { result = null; if (text == null) { return(new ArgumentNullException("type")); } text = text.Trim(); if (text.Length == 0) { return(Failure.AllWhitespace("text")); } serviceProvider = serviceProvider ?? ServiceProvider.Root; Type builtIn; if (builtInNames.TryGetValue(text, out builtIn)) { result = FromType(builtIn); return(null); } if (text.Contains(":") || text.Contains("{")) { try { QualifiedName qn = QualifiedName.Parse(text, serviceProvider); result = new TypeReference(text, new QualifiedNameResolver(qn)); return(null); } catch (FormatException f) { return(Failure.NotParsable("text", typeof(TypeReference), f)); } } string[] s = text.Split(new [] { ',' }, 2); string typeName = s[0]; if (s.Length == 2) { AssemblyName assemblyName = null; try { assemblyName = new AssemblyName(s[1]); } catch (Exception ex) { return(Failure.NotParsable("text", typeof(TypeReference), ex)); } var resolveThunk = new DefaultResolver(assemblyName, typeName); result = new TypeReference(text, resolveThunk); return(null); } else { var resolveThunk = new SlowResolver(typeName); result = new TypeReference(text, resolveThunk); return(null); } }
public void Parse_should_parse_expanded_names() { QualifiedName qn = QualifiedName.Parse("{http://ns.example.com/mushroom-kingdom} Mario"); Assert.Equal("Mario", qn.LocalName); Assert.Equal("http://ns.example.com/mushroom-kingdom", qn.NamespaceName); }
public async Task <NamedTemplate> TryGetGlobalTemplateAsync(string templateName) { var name = QualifiedName.Parse(templateName); using (var raft = Factory.CreateRaftRepository(name.Namespace ?? RaftRepository.DefaultName, OpenRaftOptions.ReadOnly | OpenRaftOptions.OptimizeLoadTime)) { if (raft != null) { var rubbish = await raft.GetRaftItemsAsync(); var template = await raft.GetRaftItemAsync(RaftItemType.Module, name.Name + ".otter"); if (template != null) { using (var stream = await raft.OpenRaftItemAsync(RaftItemType.Module, template.ItemName, FileMode.Open, FileAccess.Read)) { var results = Compiler.Compile(stream); if (results.Script != null) { return(results.Script.Templates.Values.FirstOrDefault()); } else { throw new ExecutionFailureException($"Error processing template {name}: {string.Join(Environment.NewLine, results.Errors)}"); } } } } } return(null); }
public void Parse_should_parse_curie_syntax() { var resolver = ServiceProvider.FromValue(new FakeXmlNamespaceResolver()); QualifiedName qn = QualifiedName.Parse("[example:a]", resolver); Assert.Equal("a", qn.LocalName); Assert.Equal("http://ns.example.com", qn.NamespaceName); }
public void EncodeQualifiedName() { var val = QualifiedName.Parse("4:Test"); EncodeDecode( e => e.WriteQualifiedName(null, val), d => d.ReadQualifiedName(null)) .Should().BeEquivalentTo(val, options => options.ComparingByMembers <QualifiedName>()); }
public void QualifiedNameParseTestMethod3() { QualifiedName _qn = QualifiedName.Parse("Name"); //Cannot find information that the NamespaceIndex is optional Assert.IsNotNull(_qn); Assert.AreEqual <int>(_qn.NamespaceIndex, 0); Assert.IsFalse(_qn.NamespaceIndexSpecified); Assert.AreEqual <string>(_qn.Name, "Name"); }
public void GetTypeByQualifiedName_get_type_from_qualified_name_open_generic_type() { var open = typeof(AdapterFactory <>); string fullName = string.Format("{{{0}}} AdapterFactory-1", Xmlns.Core2008); Assert.Equal(fullName, open.GetQualifiedName().ToString()); Assert.Equal(open, App.GetTypeByQualifiedName(QualifiedName.Parse(fullName))); }
public void GetQualifiedName_get_type_from_qualified_name_nested_types() { var nested = typeof(TypeReference).GetNestedType("TrivialResolver", BindingFlags.NonPublic); string fullName = string.Format("{{{0}}} TypeReference.TrivialResolver", Xmlns.Core2008); Assert.Equal(fullName, nested.GetQualifiedName().ToString()); Assert.Equal(nested, App.GetTypeByQualifiedName(QualifiedName.Parse(fullName))); }
public async Task <Result> CompileAndRun(string source, CancellationToken token) { var result = new Result(); using var assemblyStream = new MemoryStream(); using var csharpStream = new MemoryStream(); var compilationResult = _assemblyCompiler.CompileAssembly( _assemblyFactory.FromSource( QualifiedName.Parse("WebIde"), (0, 0, null), ImmutableArray <IAssembly> .Empty, ImmutableArray.Create(DocumentFactory.FromString(source))), assemblyStream, csharpStream, cancellationToken: token); await Task.Yield(); token.ThrowIfCancellationRequested(); if (compilationResult.AssemblyDiagnostics.Any()) { result.Diagnostics = compilationResult .AssemblyDiagnostics; } else { csharpStream.Position = 0; result.EmittedCSharp = CSharpSyntaxTree.ParseText(SourceText.From(csharpStream)).GetRoot().NormalizeWhitespace().ToFullString(); await Task.Yield(); token.ThrowIfCancellationRequested(); try { var assembly = Assembly.Load(assemblyStream.ToArray()); await Task.Yield(); token.ThrowIfCancellationRequested(); var entryPoint = assembly.EntryPoint; if (entryPoint != null) { result.RunResult = entryPoint.Invoke(null, null)?.ToString() ?? ""; } } catch (Exception e) { result.RuntimeError = e.ToString(); } } return(result); }
/// <summary> /// Determines PHP type name of an exported PHP type. /// Gets default<QualifiedName> if type is not exported PHP type. /// </summary> public static QualifiedName GetPhpTypeNameOrNull(this PENamedTypeSymbol s) { if (TryGetPhpTypeAttribute(s, out var tname, out var fname)) { return(tname != null ? QualifiedName.Parse(tname, true) : s.MakeQualifiedName()); } return(default);
public void Parse_should_expand_empty_prefix() { IDictionary <string, string> lookup = new Dictionary <string, string>(); lookup.Add("", null); QualifiedName qn = QualifiedName.Parse(":Mario", MakeResolver(lookup)); Assert.Equal(NamespaceUri.Default.NamespaceName, qn.Namespace.NamespaceName); Assert.Equal("Mario", qn.LocalName); }
public void GetTypeByQualifiedName_get_type_from_qualified_name_nominal() { string fullName = string.Format("{{{0}}} TypeReference", Xmlns.Core2008); Assert.Equal(typeof(TypeReference), App.GetTypeByQualifiedName(QualifiedName.Parse(fullName))); TypeReference tr = TypeReference.Parse(fullName); Assert.Equal(typeof(TypeReference), tr.Resolve()); }
public void ToString_should_format() { QualifiedName qn = QualifiedName.Parse("{http://ns.example.com/mushroom-kingdom} Mario"); Assert.Equal("{http://ns.example.com/mushroom-kingdom} Mario", qn.ToString()); Assert.Equal("{http://ns.example.com/mushroom-kingdom} Mario", qn.ToString("F")); Assert.Equal("Mario", qn.ToString("S")); Assert.Equal("http://ns.example.com/mushroom-kingdom", qn.ToString("N")); Assert.Equal("{http://ns.example.com/mushroom-kingdom}", qn.ToString("m")); }
public void Parse_should_expand_using_prefix_lookup() { IDictionary <string, string> lookup = new Dictionary <string, string> { { "mk", MUSHROOM_KINGDOM } }; QualifiedName qn = QualifiedName.Parse("mk:Mario", MakeResolver(lookup)); Assert.Equal(MUSHROOM_KINGDOM, qn.Namespace.NamespaceName); Assert.Equal("Mario", qn.LocalName); }
public override object ConvertFromString(string text, Type destinationType, IValueSerializerContext context) { string s = text; if (s != null) { return(QualifiedName.Parse(s, context)); } return(base.ConvertFromString(text, destinationType, context)); }
public void SetProperty_should_apply_to_IPropertiesContainer() { var def = PropertyTreeDefinition.FromType(typeof(IPropertiesContainer)); var indexer = def.Properties.OfType <IndexerUsingIPropertiesPropertyDefinition>().FirstOrDefault(); Assert.NotNull(indexer); var it = new FakePropertiesContainer(); indexer.SetValue(it, QualifiedName.Parse("a"), "hello"); Assert.Equal("hello", it.Properties["a"]); }
/// <summary> /// Provides a mechanism to assemble a fully qualified Area name in a hierarchical space. /// </summary> /// <param name="szAreaName">The name of an Area at the current level, obtained from the string enumerator returned by BrowseOPCAreas with a BrowseFilterType of OPC_AREA</param> /// <param name="pszQualifiedAreaName">Where to return the resulting fully qualified area name.</param> public void GetQualifiedAreaName(string szAreaName, out string pszQualifiedAreaName) { pszQualifiedAreaName = String.Empty; try { pszQualifiedAreaName = szAreaName; // Make sure the stack is not null INode parent = m_browseStack.Peek(); if (parent == null) { throw ComUtils.CreateComException(ResultIds.E_FAIL); } // And make sure this is avalid Area name at the level INode child = FindChildByName(parent.NodeId, szAreaName); if (child == null) { throw ComUtils.CreateComException(ResultIds.E_INVALIDARG); } pszQualifiedAreaName = ""; INode[] stack = m_browseStack.ToArray(); for (int i = stack.Length - 2; i >= 0; i--) { // Translate the server namespace index in browsename to the corresponding client namespace index QualifiedName QName = stack[i].BrowseName; QualifiedName translatedName = new QualifiedName(QName.Name, (ushort)m_server.ServerMappingTable[QName.NamespaceIndex]); if (pszQualifiedAreaName.Length != 0) { pszQualifiedAreaName = pszQualifiedAreaName + "/" + translatedName.ToString(); } else { pszQualifiedAreaName = translatedName.ToString(); } } //Also translate the areaname QualifiedName QualifiedAreaName = QualifiedName.Parse(szAreaName); QualifiedName TranslatedAreaName = new QualifiedName(QualifiedAreaName.Name, (ushort)m_server.ServerMappingTable[QualifiedAreaName.NamespaceIndex]); pszQualifiedAreaName = pszQualifiedAreaName + "/" + TranslatedAreaName.ToString(); } catch (COMException e) { throw ComUtils.CreateComException(e); } catch (Exception e) { Utils.Trace(e, "Unexpected error in GetQualifiedAreaName"); throw ComUtils.CreateComException(e); } }
public static IQualifiedName ToQualifiedName(this HtmlNode self) { if (self == null) { throw new ArgumentNullException("self"); } var formattedName = self.Name != null? self.Name.Replace("<", string.Empty).Replace(">", string.Empty).Trim() : null; return(formattedName != null? QualifiedName.Parse(formattedName) : null); }
public ItemInfo(string id, string name, DataType type, int dimension, string address) { this.ID = id; this.Name = name; this.Type = type; this.Dimension = dimension; if (string.IsNullOrEmpty(address)) { Node = NodeId.Null; } else if (address.StartsWith(Objects) || address.StartsWith(Views)) { Node = null; if (address.StartsWith(Objects)) { StartingNode = NodeId.Parse(ObjectIds.ObjectsFolder); string path = address.Substring(Objects.Length); List <string> components = GetComponents(path); RelativePath = new RelativePath() { Elements = components.Select(comp => new RelativePathElement() { TargetName = QualifiedName.Parse(comp) }).ToArray() }; } else { StartingNode = NodeId.Parse(ObjectIds.ViewsFolder); string path = address.Substring(Views.Length); List <string> components = GetComponents(path); RelativePath = new RelativePath() { Elements = components.Select(comp => new RelativePathElement() { TargetName = QualifiedName.Parse(comp) }).ToArray() }; } } else { Node = NodeId.Parse(address); } }
public MetadataNamedInterface( InterfaceAttribute attribute, SourceSymbolContext sourceSymbolContext, DiagnosticBag diagnostics) : base(diagnostics) { _anonymousSourceInterface = new SourceAnonymousInterface( Utils.Parse( attribute.AnonymousInterfaceDeclaration, p => p.anonymous_interface_declaration_metadata().anonymous_interface_declaration(), _diagnostics), sourceSymbolContext.WithTypeParameters(() => TypeParameters), true, _diagnostics); _attribute = attribute; _sourceSymbolContext = sourceSymbolContext; FullyQualifiedName = QualifiedName.Parse(attribute.FullyQualifiedName); _typeParameters = new Lazy <ImmutableArray <ITypeParameter> >(GenerateTypeParameters); }
/// <summary> /// Returns a qualified name from a string /// </summary> /// <param name="value"></param> /// <param name="context"></param> /// <returns></returns> public static QualifiedName ToQualifiedName(this string value, ServiceMessageContext context) { if (string.IsNullOrEmpty(value)) { return(QualifiedName.Null); } string nsUri = null; if (Uri.TryCreate(value, UriKind.Absolute, out var uri)) { if (string.IsNullOrEmpty(uri.Fragment)) { value = string.Empty; } else { value = uri.Fragment.TrimStart('#'); } nsUri = uri.NoQueryAndFragment().AbsoluteUri; } else { // Not a real namespace uri - split and decode var parts = value.Split('#'); if (parts.Length == 2) { nsUri = parts[0]; value = parts[1]; } } if (nsUri != null) { return(new QualifiedName(string.IsNullOrEmpty(value) ? null : value.UrlDecode(), context.NamespaceUris.GetIndexOrAppend(nsUri))); } try { return(QualifiedName.Parse(value.UrlDecode())); } catch { // Give up return(new QualifiedName(value)); } }
/// <summary> /// Determines PHP type name of an exported PHP type. /// Gets default<QualifiedName> if type is not exported PHP type. /// </summary> public static QualifiedName GetPhpTypeNameOrNull(this PENamedTypeSymbol s) { var attrs = s.GetAttributes(); if (attrs.Length != 0) { for (int i = 0; i < attrs.Length; i++) { if (attrs[i].AttributeClass.MetadataName == "PhpTypeAttribute") { var ctorargs = attrs[i].ConstructorArguments; var tname = ctorargs[0]; return(tname.IsNull ? s.MakeQualifiedName() : QualifiedName.Parse(tname.DecodeValue <string>(SpecialType.System_String), true)); } } } return(default(QualifiedName)); }
static void WriteException(TextWriter output, string[] types, string pdesc) { if (string.IsNullOrWhiteSpace(pdesc) || types == null) { return; } // for (int i = 0; i < types.Length; i++) { var t = types[i]; output.Write("<exception cref=\""); output.Write(XmlEncode(QualifiedName.Parse(t, true).ClrName())); // TODO: CommentIdResolver.GetId(..) // TODO: translate correctly using current naming context output.Write('\"'); output.Write('>'); output.Write(XmlEncode(pdesc)); output.WriteLine("</exception>"); } }
public static IEnumerable <IAttribute> ToAttributes(this HtmlNode self, INode parent) { if (self == null) { throw new ArgumentNullException("self"); } if (parent == null) { throw new ArgumentNullException("parent"); } var attributes = new List <IAttribute>(); foreach (var node in self.Attributes.OfType <HtmlAttribute>()) { var name = QualifiedName.Parse(node.Name); var attribute = Attribute.Parse(parent, name, node.Value); attributes.Add(attribute); } return(attributes); }
private ValueTask <IAssembly> LoadDependencyAsync( AssemblyLoadContext assemblyLoadContext, Reference reference, IEnumerable <IAssembly> alreadyLoadedProjects, ProjectInfo project, CancellationToken cancellationToken) { if (reference.Type == Project) { var name = QualifiedName.Parse(reference.Name); var assembly = alreadyLoadedProjects.FirstOrDefault(x => x.Name == name) ?? throw new InvalidOperationException($"{name} is a dependency of {project}, so must be built first"); return(new ValueTask <IAssembly>(assembly)); } Release.Assert(reference.Version != null); return(new ValueTask <IAssembly>(LoadDependencyAsync( assemblyLoadContext, new Dependency(reference.Name, reference.Version), cancellationToken))); }
public TargetProviderDirective CreateTargetProvider(Type providerType, PropertyTreeNavigator nav) { var serviceProvider = parent.GetBasicServices(nav); if (nav.IsProperty) { string text = nav.Value.ToString(); Exception error; try { var qn = QualifiedName.Parse(text, serviceProvider); return(new TargetProviderDirective { Name = qn }); } catch (ArgumentException e) { error = e; } catch (FormatException e) { error = e; } Errors.BadTargetProviderDirective(error, nav.FileLocation); return(null); } else { try { return(nav.Bind <TargetProviderDirective>()); } catch (Exception ex) { if (Failure.IsCriticalException(ex)) { throw; } Errors.BadTargetProviderDirective(ex, nav.FileLocation); return(null); } } }
public void UpdateWithDifferentNodeIdTest() { Mock <IAddressSpaceBuildContext> _asMock = new Mock <IAddressSpaceBuildContext>(); QualifiedName qualifiedName = QualifiedName.Parse("EURange"); IUANodeContext _newNode = new UANodeContext(NodeId.Parse("ns=1;i=11"), _asMock.Object); Assert.AreEqual <string>("ns=1;i=11", _newNode.NodeIdContext.ToString()); UANode _nodeFactory = new UAVariable() { NodeId = "ns=1;i=47", BrowseName = "EURange", ParentNodeId = "ns=1;i=43", DataType = "i=884", DisplayName = new XML.LocalizedText[] { new XML.LocalizedText() { Value = "EURange" } } }; _newNode.Update(_nodeFactory, x => Assert.Fail()); // Update has different NodeId - no change is expected. Assert.AreEqual <string>("ns=1;i=11", _newNode.NodeIdContext.ToString()); Assert.AreEqual <string>("ns=1;i=47", _newNode.UANode.NodeId); }