コード例 #1
0
 public TestEnvironment()
 {
     _testFolder         = new TemporaryFolder("WritingSystemMigratorTests");
     _wsPrefsFilePath    = Path.Combine(_testFolder.Path, "WritingSystemPrefs.xml");
     _writingSystemsPath = Path.Combine(_testFolder.Path, "WritingSystems");
     Directory.CreateDirectory(WritingSystemsPath);
     _namespaceManager = new XmlNamespaceManager(new NameTable());
     NamespaceManager.AddNamespace("palaso", "urn://palaso.org/ldmlExtensions/v1");
 }
コード例 #2
0
ファイル: Log4JParser.cs プロジェクト: ARLM-Attic/harvester
        public Log4JParser(IRetrieveProcesses processRetriever, IHaveExtendedProperties extendedProperties)
            : base(processRetriever, "log4j", "http://logging.apache.org/log4j/")
        {
            Verify.NotNull(extendedProperties, "extendedProperties");

            //NOTE: NLog extends standard log4j XML structure with custom NLog namespace; add `nlog` namespace to the XML namespace manager to
            //      allow the XML document to be parsed if originated from NLog even though we are only interested in the core log4j elements.
            NamespaceManager.AddNamespace("nlog", "http://nlog-project.org/log4j/");
        }
コード例 #3
0
        public async Task <ActionResult> Index()
        {
            // Instantiate the XmlElementSignatureStarter class, responsible for receiving the signature
            // elements and start the signature process.
            var signatureStarter = new FullXmlSignatureStarter(Util.GetRestPkiClient());

            // Set the XML to be signed, a sample XML Document.
            signatureStarter.SetXml(StorageMock.GetSampleXmlDocumentPath());

            // Set the signature policy.
            signatureStarter.SetSignaturePolicy(StandardXmlSignaturePolicies.XadesBes);

            // Set the security context to be used to determine trust in the certificate chain. We have
            // encapsulated the security context choice on Util.cs.
            signatureStarter.SetSecurityContext(Util.GetSecurityContextId());

            // Set the location on which to insert the signature node. If the location is not specified, the
            // signature will appended to the root element (which is most usual with enveloped signatures).
            var nsm = new NamespaceManager();

            nsm.AddNamespace("ls", "http://www.lacunasoftware.com/sample");
            signatureStarter.SetSignatureElementLocation("//ls:signaturePlaceholder", XmlInsertionOptions.AppendChild, nsm);

            // Call the StartWithWebPki() method, which initiates the signature. This yields the token,
            // a 43-character case-sensitive URL-safe string, which identifies this signature process. We'll
            // use this value to call the signWithRestPki() method on the Web PKI component (see
            // signature-form.js) and also to complete the signature on the POST action below (this should
            // not be mistaken with the API access token).
            var token = await signatureStarter.StartWithWebPkiAsync();

            // The token acquired above can only be used for a single signature attempt. In order to retry
            // the signature it is necessary to get a new token. This can be a problem if the user uses the
            // back button of the browser, since the browser might show a cached page that we rendered
            // previously, with a now stale token. To prevent this from happening, we call the method
            // SetNoCacheHeaders() (in BaseController) which sets HTTP headers to prevent caching of the
            // page.
            base.SetNoCacheHeaders();

            // Render the signature page with the token obtained from REST PKI.
            return(View(new SignatureModel()
            {
                Token = token
            }));
        }
コード例 #4
0
        public ActionResult Index()
        {
            // Instantiate the XmlElementSignatureStarter class, responsible for receiving the signature elements and start the
            // signature process
            var signatureStarter = new FullXmlSignatureStarter(Util.GetRestPkiClient());

            // Set the XML to be signed, a sample XML Document
            signatureStarter.SetXml(Util.GetSampleXmlDocument());

            // Set the signature policy
            signatureStarter.SetSignaturePolicy(StandardXmlSignaturePolicies.XadesBes);

            // Set a SecurityContext to be used to determine trust in the certificate chain
            signatureStarter.SetSecurityContext(StandardSecurityContexts.PkiBrazil);
            // Note: By changing the SecurityContext above you can accept only certificates from a certain PKI, for instance,
            // ICP-Brasil (\Lacuna\StandardSecurityContexts::PKI_BRAZIL).

            // Set the location on which to insert the signature node. If the location is not specified, the signature will appended
            // to the root element (which is most usual with enveloped signatures).
            var nsm = new NamespaceManager();

            nsm.AddNamespace("ls", "http://www.lacunasoftware.com/sample");
            signatureStarter.SetSignatureElementLocation("//ls:signaturePlaceholder", Api.XmlSignature.XmlInsertionOptions.AppendChild, nsm);

            // Call the StartWithWebPki() method, which initiates the signature. This yields the token, a 43-character
            // case-sensitive URL-safe string, which identifies this signature process. We'll use this value to call the
            // signWithRestPki() method on the Web PKI component (see javascript on the view) and also to complete the signature
            // on the POST action below (this should not be mistaken with the API access token).
            var token = signatureStarter.StartWithWebPki();

            // The token acquired above can only be used for a single signature attempt. In order to retry the signature it is
            // necessary to get a new token. This can be a problem if the user uses the back button of the browser, since the
            // browser might show a cached page that we rendered previously, with a now stale token. To prevent this from happening,
            // we call the method SetNoCacheHeaders() (in BaseController) which sets HTTP headers to prevent caching of the page.
            base.SetNoCacheHeaders();

            // Render the signature page with the token obtained from REST PKI
            return(View(new XmlSignatureModel()
            {
                Token = token
            }));
        }
コード例 #5
0
		public ActionResult Index() {

			// Instantiate the XmlElementSignatureStarter class, responsible for receiving the signature elements and start the
			// signature process
			var signatureStarter = new FullXmlSignatureStarter(Util.GetRestPkiClient());

			// Set the XML to be signed, a sample XML Document
			signatureStarter.SetXml(Util.GetSampleXmlDocument());

			// Set the signature policy
			signatureStarter.SetSignaturePolicy(StandardXmlSignaturePolicies.XadesBes);

			// Set a SecurityContext to be used to determine trust in the certificate chain
			signatureStarter.SetSecurityContext(StandardSecurityContexts.PkiBrazil);
			// Note: By changing the SecurityContext above you can accept only certificates from a certain PKI, for instance,
			// ICP-Brasil (\Lacuna\StandardSecurityContexts::PKI_BRAZIL).

			// Set the location on which to insert the signature node. If the location is not specified, the signature will appended
			// to the root element (which is most usual with enveloped signatures).
			var nsm = new NamespaceManager();
			nsm.AddNamespace("ls", "http://www.lacunasoftware.com/sample");
			signatureStarter.SetSignatureElementLocation("//ls:signaturePlaceholder", Api.XmlSignature.XmlInsertionOptions.AppendChild, nsm);

			// Call the StartWithWebPki() method, which initiates the signature. This yields the token, a 43-character
			// case-sensitive URL-safe string, which identifies this signature process. We'll use this value to call the
			// signWithRestPki() method on the Web PKI component (see javascript on the view) and also to complete the signature
			// on the POST action below (this should not be mistaken with the API access token).
			var token = signatureStarter.StartWithWebPki();

			// The token acquired above can only be used for a single signature attempt. In order to retry the signature it is
			// necessary to get a new token. This can be a problem if the user uses the back button of the browser, since the
			// browser might show a cached page that we rendered previously, with a now stale token. To prevent this from happening,
			// we call the method SetNoCacheHeaders() (in BaseController) which sets HTTP headers to prevent caching of the page.
			base.SetNoCacheHeaders();

			// Render the signature page with the token obtained from REST PKI
			return View(new XmlSignatureModel() {
				Token = token
			});
		}
コード例 #6
0
        public override void Validate(object state)
        {
            base.Validate(state);

            //if (XPath.IsNull())
            //    throw new ChoRecordConfigurationException("XPath can't be null or whitespace.");

            if (XPath.IsNullOrWhiteSpace())
            {
                if (!IsDynamicObject && (RecordType.IsGenericType && RecordType.GetGenericTypeDefinition() == typeof(KeyValuePair <,>)))
                {
                    NodeName = NodeName.IsNullOrWhiteSpace() ? "KeyValuePair" : NodeName;
                    RootName = RootName.IsNullOrWhiteSpace() ? "KeyValuePairs" : RootName;
                }
                else if (!IsDynamicObject && !typeof(IChoScalarObject).IsAssignableFrom(RecordType))
                {
                    NodeName = NodeName.IsNullOrWhiteSpace() ? RecordType.Name : NodeName;
                    RootName = RootName.IsNullOrWhiteSpace() ? NodeName.ToPlural() : RootName;
                }
            }
            else
            {
                RootName = RootName.IsNullOrWhiteSpace() ? XPath.SplitNTrim("/").Where(t => !t.IsNullOrWhiteSpace() && t.NTrim() != "." && t.NTrim() != ".." && t.NTrim() != "*").FirstOrDefault() : RootName;
                NodeName = NodeName.IsNullOrWhiteSpace() ? XPath.SplitNTrim("/").Where(t => !t.IsNullOrWhiteSpace() && t.NTrim() != "." && t.NTrim() != ".." && t.NTrim() != "*").Skip(1).FirstOrDefault() : NodeName;
            }

            string rootName = null;
            string nodeName = null;
            ChoXmlDocumentRootAttribute da = TypeDescriptor.GetAttributes(RecordType).OfType <ChoXmlDocumentRootAttribute>().FirstOrDefault();

            if (da != null)
            {
                rootName = da.Name;
            }
            else
            {
                XmlRootAttribute ra = TypeDescriptor.GetAttributes(RecordType).OfType <XmlRootAttribute>().FirstOrDefault();
                if (ra != null)
                {
                    nodeName = ra.ElementName;
                }
            }

            RootName = RootName.IsNullOrWhiteSpace() && !rootName.IsNullOrWhiteSpace() ? rootName : RootName;
            NodeName = NodeName.IsNullOrWhiteSpace() && !nodeName.IsNullOrWhiteSpace() ? nodeName : NodeName;

            RootName = RootName.IsNullOrWhiteSpace() && !NodeName.IsNullOrWhiteSpace() ? NodeName.ToPlural() : RootName;
            if (!RootName.IsNullOrWhiteSpace() && RootName.ToSingular() != RootName)
            {
                NodeName = NodeName.IsNullOrWhiteSpace() && !RootName.IsNullOrWhiteSpace() ? RootName.ToSingular() : NodeName;
            }

            if (RootName.IsNullOrWhiteSpace())
            {
                RootName = "Root";
            }
            if (NodeName.IsNullOrWhiteSpace())
            {
                NodeName = "XElement";
            }

            //Encode Root and node names
            RootName = System.Net.WebUtility.HtmlEncode(RootName);
            NodeName = System.Net.WebUtility.HtmlEncode(NodeName);

            string[] fieldNames = null;
            XElement xpr        = null;

            if (state is Tuple <long, XElement> )
            {
                xpr = ((Tuple <long, XElement>)state).Item2;
            }
            else
            {
                fieldNames = state as string[];
            }

            if (AutoDiscoverColumns &&
                XmlRecordFieldConfigurations.Count == 0)
            {
                if (RecordType != null && !IsDynamicObject &&
                    ChoTypeDescriptor.GetProperties(RecordType).Where(pd => pd.Attributes.OfType <ChoXmlNodeRecordFieldAttribute>().Any()).Any())
                {
                    DiscoverRecordFields(RecordType);
                }
                else if (xpr != null)
                {
                    XmlRecordFieldConfigurations.AddRange(DiscoverRecordFieldsFromXElement(xpr));
                }
                else if (!fieldNames.IsNullOrEmpty())
                {
                    foreach (string fn in fieldNames)
                    {
                        if (IgnoredFields.Contains(fn))
                        {
                            continue;
                        }

                        if (fn.StartsWith("_"))
                        {
                            string fn1 = fn.Substring(1);
                            var    obj = new ChoXmlRecordFieldConfiguration(fn, xPath: $"./{fn1}");
                            obj.FieldName      = fn1;
                            obj.IsXmlAttribute = true;
                            XmlRecordFieldConfigurations.Add(obj);
                        }
                        else if (fn.EndsWith("_"))
                        {
                            string fn1 = fn.Substring(0, fn.Length - 1);
                            var    obj = new ChoXmlRecordFieldConfiguration(fn, xPath: $"./{fn1}");
                            obj.FieldName  = fn1;
                            obj.IsXmlCDATA = true;
                            XmlRecordFieldConfigurations.Add(obj);
                        }
                        else
                        {
                            var obj = new ChoXmlRecordFieldConfiguration(fn, xPath: $"./{fn}");
                            XmlRecordFieldConfigurations.Add(obj);
                        }
                    }
                }
            }
            else
            {
                IsComplexXPathUsed = false;

                foreach (var fc in XmlRecordFieldConfigurations)
                {
                    if (fc.IsArray == null)
                    {
                        fc.IsArray = typeof(ICollection).IsAssignableFrom(fc.FieldType);
                    }

                    if (fc.FieldName.IsNullOrWhiteSpace())
                    {
                        fc.FieldName = fc.Name;
                    }

                    if (fc.XPath.IsNullOrWhiteSpace())
                    {
                        fc.XPath = $"/{fc.FieldName}|/@{fc.FieldName}";
                    }
                    else
                    {
                        if (fc.XPath == fc.FieldName ||
                            fc.XPath == $"/{fc.FieldName}" || fc.XPath == $"/{fc.FieldName}" || fc.XPath == $"/{fc.FieldName}" ||
                            fc.XPath == $"/@{fc.FieldName}" || fc.XPath == $"/@{fc.FieldName}" || fc.XPath == $"/@{fc.FieldName}"
                            )
                        {
                        }
                        else
                        {
                            IsComplexXPathUsed = true;
                            fc.UseCache        = false;
                        }
                    }
                }
            }

            if (XmlRecordFieldConfigurations.Count <= 0)
            {
                throw new ChoRecordConfigurationException("No record fields specified.");
            }

            //Validate each record field
            foreach (var fieldConfig in XmlRecordFieldConfigurations)
            {
                fieldConfig.Validate(this);
            }

            //Check field position for duplicate
            string[] dupFields = XmlRecordFieldConfigurations.GroupBy(i => i.Name)
                                 .Where(g => g.Count() > 1)
                                 .Select(g => g.Key).ToArray();

            if (dupFields.Length > 0)
            {
                throw new ChoRecordConfigurationException("Duplicate field(s) [Name(s): {0}] found.".FormatString(String.Join(",", dupFields)));
            }

            PIDict = new Dictionary <string, System.Reflection.PropertyInfo>();
            PDDict = new Dictionary <string, PropertyDescriptor>();
            foreach (var fc in XmlRecordFieldConfigurations)
            {
                var pd1 = fc.DeclaringMember.IsNullOrWhiteSpace() ? ChoTypeDescriptor.GetProperty(RecordType, fc.Name)
                    : ChoTypeDescriptor.GetProperty(RecordType, fc.DeclaringMember);
                if (pd1 != null)
                {
                    fc.PropertyDescriptor = pd1;
                }

                if (fc.PropertyDescriptor == null)
                {
                    fc.PropertyDescriptor = TypeDescriptor.GetProperties(RecordType).AsTypedEnumerable <PropertyDescriptor>().Where(pd => pd.Name == fc.Name).FirstOrDefault();
                }
                if (fc.PropertyDescriptor == null)
                {
                    continue;
                }

                PIDict.Add(fc.Name, fc.PropertyDescriptor.ComponentType.GetProperty(fc.PropertyDescriptor.Name));
                PDDict.Add(fc.Name, fc.PropertyDescriptor);
            }

            RecordFieldConfigurationsDict = XmlRecordFieldConfigurations.OrderBy(c => c.IsXmlAttribute).Where(i => !i.Name.IsNullOrWhiteSpace()).ToDictionary(i => i.Name);

            if (XmlRecordFieldConfigurations.Where(e => e.IsNullable).Any() ||
                NullValueHandling == ChoNullValueHandling.Default)
            {
                if (NamespaceManager != null)
                {
                    if (!NamespaceManager.HasNamespace("xsi"))
                    {
                        NamespaceManager.AddNamespace("xsi", ChoXmlSettings.XmlSchemaInstanceNamespace);
                    }
                    if (!NamespaceManager.HasNamespace("xsd"))
                    {
                        NamespaceManager.AddNamespace("xsd", ChoXmlSettings.XmlSchemaNamespace);
                    }
                }
            }

            LoadNCacheMembers(XmlRecordFieldConfigurations);
        }
コード例 #7
0
    public static void Main(string[] args)
    {
        Opts opts = new Opts();

        opts.ProcessArgs(args);
        if (opts.RemainingArguments.Length != 2 && opts.RemainingArguments.Length != 3)
        {
            opts.DoHelp();
            return;
        }

        string datasource, rootentity, stylesheetfile;

        if (opts.RemainingArguments.Length == 2)
        {
            datasource     = opts.RemainingArguments[0];
            rootentity     = null;
            stylesheetfile = opts.RemainingArguments[1];
        }
        else
        {
            datasource     = opts.RemainingArguments[0];
            rootentity     = opts.RemainingArguments[1];
            stylesheetfile = opts.RemainingArguments[2];
        }

        XsltArgumentList xsltargs = new XsltArgumentList();

        if (opts.param != null)
        {
            foreach (string p in opts.param)
            {
                int eq = p.IndexOf('=');
                if (eq == -1)
                {
                    Console.Error.WriteLine("Param arguments must be name=value.");
                    return;
                }
                string n = p.Substring(0, eq);
                string v = p.Substring(eq + 1);
                xsltargs.AddParam(n, "", v);
            }
        }

        XmlDocument sty = new XmlDocument();

        sty.PreserveWhitespace = true;
        sty.Load(stylesheetfile);

        XslTransform t = new XslTransform();

        t.Load(sty, null, null);

        NamespaceManager nsmgr = new NamespaceManager();

        // Scan xmlsn: attributes in the stylesheet node.
        // For all namespaces of the form assembly://assemblyname/TypeName, load in
        // the methods of that type as extension functions in that namespace.
        // And add xmlns declarations to nsmgr.
        foreach (XmlAttribute a in sty.DocumentElement.Attributes)
        {
            if (!a.Name.StartsWith("xmlns:"))
            {
                continue;
            }

            nsmgr.AddNamespace(a.Value, a.Name.Substring(6));

            System.Uri uri = new System.Uri(a.Value);
            if (uri.Scheme != "assembly")
            {
                continue;
            }
            System.Reflection.Assembly assembly = System.Reflection.Assembly.Load(uri.Host);
            System.Type ty = assembly.GetType(uri.AbsolutePath.Substring(1));
            if (ty == null)
            {
                Console.Error.WriteLine("Type not found: " + uri);
                return;
            }
            object obj = ty.GetConstructor(new Type[0]).Invoke(new Type[0]);
            xsltargs.AddExtensionObject(a.Value, obj);
        }

        StatementSource source = Store.CreateForInput(datasource);
        Store           model;

        if (source is Store)
        {
            model = (Store)source;
        }
        else
        {
            model = new MemoryStore(source);
        }

        XPathNavigator nav;

        if (rootentity != null)
        {
            nav = new XPathSemWebNavigator(rootentity, model, nsmgr);
        }
        else
        {
            nav = new XPathSemWebNavigator(model, nsmgr);
        }

        t.Transform(nav, xsltargs, Console.Out, null);
    }
コード例 #8
0
        static MetadataStore()
        {
            Namespaces = new NamespaceManager();

            Namespaces.AddNamespace(PhotoshopNS, "photoshop");
            Namespaces.AddNamespace(Iptc4xmpCoreNS, "Iptc4xmpCore");
            Namespaces.AddNamespace(DcNS, "dc");
            Namespaces.AddNamespace(XmpNS, "xmp");
            Namespaces.AddNamespace(XmpidqNS, "xmpidq");
            Namespaces.AddNamespace(XmpRightsNS, "xmpRights");
            Namespaces.AddNamespace(XmpBJNS, "xmpBJ");
            Namespaces.AddNamespace(XmpMMNS, "xmpMM");
            Namespaces.AddNamespace(ExifNS, "exif");
            Namespaces.AddNamespace(TiffNS, "tiff");
            Namespaces.AddNamespace(RdfNS, "rdf");
            Namespaces.AddNamespace(RdfsNS, "rdfs");
            Namespaces.AddNamespace(IViewNS, "mediapro");
        }
コード例 #9
0
        public override void Validate(object state)
        {
            base.Validate(state);

            //if (XPath.IsNull())
            //    throw new ChoRecordConfigurationException("XPath can't be null or whitespace.");

            if (XPath.IsNullOrWhiteSpace())
            {
                if (!IsDynamicObject && (RecordType.IsGenericType && RecordType.GetGenericTypeDefinition() == typeof(KeyValuePair <,>)))
                {
                    NodeName = "KeyValuePair";
                    RootName = "KeyValuePairs";
                }
                else if (!IsDynamicObject && !typeof(IChoScalarObject).IsAssignableFrom(RecordType))
                {
                    NodeName = RecordType.Name;
                    RootName = NodeName.ToPlural();
                }
            }
            else
            {
                RootName = XPath.SplitNTrim("/").Where(t => !t.IsNullOrWhiteSpace() && t.NTrim() != "." && t.NTrim() != ".." && t.NTrim() != "*").FirstOrDefault();
                NodeName = XPath.SplitNTrim("/").Where(t => !t.IsNullOrWhiteSpace() && t.NTrim() != "." && t.NTrim() != ".." && t.NTrim() != "*").Skip(1).FirstOrDefault();
            }

            if (RootName.IsNullOrWhiteSpace())
            {
                ChoXmlDocumentRootAttribute da = TypeDescriptor.GetAttributes(RecordType).OfType <ChoXmlDocumentRootAttribute>().FirstOrDefault();
                if (da != null)
                {
                    NodeName = da.Name;
                }
                if (RootName.IsNullOrWhiteSpace())
                {
                    RootName = "Root";
                }
            }

            if (NodeName.IsNullOrWhiteSpace())
            {
                if (!IsDynamicObject)
                {
                    XmlRootAttribute ra = TypeDescriptor.GetAttributes(RecordType).OfType <XmlRootAttribute>().FirstOrDefault();
                    if (ra != null)
                    {
                        NodeName = ra.ElementName;
                    }
                }

                if (NodeName.IsNullOrWhiteSpace())
                {
                    NodeName = "XElement";
                }
            }

            //Encode Root and node names
            RootName = System.Net.WebUtility.HtmlEncode(RootName);
            NodeName = System.Net.WebUtility.HtmlEncode(NodeName);

            string[] fieldNames = null;
            XElement xpr        = null;

            if (state is Tuple <long, XElement> )
            {
                xpr = ((Tuple <long, XElement>)state).Item2;
            }
            else
            {
                fieldNames = state as string[];
            }

            if (AutoDiscoverColumns &&
                XmlRecordFieldConfigurations.Count == 0)
            {
                if (RecordType != null && !IsDynamicObject &&
                    ChoTypeDescriptor.GetProperties(RecordType).Where(pd => pd.Attributes.OfType <ChoXmlNodeRecordFieldAttribute>().Any()).Any())
                {
                    IsComplexXPathUsed = false;

                    long   startIndex = 0;
                    long   size       = 0;
                    string xpath      = null;
                    bool   useCache   = true;
                    ChoXmlNodeRecordFieldAttribute attr = null;
                    foreach (PropertyDescriptor pd in ChoTypeDescriptor.GetProperties(RecordType).Where(pd => pd.Attributes.OfType <ChoXmlNodeRecordFieldAttribute>().Any()))
                    {
                        //if (!pd.PropertyType.IsSimple())
                        //    throw new ChoRecordConfigurationException("Property '{0}' is not a simple type.".FormatString(pd.Name));

                        attr = ChoTypeDescriptor.GetPropetyAttribute <ChoXmlNodeRecordFieldAttribute>(pd);
                        if (attr.XPath.IsNullOrEmpty())
                        {
                            xpath = $"//{pd.Name}|//@{pd.Name}";
                            IsComplexXPathUsed = true;
                        }
                        else
                        {
                            useCache = false;
                        }

                        var obj = new ChoXmlRecordFieldConfiguration(pd.Name, xpath);
                        obj.FieldType = pd.PropertyType;
                        obj.UseCache  = useCache;
                        //if (!obj.IsCollection)
                        //    obj.IsCollection = typeof(ICollection).IsAssignableFrom(obj.FieldType);
                        XmlRecordFieldConfigurations.Add(obj);

                        startIndex += size;
                    }

                    //RecordLength = startIndex;
                }
                else if (xpr != null)
                {
                    IsComplexXPathUsed = false;
                    ChoXmlNamespaceManager nsMgr = new ChoXmlNamespaceManager(NamespaceManager);

                    Dictionary <string, ChoXmlRecordFieldConfiguration> dict = new Dictionary <string, ChoXmlRecordFieldConfiguration>(StringComparer.CurrentCultureIgnoreCase);
                    string name = null;
                    foreach (var attr in xpr.Attributes())
                    {
                        //if (!attr.Name.NamespaceName.IsNullOrWhiteSpace()) continue;

                        name = GetNameWithNamespace(xpr.Name, attr.Name);

                        if (!dict.ContainsKey(name))
                        {
                            dict.Add(name, new ChoXmlRecordFieldConfiguration(name, $"//@{name}")); // DefaultNamespace.IsNullOrWhiteSpace() ? $"//@{name}" : $"//@{DefaultNamespace}" + ":" + $"{name}") { IsXmlAttribute = true });
                        }
                        else
                        {
                            throw new ChoRecordConfigurationException("Duplicate field(s) [Name(s): {0}] found.".FormatString(name));
                        }
                    }

                    bool hasElements = false;
                    var  z           = xpr.Elements().ToArray();
                    foreach (var ele in xpr.Elements())
                    {
                        name = GetNameWithNamespace(ele.Name);

                        hasElements = true;
                        if (!dict.ContainsKey(name))
                        {
                            dict.Add(name, new ChoXmlRecordFieldConfiguration(name, $"//{name}")); // DefaultNamespace.IsNullOrWhiteSpace() ? $"//{name}" : $"//{DefaultNamespace}" + ":" + $"{name}"));
                        }
                        else
                        {
                            if (dict[name].IsXmlAttribute)
                            {
                                throw new ChoRecordConfigurationException("Duplicate field(s) [Name(s): {0}] found.".FormatString(name));
                            }

                            dict[name].IsArray = true;
                        }
                    }

                    if (!hasElements)
                    {
                        name = xpr.Name.LocalName;
                        dict.Add(name, new ChoXmlRecordFieldConfiguration(name, "text()"));
                    }

                    foreach (ChoXmlRecordFieldConfiguration obj in dict.Values)
                    {
                        XmlRecordFieldConfigurations.Add(obj);
                    }
                }
                else if (!fieldNames.IsNullOrEmpty())
                {
                    foreach (string fn in fieldNames)
                    {
                        var obj = new ChoXmlRecordFieldConfiguration(fn, xPath: $"//{fn}");
                        XmlRecordFieldConfigurations.Add(obj);
                    }
                }
            }
            else
            {
                IsComplexXPathUsed = false;

                foreach (var fc in XmlRecordFieldConfigurations)
                {
                    if (fc.IsArray == null)
                    {
                        fc.IsArray = typeof(ICollection).IsAssignableFrom(fc.FieldType);
                    }

                    if (fc.XPath.IsNullOrWhiteSpace())
                    {
                        fc.XPath = $"//{fc.FieldName}|//@{fc.FieldName}";
                    }
                    else
                    {
                        if (fc.XPath == fc.FieldName ||
                            fc.XPath == $"//{fc.FieldName}" || fc.XPath == $"/{fc.FieldName}" || fc.XPath == $"./{fc.FieldName}" ||
                            fc.XPath == $"//@{fc.FieldName}" || fc.XPath == $"/@{fc.FieldName}" || fc.XPath == $"./@{fc.FieldName}"
                            )
                        {
                        }
                        else
                        {
                            IsComplexXPathUsed = true;
                            fc.UseCache        = false;
                        }
                    }
                }
            }

            if (XmlRecordFieldConfigurations.Count <= 0)
            {
                throw new ChoRecordConfigurationException("No record fields specified.");
            }

            //Validate each record field
            foreach (var fieldConfig in XmlRecordFieldConfigurations)
            {
                fieldConfig.Validate(this);
            }

            //Check field position for duplicate
            string[] dupFields = XmlRecordFieldConfigurations.GroupBy(i => i.Name)
                                 .Where(g => g.Count() > 1)
                                 .Select(g => g.Key).ToArray();

            if (dupFields.Length > 0)
            {
                throw new ChoRecordConfigurationException("Duplicate field(s) [Name(s): {0}] found.".FormatString(String.Join(",", dupFields)));
            }

            RecordFieldConfigurationsDict = XmlRecordFieldConfigurations.OrderBy(c => c.IsXmlAttribute).Where(i => !i.Name.IsNullOrWhiteSpace()).ToDictionary(i => i.Name);

            if (XmlRecordFieldConfigurations.Where(e => e.IsNullable).Any() ||
                NullValueHandling == ChoNullValueHandling.Empty)
            {
                if (!NamespaceManager.HasNamespace("xsi"))
                {
                    NamespaceManager.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
                }
                if (!NamespaceManager.HasNamespace("xsd"))
                {
                    NamespaceManager.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema");
                }
            }

            LoadNCacheMembers(XmlRecordFieldConfigurations);
        }
コード例 #10
0
        public override void Validate(object state)
        {
            base.Validate(state);

            //if (XPath.IsNull())
            //    throw new ChoRecordConfigurationException("XPath can't be null or whitespace.");

            if (XPath.IsNullOrWhiteSpace())
            {
                if (!IsDynamicObject && (RecordType.IsGenericType && RecordType.GetGenericTypeDefinition() == typeof(KeyValuePair <,>)))
                {
                    NodeName = NodeName.IsNullOrWhiteSpace() ? "KeyValuePair" : NodeName;
                    RootName = RootName.IsNullOrWhiteSpace() ? "KeyValuePairs" : RootName;
                }
                else if (!IsDynamicObject && !typeof(IChoScalarObject).IsAssignableFrom(RecordType))
                {
                    NodeName = NodeName.IsNullOrWhiteSpace() ? RecordType.Name : NodeName;
                    RootName = RootName.IsNullOrWhiteSpace() ? NodeName.ToPlural() : NodeName;
                }
            }
            else
            {
                RootName = RootName.IsNullOrWhiteSpace() ? XPath.SplitNTrim("/").Where(t => !t.IsNullOrWhiteSpace() && t.NTrim() != "." && t.NTrim() != ".." && t.NTrim() != "*").FirstOrDefault() : RootName;
                NodeName = NodeName.IsNullOrWhiteSpace() ? XPath.SplitNTrim("/").Where(t => !t.IsNullOrWhiteSpace() && t.NTrim() != "." && t.NTrim() != ".." && t.NTrim() != "*").Skip(1).FirstOrDefault() : NodeName;
            }

            string rootName = null;
            string nodeName = null;
            ChoXmlDocumentRootAttribute da = TypeDescriptor.GetAttributes(RecordType).OfType <ChoXmlDocumentRootAttribute>().FirstOrDefault();

            if (da != null)
            {
                rootName = da.Name;
            }
            else
            {
                XmlRootAttribute ra = TypeDescriptor.GetAttributes(RecordType).OfType <XmlRootAttribute>().FirstOrDefault();
                if (ra != null)
                {
                    nodeName = ra.ElementName;
                }
            }

            RootName = RootName.IsNullOrWhiteSpace() && !rootName.IsNullOrWhiteSpace() ? rootName : RootName;
            NodeName = NodeName.IsNullOrWhiteSpace() && !nodeName.IsNullOrWhiteSpace() ? nodeName : NodeName;

            RootName = RootName.IsNullOrWhiteSpace() && !NodeName.IsNullOrWhiteSpace() ? NodeName.ToPlural() : RootName;
            if (!RootName.IsNullOrWhiteSpace() && RootName.ToSingular() != RootName)
            {
                NodeName = NodeName.IsNullOrWhiteSpace() && !RootName.IsNullOrWhiteSpace() ? RootName.ToSingular() : NodeName;
            }

            if (RootName.IsNullOrWhiteSpace())
            {
                RootName = "Root";
            }
            if (NodeName.IsNullOrWhiteSpace())
            {
                NodeName = "XElement";
            }

            //Encode Root and node names
            RootName = System.Net.WebUtility.HtmlEncode(RootName);
            NodeName = System.Net.WebUtility.HtmlEncode(NodeName);

            string[] fieldNames = null;
            XElement xpr        = null;

            if (state is Tuple <long, XElement> )
            {
                xpr = ((Tuple <long, XElement>)state).Item2;
            }
            else
            {
                fieldNames = state as string[];
            }

            if (AutoDiscoverColumns &&
                XmlRecordFieldConfigurations.Count == 0)
            {
                if (RecordType != null && !IsDynamicObject &&
                    ChoTypeDescriptor.GetProperties(RecordType).Where(pd => pd.Attributes.OfType <ChoXmlNodeRecordFieldAttribute>().Any()).Any())
                {
                    DiscoverRecordFields(RecordType);
                }
                else if (xpr != null)
                {
                    IsComplexXPathUsed = false;
                    ChoXmlNamespaceManager nsMgr = new ChoXmlNamespaceManager(NamespaceManager);

                    Dictionary <string, ChoXmlRecordFieldConfiguration> dict = new Dictionary <string, ChoXmlRecordFieldConfiguration>(StringComparer.CurrentCultureIgnoreCase);
                    string name = null;
                    foreach (var attr in xpr.Attributes())
                    {
                        if (!attr.IsValidAttribute(XmlSchemaNamespace, JSONSchemaNamespace))
                        {
                            continue;
                        }

                        if (!IsInNamespace(xpr.Name, attr.Name))
                        {
                            continue;
                        }
                        //if (!attr.Name.NamespaceName.IsNullOrWhiteSpace()) continue;

                        name = GetNameWithNamespace(xpr.Name, attr.Name);

                        if (!dict.ContainsKey(name))
                        {
                            dict.Add(name, new ChoXmlRecordFieldConfiguration(attr.Name.LocalName, $"./@{name}")
                            {
                                FieldName = name
                            });                                                                                                         // DefaultNamespace.IsNullOrWhiteSpace() ? $"//@{name}" : $"//@{DefaultNamespace}" + ":" + $"{name}") { IsXmlAttribute = true });
                        }
                        else
                        {
                            throw new ChoRecordConfigurationException("Duplicate field(s) [Name(s): {0}] found.".FormatString(name));
                        }
                    }

                    bool hasElements = false;
                    //var z = xpr.Elements().ToArray();
                    XElement ele = null;
                    foreach (var kvp in xpr.Elements().GroupBy(e => e.Name.LocalName).Select(g => new { Name = g.Key, Value = g.ToArray() }))
                    {
                        if (kvp.Value.Length == 1)
                        {
                            ele = kvp.Value.First();
                            if (!IsInNamespace(ele.Name))
                            {
                                continue;
                            }

                            name = GetNameWithNamespace(ele.Name);

                            hasElements = true;
                            if (!dict.ContainsKey(name))
                            {
                                dict.Add(name, new ChoXmlRecordFieldConfiguration(ele.Name.LocalName, $"./{name}")
                                {
                                    FieldName = name
                                });                                                                                                       // DefaultNamespace.IsNullOrWhiteSpace() ? $"//{name}" : $"//{DefaultNamespace}" + ":" + $"{name}"));
                            }
                            else
                            {
                                if (dict[name].IsXmlAttribute)
                                {
                                    throw new ChoRecordConfigurationException("Duplicate field(s) [Name(s): {0}] found.".FormatString(name));
                                }

                                dict[name].IsArray = true;
                            }
                        }
                        else if (kvp.Value.Length > 1)
                        {
                            ele = kvp.Value.First();
                            if (!IsInNamespace(ele.Name))
                            {
                                continue;
                            }

                            name = GetNameWithNamespace(ele.Name);

                            hasElements = true;
                            if (!dict.ContainsKey(name))
                            {
                                dict.Add(name, new ChoXmlRecordFieldConfiguration(xpr.Name.LocalName, $"./{name}")
                                {
                                    FieldName = name
                                });                                                                                                       // DefaultNamespace.IsNullOrWhiteSpace() ? $"//{name}" : $"//{DefaultNamespace}" + ":" + $"{name}"));
                            }
                            else
                            {
                                if (dict[name].IsXmlAttribute)
                                {
                                    throw new ChoRecordConfigurationException("Duplicate field(s) [Name(s): {0}] found.".FormatString(name));
                                }

                                dict[name].IsArray = true;
                            }
                        }
                    }

                    //foreach (var ele in xpr.Elements())
                    //{
                    //    if (!IsInNamespace(ele.Name))
                    //        continue;

                    //    name = GetNameWithNamespace(ele.Name);

                    //    hasElements = true;
                    //    if (!dict.ContainsKey(name))
                    //        dict.Add(name, new ChoXmlRecordFieldConfiguration(ele.Name.LocalName, $"/{name}") { FieldName = name }); // DefaultNamespace.IsNullOrWhiteSpace() ? $"//{name}" : $"//{DefaultNamespace}" + ":" + $"{name}"));
                    //    else
                    //    {
                    //        if (dict[name].IsXmlAttribute)
                    //            throw new ChoRecordConfigurationException("Duplicate field(s) [Name(s): {0}] found.".FormatString(name));

                    //        dict[name].IsArray = true;
                    //    }
                    //}

                    if (!hasElements)
                    {
                        if (IsInNamespace(xpr.Name))
                        {
                            //name = xpr.Name.LocalName;
                            name = GetNameWithNamespace(xpr.Name);
                            dict.Add(name, new ChoXmlRecordFieldConfiguration(name, "text()")
                            {
                                FieldName = name
                            });
                        }
                    }

                    foreach (ChoXmlRecordFieldConfiguration obj in dict.Values)
                    {
                        XmlRecordFieldConfigurations.Add(obj);
                    }
                }
                else if (!fieldNames.IsNullOrEmpty())
                {
                    foreach (string fn in fieldNames)
                    {
                        if (fn.StartsWith("_"))
                        {
                            string fn1 = fn.Substring(1);
                            var    obj = new ChoXmlRecordFieldConfiguration(fn, xPath: $"./{fn1}");
                            obj.FieldName      = fn1;
                            obj.IsXmlAttribute = true;
                            XmlRecordFieldConfigurations.Add(obj);
                        }
                        else if (fn.EndsWith("_"))
                        {
                            string fn1 = fn.Substring(0, fn.Length - 1);
                            var    obj = new ChoXmlRecordFieldConfiguration(fn, xPath: $"./{fn1}");
                            obj.FieldName  = fn1;
                            obj.IsXmlCDATA = true;
                            XmlRecordFieldConfigurations.Add(obj);
                        }
                        else
                        {
                            var obj = new ChoXmlRecordFieldConfiguration(fn, xPath: $"./{fn}");
                            XmlRecordFieldConfigurations.Add(obj);
                        }
                    }
                }
            }
            else
            {
                IsComplexXPathUsed = false;

                foreach (var fc in XmlRecordFieldConfigurations)
                {
                    if (fc.IsArray == null)
                    {
                        fc.IsArray = typeof(ICollection).IsAssignableFrom(fc.FieldType);
                    }

                    if (fc.FieldName.IsNullOrWhiteSpace())
                    {
                        fc.FieldName = fc.Name;
                    }

                    if (fc.XPath.IsNullOrWhiteSpace())
                    {
                        fc.XPath = $"./{fc.FieldName}|.//@{fc.FieldName}";
                    }
                    else
                    {
                        if (fc.XPath == fc.FieldName ||
                            fc.XPath == $"./{fc.FieldName}" || fc.XPath == $"./{fc.FieldName}" || fc.XPath == $"./{fc.FieldName}" ||
                            fc.XPath == $"./@{fc.FieldName}" || fc.XPath == $"./@{fc.FieldName}" || fc.XPath == $"./@{fc.FieldName}"
                            )
                        {
                        }
                        else
                        {
                            IsComplexXPathUsed = true;
                            fc.UseCache        = false;
                        }
                    }
                }
            }

            if (XmlRecordFieldConfigurations.Count <= 0)
            {
                throw new ChoRecordConfigurationException("No record fields specified.");
            }

            //Validate each record field
            foreach (var fieldConfig in XmlRecordFieldConfigurations)
            {
                fieldConfig.Validate(this);
            }

            //Check field position for duplicate
            string[] dupFields = XmlRecordFieldConfigurations.GroupBy(i => i.Name)
                                 .Where(g => g.Count() > 1)
                                 .Select(g => g.Key).ToArray();

            if (dupFields.Length > 0)
            {
                throw new ChoRecordConfigurationException("Duplicate field(s) [Name(s): {0}] found.".FormatString(String.Join(",", dupFields)));
            }

            PIDict = new Dictionary <string, System.Reflection.PropertyInfo>();
            PDDict = new Dictionary <string, PropertyDescriptor>();
            foreach (var fc in XmlRecordFieldConfigurations)
            {
                if (fc.PropertyDescriptor == null)
                {
                    fc.PropertyDescriptor = ChoTypeDescriptor.GetProperties(RecordType).Where(pd => pd.Name == fc.Name).FirstOrDefault();
                }
                if (fc.PropertyDescriptor == null)
                {
                    continue;
                }

                PIDict.Add(fc.PropertyDescriptor.Name, fc.PropertyDescriptor.ComponentType.GetProperty(fc.PropertyDescriptor.Name));
                PDDict.Add(fc.PropertyDescriptor.Name, fc.PropertyDescriptor);
            }

            RecordFieldConfigurationsDict = XmlRecordFieldConfigurations.OrderBy(c => c.IsXmlAttribute).Where(i => !i.Name.IsNullOrWhiteSpace()).ToDictionary(i => i.Name);

            if (XmlRecordFieldConfigurations.Where(e => e.IsNullable).Any() ||
                NullValueHandling == ChoNullValueHandling.Default)
            {
                if (NamespaceManager != null)
                {
                    if (!NamespaceManager.HasNamespace("xsi"))
                    {
                        NamespaceManager.AddNamespace("xsi", ChoXmlSettings.XmlSchemaInstanceNamespace);
                    }
                    if (!NamespaceManager.HasNamespace("xsd"))
                    {
                        NamespaceManager.AddNamespace("xsd", ChoXmlSettings.XmlSchemaNamespace);
                    }
                }
            }

            LoadNCacheMembers(XmlRecordFieldConfigurations);
        }