Exemplo n.º 1
0
        public override INodePointer CreateChild(SifXPathContext context, string name, int i)
        {
            SifVersion   version    = Version;
            IElementDef  subEleDef  = GetChildDef(name);
            SifFormatter formatter  = Adk.Dtd.GetFormatter(version);
            SifElement   sifElement = (SifElement)fElement;

            // Check to see if this child has a render surrogate defined
            IRenderSurrogate rs = subEleDef.GetVersionInfo(version).GetSurrogate();

            if (rs != null)
            {
                return(rs.CreateChild(this, formatter, version, context));
            }

            if (subEleDef.Field)
            {
                SifSimpleType ssf = subEleDef.TypeConverter.GetSifSimpleType(null);
                SimpleField   sf  = formatter.SetField(sifElement, subEleDef, ssf, version);
                return(SimpleFieldPointer.Create(this, sf));
            }
            else
            {
                SifElement newEle = SifElement.Create(sifElement, subEleDef);
                formatter.AddChild(sifElement, newEle, version);
                return(new SifElementPointer(this, newEle, version));
            }
        }
Exemplo n.º 2
0
 /// <summary>
 /// Throws an exception if a developer attempts to add the wrong type
 /// of child to this list, which is typed to contain only a single type of element
 /// </summary>
 /// <param name="child"></param>
 private void _throwInvalidChild(SifElement child)
 {
     throw new InvalidCastException
               (string.Format
                   ("This <{0}> instance is in an invalid state. Cannot contain a child of type <{1}>.",
                   ElementDef.Name, child.ElementDef.Name));
 }
Exemplo n.º 3
0
        /// <summary>
        /// Use by SIFXPathContext when determining if it can add a child
        /// or not
        /// </summary>
        /// <param name="childName"></param>
        /// <returns></returns>
        public AddChildDirective GetAddChildDirective(string childName)
        {
            SifElement sifElement = (SifElement)fElement;

            if (sifElement.ChildCount == 0)
            {
                // There are no children. Don't even check for repeatability.
                // This child can be added.
                return(AddChildDirective.ADD);
            }
            IElementDef candidate = GetChildDef(childName);

            if (candidate.Field)
            {
                // Don't evaluate repeatability
                return(AddChildDirective.ADD);
            }

            SifElement instance = sifElement.GetChild(candidate);

            if (instance == null)
            {
                // There are no siblings of this type. This child can be
                // added
                return(AddChildDirective.ADD);
            }
            if (candidate.IsRepeatable(Version))
            {
                // This element is repeatable. This child can be added
                return(AddChildDirective.ADD);
            }

            // A sibling exists, and the element is not repeatable
            return(AddChildDirective.DONT_ADD_NOT_REPEATABLE);
        }
Exemplo n.º 4
0
 /// <summary>
 /// Adds a SimpleField parsed from a specific version of SIF to the parent.
 /// </summary>
 /// <param name="contentParent">The element to add content to</param>
 /// <param name="fieldDef">The metadata definition of the field to set</param>
 /// <param name="data">The value to set to the field</param>
 /// <param name="version">The version of SIF that the SIFElement is being constructed
 /// from</param>
 /// <returns></returns>
 public virtual SimpleField SetField(SifElement contentParent,
                                     IElementDef fieldDef,
                                     SifSimpleType data,
                                     SifVersion version)
 {
     return(contentParent.SetField(fieldDef, data));
 }
Exemplo n.º 5
0
        private void AssertMessageStreamer(MessageStreamer streamer, SifVersion version)
        {
            long         length = streamer.Length;
            MemoryStream ms     = new MemoryStream();

            streamer.CopyTo(ms);

            // Copy to a string for debugging purposes
            Console.WriteLine("********************************************************************");
            string data = Encoding.UTF8.GetString(ms.ToArray());

            Console.WriteLine("RawLength:{0}, Text Length:{1}", ms.Length, data.Length);
            Console.WriteLine(data);

            Assert.AreEqual(length, ms.Length, "Length property and final length are not the same.");


            // Try parsing the final stream to see if it is a valid message
            SifParser parser = SifParser.NewInstance();

            ms.Seek(0, SeekOrigin.Begin);
            StreamReader reader = new StreamReader(ms);
            SifElement   o      = parser.Parse(reader, null, SifParserFlags.None, version);

            Assert.IsNotNull(o);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Creates a new SifXPathContext instance to use for traversing the
        /// specified SIF Data Object
        /// </summary>
        /// <remarks>
        /// Contexts that are created from other contexts automatically inherit all
        /// custom variables and functions that are defined in the other context
        /// </remarks>
        /// <param name="parent">The SifXPathContext to share custom functions and
        /// variables with</param>
        /// <param name="sdo">The SIF Data Object or SIFElement to traverse</param>
        /// <returns>an instance of SifXPathContext</returns>
        public static SifXPathContext NewSIFContext(SifXPathContext parent,
                                                    SifElement sdo)
        {
            SifXPathContext context = new SifXPathContext(parent, sdo);

            return(context);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Creates a new SifXPathContext instance to use for traversing the
        /// specified SIF Data Object
        /// </summary>
        /// <remarks>
        /// NOTE: The SIFDataObject.setSIFVersion(version) is automatically
        /// called and set to the target version.
        /// </remarks>
        /// <param name="sdo">The SIF Data Object or SIFElement to traverse</param>
        /// <returns>an instance of SifXPathContext</returns>
        /// <param name="version">The SIFVersion to use when traversing this object using XPath.</param>
        public static SifXPathContext NewSIFContext(SifElement sdo, SifVersion version)
        {
            sdo.SifVersion = version;
            SifXPathContext context = NewSIFContext(sdo);

            return(context);
        }
Exemplo n.º 8
0
 /// <summary>
 /// Adds a SimpleField parsed from a specific version of SIF to the parent.
 /// </summary>
 /// <param name="contentParent">The element to add content to</param>
 /// <param name="fieldDef">The metadata definition of the field to set</param>
 /// <param name="data">The value to set to the field</param>
 /// <param name="version">The version of SIF that the SIFElement is being constructed
 /// from</param>
 /// <returns></returns>
 public override SimpleField SetField(SifElement contentParent,
                                      IElementDef fieldDef,
                                      SifSimpleType data,
                                      SifVersion version)
 {
     return(GetContainer(contentParent, fieldDef, version).SetField(fieldDef, data));
 }
Exemplo n.º 9
0
        private SifElement GetContainer(SifElement contentParent, IElementDef childDef, SifVersion version)
        {
            IElementDef elementParentDef = childDef.Parent;

            if (elementParentDef != null && elementParentDef != contentParent.ElementDef)
            {
                // The element does not appear to belong to this parent. Attempt to look
                // for a container element that might be missing in between the two
                // If the parent of this element were collapsed in a previous version
                // of SIF, check for or re-add the parent element and add this new
                // child instead.
                //
                // For example, a child could be an Email element from the
                // common package that's being added to StudentPersonal. In this
                // case,
                // we need to actually find or create an instance of the new
                // EmailList
                // container element and add the child to it, instead of to "this"
                String      tag         = elementParentDef.Tag(Adk.SifVersion);
                IElementDef missingLink = Adk.Dtd.LookupElementDef(contentParent.ElementDef, tag);
                if (missingLink != null && missingLink.IsCollapsed(version))
                {
                    SifElement container = contentParent.GetChild(missingLink);
                    if (container == null)
                    {
                        container = SifElement.Create(contentParent, missingLink);
                    }
                    AddChild(contentParent, container, version);
                    return(container);
                }
            }

            return(contentParent);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Gets the content from the SIFElement for the specified version of SIF. Only
        /// elements that apply to the requested version of SIF will be returned.
        /// </summary>
        /// <param name="element">The element to retrieve content from</param>
        /// <param name="version"></param>
        /// <returns></returns>
        public virtual IList <Element> GetContent(SifElement element, SifVersion version)
        {
            List <Element>            returnValue = new List <Element>();
            ICollection <SimpleField> fields      = element.GetFields();

            foreach (SimpleField val in fields)
            {
                IElementDef def = val.ElementDef;
                if (def.IsSupported(version) &&
                    !def.IsAttribute(version) &&
                    def.Field)
                {
                    returnValue.Add(val);
                }
            }

            IList <SifElement> children = element.GetChildList();

            foreach (SifElement val in children)
            {
                IElementDef def = val.ElementDef;
                if (def.IsSupported(version))
                {
                    returnValue.Add(val);
                }
            }


            MergeSort.Sort <Element>(returnValue, ElementSorter <Element> .GetInstance(version));
            //returnValue.Sort( ElementSorter<Element>.GetInstance( version ) );
            return(returnValue);
        }
Exemplo n.º 11
0
 /// <summary>
 /// Adds a SIFElement parsed from a specific version of SIF to the parent.
 /// The formatter instance may use version-specific rules to ensure that the
 /// hierarchy is properly maintained when the source of the content is from
 /// this version of SIF
 /// </summary>
 /// <param name="contentParent"> The element to add content to</param>
 /// <param name="content">The element to add</param>
 /// <param name="version"> The version of SIF that the SIFElement is being constructed
 /// from</param>
 public override SifElement AddChild(
     SifElement contentParent, 
     SifElement content,
     SifVersion version)
 {
     contentParent.RestoreImplementationDef(content);
     return GetContainer(contentParent, content.ElementDef, version).AddChild(content);
 }
Exemplo n.º 12
0
 /// <summary>
 /// Creates a new SifElementPointer
 /// </summary>
 /// <param name="parentPointer">The parent of this pointer</param>
 /// <param name="element">The element being wrapped</param>
 /// <param name="version">The SifVersion in effect</param>
 public SifElementPointer(
     INodePointer parentPointer,
     SifElement element,
     SifVersion version )
     : base(parentPointer, element, version)
 {
     fSifElement = element;
 }
Exemplo n.º 13
0
 /// <summary>
 /// Parses the XML string value and returns the proper SimpleField instance to hold
 /// the element value
 /// </summary>
 /// <param name="parent">The parent SIFElement of this field</param>
 /// <param name="id">The metadata definition of the field</param>
 /// <param name="formatter">The formatter to use for the specific version of SIF being parsed</param>
 /// <param name="xmlValue">A string representing the XML payload being used for this version of SIF</param>
 /// <returns>A simple field initialized with the proper value</returns>
 /// <exception cref="AdkTypeParseException">thrown if the value cannot be parsed according to the
 /// formatting rules for this version of SIF</exception>
 public SimpleField ParseField(
     SifElement parent,
     IElementDef id,
     SifFormatter formatter,
     string xmlValue)
 {
     return(Parse(formatter, xmlValue).CreateField(parent, id));
 }
Exemplo n.º 14
0
        public override void SetValue(object rawValue)
        {
            SifElementPointer immediateParent = (SifElementPointer)Parent;
            SifElement        parentElement   = immediateParent.Element as SifElement;
            SifSimpleType     sst             = GetSIFSimpleTypeValue(fElementDef, rawValue);

            parentElement.SetField(fElementDef, sst);
        }
Exemplo n.º 15
0
 /// <summary>
 /// Validates that the child being added is the same type as TValue
 /// </summary>
 /// <param name="element">The child that is about to be added</param>
 protected override void EvaluateChild(SifElement element)
 {
     base.EvaluateChild(element);
     if (!(element is TValue))
     {
         _throwInvalidChild(element);
     }
 }
Exemplo n.º 16
0
 /// <summary>
 /// Creates a new SifElementPointer
 /// </summary>
 /// <param name="parentPointer">The parent of this pointer</param>
 /// <param name="element">The element being wrapped</param>
 /// <param name="version">The SifVersion in effect</param>
 public SifElementPointer(
     INodePointer parentPointer,
     SifElement element,
     SifVersion version)
     : base(parentPointer, element, version)
 {
     fSifElement = element;
 }
Exemplo n.º 17
0
 /// <summary>
 /// Adds a SIFElement parsed from a specific version of SIF to the parent.
 /// The formatter instance may use version-specific rules to ensure that the
 /// hierarchy is properly maintained when the source of the content is from
 /// this version of SIF
 /// </summary>
 /// <param name="contentParent"> The element to add content to</param>
 /// <param name="content">The element to add</param>
 /// <param name="version"> The version of SIF that the SIFElement is being constructed
 /// from</param>
 public override SifElement AddChild(
     SifElement contentParent,
     SifElement content,
     SifVersion version)
 {
     contentParent.RestoreImplementationDef(content);
     return(GetContainer(contentParent, content.ElementDef, version).AddChild(content));
 }
Exemplo n.º 18
0
        private SIF_Ack SifSystemControl(SifElement command, ZoneImpl zone)
        {
            SIF_SystemControl     msg = new SIF_SystemControl(zone.HighestEffectiveZISVersion);
            SIF_SystemControlData cmd = new SIF_SystemControlData();

            cmd.AddChild(command);
            msg.SIF_SystemControlData = cmd;
            return(zone.Dispatcher.send(msg));
        }
Exemplo n.º 19
0
        public void testInheritRules()
        {
            String configFileText1_ = "<agent id=\"mcmTest.MappingsTest\" sifVersion=\"2.0\">\n"
                                      + " <mappings id=\"Default\">\n"
                                      + " <object object=\"StudentPersonal\">\n"
                                      + " <field name=\"StudentPers_guid\">@RefId</field>\n"
                                      + " <field name=\"LastName\">Name[@Type='01']/LastName</field>\n"
                                      + " <field name=\"FirstName\">Name[@Type='01']/FirstName</field>\n"
                                      + " <field name=\"MiddleName\">Name[@Type='01']/MiddleName</field>\n"
                                      +
                                      " <field name=\"Street\">StudentAddress[@PickupOrDropoff='NA',@DayOfWeek='NA']/Address[@Type='01']/Street/Line1</field>\n"
                                      +
                                      " <field name=\"City\">StudentAddress[@PickupOrDropoff='NA',@DayOfWeek='NA']/Address[@Type='01']/City</field>\n"
                                      +
                                      " <field name=\"State\">StudentAddress[@PickupOrDropoff='NA',@DayOfWeek='NA']/Address[@Type='01']/StateProvince</field>\n"
                                      +
                                      " <field name=\"Zip\">StudentAddress[@PickupOrDropoff='NA',@DayOfWeek='NA']/Address[@Type='01']/PostalCode</field>\n"
                                      + " </object>\n"
                                      + "  <mappings id=\"Zone A\" zoneId=\"Zone A\">\n"
                                      + "   <object object=\"StudentPersonal\">\n"
                                      + "     <field name=\"LastName\">Name[@Type='06']/LastName</field>\n"
                                      + "     <field name=\"FirstName\">Name[@Type='06']/FirstName</field>\n"
                                      + "     <field name=\"MiddleName\">Name[@Type='06']/MiddleName</field>\n"
                                      + "   </object>\n"
                                      + "  </mappings>\n"
                                      + " </mappings>\n"
                                      + "</agent>";

            IDictionary psValueMap = new Dictionary <String, String>();

            psValueMap["StudentPers_guid"] = "14050614103526133C3FD2324C5BC8FF";
            psValueMap["LastName"]         = "Finale";
            psValueMap["FirstName"]        = "Prima";
            psValueMap["MiddleName"]       = "Mediccio";
            psValueMap["Street"]           = "667 Gate Way";
            psValueMap["City"]             = "Sacramento";
            psValueMap["State"]            = "CA";
            psValueMap["Zip"] = "91020";

            StringMapAdaptor sma = new StringMapAdaptor(psValueMap);
            StudentPersonal  sp  = doOutboundMappingSelect(sma, configFileText1_,
                                                           "Zone A", null, null);

            Assertion.AssertNotNull("Student should not be null", sp);

            SifElement address = (SifElement)sp
                                 .GetElementOrAttribute(
                "StudentAddress[@PickupOrDropoff='NA',@DayOfWeek='NA']/Address[@Type='01']");

            Assertion.AssertNotNull("Student Address should have mapped", address);

            SifElement name = (SifElement)sp
                              .GetElementOrAttribute("Name[@Type='06']");

            Assertion.AssertNotNull("Name should have mapped to '06'", name);
        }
Exemplo n.º 20
0
        public bool ReadRaw(XmlReader reader,
                            SifVersion version,
                            SifElement parent,
                            SifFormatter formatter)
        {
            string name = reader.LocalName;

            if (name.Equals(fDateElement))
            {
                String   dateValue = ConsumeElementTextValue(reader, version);
                DateTime?date      = formatter.ToDate(dateValue);
                if (date.HasValue)
                {
                    DateTime    tsValue  = date.Value;
                    SifDateTime dateTime = new SifDateTime(tsValue);
                    parent.SetField(dateTime.CreateField(parent, fElementDef));
                }
            }
            else if (name.Equals(fTimeElement))
            {
                String   timeValue = ConsumeElementTextValue(reader, version);
                DateTime?time      = formatter.ToTime(timeValue);
                if (time.HasValue)
                {
                    DateTime val = time.Value;
                    // See if the Timestamp field already exists on the parent
                    SimpleField timeStampField = parent.GetField(fElementDef);
                    if (timeStampField == null)
                    {
                        // Doesn't exist, create it
                        SifDateTime dateTime = new SifDateTime(val);
                        parent.SetField(dateTime.CreateField(parent, fElementDef));
                    }
                    else
                    {
                        // Exists, update the time portion of the date
                        SifDateTime sdt = (SifDateTime)timeStampField.SifValue;
                        if (sdt != null && sdt.Value.HasValue)
                        {
                            DateTime tsValue = sdt.Value.Value;
                            tsValue = tsValue.Add(val.TimeOfDay);
                            sdt     = new SifDateTime(tsValue);
                            // Overwrite the current value
                            parent.SetField(sdt.CreateField(parent, fElementDef));
                        }
                    }
                }
            }
            else
            {
                return(false);
            }

            return(true);
        }
        public void testSetPacketNumberAndMorePackets()
        {
            MessageDispatcher testDispatcher = new MessageDispatcher(this.Zone);

            this.Zone.SetDispatcher(testDispatcher);
            this.Zone.Connect(ProvisioningFlags.None);
            InMemoryProtocolHandler testProto = (InMemoryProtocolHandler)this.Zone.ProtocolHandler;

            testProto.clear();

            // Send a single SIF_Response with a small Authentication object

            String     SifRequestMsgId  = Adk.MakeGuid();
            String     sourceId         = "TEST_SOURCEID";
            SifVersion testVersion      = SifVersion.LATEST;
            int        maxBufferSize    = int.MaxValue;
            int        packetNumber     = 999;
            YesNo      morePacketsValue = YesNo.YES;

            IElementDef[] testRestrictions = new IElementDef[] { InfrastructureDTD.AUTHENTICATION_REFID };

            SifResponseSender srs = new SifResponseSender();

            srs.Open(this.Zone, SifRequestMsgId, sourceId, testVersion, maxBufferSize, testRestrictions);

            srs.SIF_PacketNumber = packetNumber;
            srs.SIF_MorePackets  = morePacketsValue;

            // Assert the values of the properties set before writing
            Assert.AreEqual(packetNumber, srs.SIF_PacketNumber);
            Assert.AreEqual(morePacketsValue, srs.SIF_MorePackets);

            srs.Write(new Authentication(Adk.MakeGuid(), Adk.MakeGuid(), AuthSifRefIdType.EMPLOYEEPERSONAL));
            srs.Close();

            // Assert the values of the properties set after writing
            Assert.AreEqual(packetNumber, srs.SIF_PacketNumber);
            Assert.AreEqual(morePacketsValue, srs.SIF_MorePackets);

            // Retrieve the SIF_Response message off the protocol handler and asssert the results
            SIF_Response response = (SIF_Response)testProto.readMsg();

            Assert.AreEqual(SifRequestMsgId, response.SIF_RequestMsgId);
            Assert.AreEqual(packetNumber, response.SIF_PacketNumber.Value);
            Assert.AreEqual(morePacketsValue.ToString(), response.SIF_MorePackets);

            SIF_Header header = response.SIF_Header;

            Assert.AreEqual(sourceId, header.SIF_DestinationId);

            SifElement responseObject = response.SIF_ObjectData.GetChildList()[0];

            Assert.IsNotNull(responseObject);
        }
        public void testSifResponseSenderMultiplePackets()
        {
            MessageDispatcher testDispatcher = new MessageDispatcher(Zone);

            Zone.Properties.OneObjectPerResponse = true;
            Zone.SetDispatcher(testDispatcher);
            Zone.Connect(ProvisioningFlags.None);
            InMemoryProtocolHandler testProto = (InMemoryProtocolHandler)Zone.ProtocolHandler;

            testProto.clear();

            // Send a single SIF_Response with a small Authentication object

            String     SifRequestMsgId = Adk.MakeGuid();
            String     sourceId        = "TEST_SOURCEID";
            SifVersion testVersion     = SifVersion.LATEST;
            int        maxBufferSize   = int.MaxValue;

            IElementDef[] testRestrictions = new IElementDef[] { InfrastructureDTD.AUTHENTICATION_REFID };

            SifResponseSender srs = new SifResponseSender();

            srs.Open(Zone, SifRequestMsgId, sourceId, testVersion, maxBufferSize, testRestrictions);
            srs.Write(new Authentication(Adk.MakeGuid(), Adk.MakeGuid(), AuthSifRefIdType.EMPLOYEEPERSONAL));
            srs.Write(new Authentication(Adk.MakeGuid(), Adk.MakeGuid(), AuthSifRefIdType.EMPLOYEEPERSONAL));
            srs.Write(new Authentication(Adk.MakeGuid(), Adk.MakeGuid(), AuthSifRefIdType.EMPLOYEEPERSONAL));
            srs.Write(new Authentication(Adk.MakeGuid(), Adk.MakeGuid(), AuthSifRefIdType.EMPLOYEEPERSONAL));
            srs.Write(new Authentication(Adk.MakeGuid(), Adk.MakeGuid(), AuthSifRefIdType.EMPLOYEEPERSONAL));
            srs.Close();


            for (int x = 0; x < 5; x++)
            {
                // Retrieve the SIF_Response message off the protocol handler and asssert the results
                SIF_Response response = (SIF_Response)testProto.readMsg();

                Assert.AreEqual(SifRequestMsgId, response.SIF_RequestMsgId);
                Assert.AreEqual(x + 1, response.SIF_PacketNumber.Value);
                if (x == 4)
                {
                    Assert.AreEqual("No", response.SIF_MorePackets);
                }
                else
                {
                    Assert.AreEqual("Yes", response.SIF_MorePackets);
                }

                SIF_Header header = response.SIF_Header;
                Assert.AreEqual(sourceId, header.SIF_DestinationId);

                SifElement responseObject = response.SIF_ObjectData.GetChildList()[0];
                Assert.IsNotNull(responseObject);
            }
        }
Exemplo n.º 23
0
        /// <summary>
        /// Gets the content from the SIFElement for the specified version of SIF. Only
        /// elements that apply to the requested version of SIF will be returned.
        /// </summary>
        /// <param name="element">The element to retrieve content from</param>
        /// <param name="version"></param>
        /// <returns></returns>
        public override IList <Element> GetContent(SifElement element, SifVersion version)
        {
            List <Element>            returnValue = new List <Element>();
            ICollection <SimpleField> fields      = element.GetFields();

            foreach (SimpleField val in fields)
            {
                IElementDef def = val.ElementDef;
                if (def.IsSupported(version) &&
                    !def.IsAttribute(version) &&
                    def.Field)
                {
                    returnValue.Add(val);
                }
            }

            IList <SifElement> children = element.GetChildList();

            foreach (SifElement val in children)
            {
                IElementDef def = val.ElementDef;
                if (def.IsSupported(version))
                {
                    if (def.IsCollapsed(version))
                    {
                        ICollection <Element> subElements = GetContent(val, version);
                        // FIXUP the ElementDef for this version of SIF.
                        // for example, StudentPersonal/EmailList/Email needs it's
                        // ElementDef set to "StudentPersonal_Email"
                        foreach (Element e in subElements)
                        {
                            IElementDef subElementDef = e.ElementDef;
                            if (version.CompareTo(subElementDef.EarliestVersion) >= 0)
                            {
                                String      tag         = subElementDef.Tag(Adk.SifVersion);
                                IElementDef restoredDef = Adk.Dtd.LookupElementDef(element.ElementDef, tag);
                                if (restoredDef != null)
                                {
                                    e.ElementDef = restoredDef;
                                }
                                returnValue.Add(e);
                            }
                        }
                    }
                    else
                    {
                        returnValue.Add(val);
                    }
                }
            }
            MergeSort.Sort <Element>(returnValue, ElementSorter <Element> .GetInstance(version));
            //returnValue.Sort(ElementSorter<Element>.GetInstance(version));
            return(returnValue);
        }
Exemplo n.º 24
0
        private void SetFieldValueFromAttribute(
            SifElement element,
            XmlReader reader,
            IDtd dtd,
            SifVersion version,
            SifFormatter formatter,
            IZone zone)
        {
            IElementDef elementDef = element.ElementDef;
            IElementDef field      = dtd.LookupElementDef(element.ElementDef, reader.LocalName);

            if (field == null && reader.Prefix != null)
            {
                if (reader.LocalName == SifWriter.NIL && reader.NamespaceURI == XmlSchema.InstanceNamespace)
                {
                    TypeConverter converter = elementDef.TypeConverter;
                    if (converter != null)
                    {
                        SifSimpleType sst = converter.GetSifSimpleType(null);
                        element.SetField(elementDef, sst);
                    }
                    return;
                }
                else if (reader.Name.StartsWith("xmlns"))
                {
                    return;
                }
                else
                {
                    field = dtd.LookupElementDef(elementDef, reader.Prefix + ":" + reader.LocalName);
                }
            }

            if (field != null)
            {
                string        strVal = reader.Value.Trim();
                SifSimpleType val    = ParseValue(field, strVal, version, formatter, zone);
                element.SetField(field, val);
            }
            else if (element.ElementDef.EarliestVersion >= SifVersion.SIF20 && version < SifVersion.SIF20)
            {
                Adk.Log.Warn("Field " + element.ElementDef.ClassName + "." + (reader.Prefix == null ? reader.LocalName : reader.Prefix + ":" + reader.LocalName) + " does not exist in the sif 2.0 specification onwards.  It may or may not be valid in sif 1.5r1.  It will be ignored.");
            }
            else
            {
                // TODO: Log and gracefully ignore, depending on whether the ADK is set to strict or loose parsing
                throw new SifException
                          (SifErrorCategoryCode.Xml, SifErrorCodes.XML_GENERIC_VALIDATION_3,
                          "Unknown element or attribute",
                          reader.LocalName + " is not a recognized attribute of the " +
                          elementDef.Name + " element (SIF " +
                          element.EffectiveSIFVersion.ToString() + ")", zone);
            }
        }
Exemplo n.º 25
0
 /// <summary>  Parses a SIF data element into a <c>SifElement</c>.
 ///
 /// </summary>
 /// <param name="msg">The content to parse
 /// </param>
 /// <param name="zone">The Zone from which the message was received, or null if
 /// not applicable or not known
 /// </param>
 /// <param name="flags">One or more <c>FLG_</c> constants, or zero if no
 /// flags are applicable
 /// </param>
 /// <param name="version">The version of SIF that will be associated with the
 /// returned object. By default, SifParser uses the default version of
 /// SIF in effect for the agent when parsing messages that do not have
 /// a SIF_Message envelope. By specifying a value to this parameter, you
 /// can change the version of SIF associated with the returned object in
 /// the event there is no SIF_Message envelope present in the XML
 /// content. Note that when parsing XML content with a SIF_Message
 /// envelope, SifParser ignores this parameter and instead uses the
 /// version indicated by the <i>Version</i> and <i>xmlns</i> attributes
 ///
 /// </param>
 /// <returns> A SifElement object encapsulating the message payload (e.g.
 /// a OpenADK.Library.us.Student.StudentPersonal object)
 ///
 /// </returns>
 /// <exception cref="OpenADK.Library.AdkParsingException">AdkParsingException is thrown if unable to
 /// parse the message</exception>
 /// <exception cref="System.IO.IOException"> IOException is thrown if an error is reported while reading
 /// the message content</exception>
 public SifElement Parse(string msg,
                         IZone zone,
                         SifParserFlags flags,
                         SifVersion version)
 {
     using (StringReader reader = new StringReader(msg))
     {
         SifElement element = Parse(reader, zone, flags, version);
         reader.Close();
         return(element);
     }
 }
Exemplo n.º 26
0
        /// <summary>
        /// Creates a child element, if supported by this node
        /// </summary>
        /// <param name="parentPointer"></param>
        /// <param name="formatter"></param>
        /// <param name="version"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public INodePointer CreateChild(INodePointer parentPointer, SifFormatter formatter, SifVersion version,
                                        SifXPathContext context)
        {
            // 1) Create an instance of the SimpleField with a null value (It's assigned later)

            //
            // STEP 2
            // Find the actual field to set the value to
            //
            SifElement parent        = (SifElement)((SifElementPointer)parentPointer).Element;
            SifElement targetElement = parent;

            if (!fElementDef.Field)
            {
                //	This indicates a child SifElement that needs to be created
                targetElement = SifElement.Create(parent, fElementDef);

                formatter.AddChild(parent, targetElement, version);
            }

            IElementDef fieldDef = null;

            if (fValueXpath.Equals("."))
            {
                fieldDef = fElementDef;
            }
            else
            {
                String fieldName = fValueXpath;
                if (fValueXpath.StartsWith("@"))
                {
                    fieldName = fValueXpath.Substring(1);
                }
                fieldDef = Adk.Dtd.LookupElementDef(fElementDef, fieldName);
            }


            if (fieldDef == null)
            {
                throw new ArgumentException("Support for value path {" + fValueXpath +
                                            "} is not supported by XPathSurrogate.");
            }

            SifSimpleType ssf = fieldDef.TypeConverter.GetSifSimpleType(null);
            SimpleField   sf  = ssf.CreateField(targetElement, fieldDef);

            targetElement.SetField(sf);


            // 2) built out a fake set of node pointers representing the SIF 1.5r1 path and
            //    return the root pointer from that stack
            return(BuildLegacyPointers(parentPointer, sf));
        }
Exemplo n.º 27
0
        /// <summary>
        /// Gets the content from the SIFElement for the specified version of SIF. Only
        /// elements that apply to the requested version of SIF will be returned.
        /// </summary>
        /// <param name="element">The element to retrieve content from</param>
        /// <param name="version"></param>
        /// <returns></returns>
        public override IList<Element> GetContent(SifElement element, SifVersion version)
        {
            List<Element> returnValue = new List<Element>();
            ICollection<SimpleField> fields = element.GetFields();
            foreach (SimpleField val in fields)
            {
                IElementDef def = val.ElementDef;
                if (def.IsSupported(version) &&
                     !def.IsAttribute(version) &&
                     def.Field )
                {
                    returnValue.Add(val);
                }
            }

            IList<SifElement> children = element.GetChildList();
            foreach (SifElement val in children)
            {
                IElementDef def = val.ElementDef;
                if (def.IsSupported(version))
                {
                    if (def.IsCollapsed(version))
                    {
                        ICollection<Element> subElements = GetContent(val, version);
                        // FIXUP the ElementDef for this version of SIF.
                        // for example, StudentPersonal/EmailList/Email needs it's
                        // ElementDef set to "StudentPersonal_Email"
                        foreach (Element e in subElements)
                        {
                            IElementDef subElementDef = e.ElementDef;
                            if (version.CompareTo(subElementDef.EarliestVersion) >= 0)
                            {
                                String tag = subElementDef.Tag(Adk.SifVersion);
                                IElementDef restoredDef = Adk.Dtd.LookupElementDef(element.ElementDef, tag);
                                if (restoredDef != null)
                                {
                                    e.ElementDef = restoredDef;
                                }
                                returnValue.Add(e);
                            }
                        }
                    }
                    else
                    {
                        returnValue.Add(val);
                    }
                }
            }
            MergeSort.Sort<Element>(returnValue, ElementSorter<Element>.GetInstance(version));
            //returnValue.Sort(ElementSorter<Element>.GetInstance(version));
            return returnValue;
        }
Exemplo n.º 28
0
        private void Write(SifElement o, int mode, Boolean isLegacy)
        {
            if (!Include(o))
            {
                return;
            }


            //  "<tag [attr...]>[text]" or "<tag [attr...]/>"
            string tag = o.ElementDef.Tag(fVersion);

            fWriter.WriteStartElement(tag);
            if (!fRootAttributesWritten)
            {
                writeRootAttributes(false);
            }
            WriteAttributes(o);
            if (mode == EMPTY)
            {
                fWriter.WriteEndElement();
            }
            else
            {
                // Check for a text value (or an xs:nil value)
                SimpleField elementValue = o.GetField(o.ElementDef);
                if (elementValue != null)
                {
                    SifSimpleType sst = elementValue.SifValue;
                    if (sst == null || sst.RawValue == null)
                    {
                        // The value of this element has been set and it is
                        // null. This should be rendered as 'xs:nil' in SIF 2.x and greater
                        if (!isLegacy)
                        {
                            fWriter.WriteAttributeString(NIL, XmlSchema.InstanceNamespace, "true");
                        }
                    }
                    else
                    {
                        if (o.DoNotEncode)
                        {
                            fWriter.WriteRaw(o.TextValue);
                        }
                        else
                        {
                            String xmlValue = sst.ToString(fFormatter);
                            fWriter.WriteString(xmlValue);
                        }
                    }
                }
            }
        }
Exemplo n.º 29
0
        /**
         * Perform a mapping operation on the specified SIFElement. The mapping operation
         * will be either inbound or outbound, depending on whether this class was returned
         * from {@link Mappings#selectInbound(ElementDef, SIFVersion, String, String)} or
         * {@link Mappings#selectOutbound(ElementDef, SIFVersion, String, String)}
         * @param mappedElement The SIFElement to perform the mappings operation on
         * @param adaptor The FieldAdaptor to use for getting or setting data
         * @throws ADKMappingException
         */

        public void Map(SifElement mappedElement, IFieldAdaptor adaptor)
        {
            SifXPathContext context = GetXPathContext(mappedElement, adaptor);

            if (fDirection == MappingDirection.Inbound)
            {
                fMappings.MapInbound(context, adaptor, mappedElement, fFieldMappings, fSIFVersion);
            }
            else if (fDirection == MappingDirection.Outbound)
            {
                fMappings.MapOutbound(context, adaptor, mappedElement, fFieldMappings, fValueBuilder, fSIFVersion);
            }
        }
Exemplo n.º 30
0
 internal static INodePointer Create(INodePointer parent, SifElement element, SifVersion version)
 {
     if (version.Major < 2)
     {
         IElementDef      fieldDef = element.ElementDef;
         IRenderSurrogate rs       = fieldDef.GetVersionInfo(version).GetSurrogate();
         if (rs != null)
         {
             return(rs.CreateNodePointer(parent, element, version));
         }
     }
     return(new SifElementPointer(parent, element, version));
 }
Exemplo n.º 31
0
 public void UnexpectedEmbeddedSIFMessage()
 {
     // this test should throw an exception because we are not passing "ExpectInnerEnvelope" in the
     // parser flags
     using (Stream aStream = GetResourceStream("GetNextMessageResponse.xml"))
     {
         TextReader aReader = new StreamReader(aStream);
         SifParser  parser  = SifParser.NewInstance();
         SifElement element = parser.Parse(aReader, null, SifParserFlags.None, SifVersion.SIF11);
         aReader.Close();
         aStream.Close();
     }
 }
Exemplo n.º 32
0
        /**
         * Runs a schema validation test on a single object using the ADK
         * @param sdo
         * @throws Exception
         */
        protected void testSchemaElement(SifElement se)
        {
            bool validated = fSchemaValidator.Validate( se, fVersion );

            // 4) If validation failed, write the object out for tracing purposes
            if ( !validated ) {
            SifWriter outWriter = new SifWriter( fOutput );
            outWriter.Write( se, fVersion );
            outWriter.Flush();
            fSchemaValidator.PrintProblems( fOutput );
            Assertion.Assert( "Errors validating...", false );
            }
        }
Exemplo n.º 33
0
        public void ParsingSIFTime()
        {
            SifElement element = null;

            using (Stream aStream = GetResourceStream("LibraryPatronStatus.xml"))
            {
                SifParser parser = SifParser.NewInstance();
                element = parser.Parse(aStream, null);
                aStream.Close();
            }

            Assert.IsNotNull(element, "SIFElement was not parsed");
        }
Exemplo n.º 34
0
        public void ParsingSectionInfo()
        {
            SifElement element = null;

            using (Stream aStream = GetResourceStream("SectionInfo_SchoolCourseInfoOverride.xml"))
            {
                SifParser parser = SifParser.NewInstance();
                element = parser.Parse(aStream, null);
                aStream.Close();
            }

            Assert.IsNotNull(element, "SIFElement was not parsed");
        }
Exemplo n.º 35
0
        /// <summary>
        /// Creates a new SifXPathContext
        /// </summary>
        /// <param name="parent"></param>
        /// <param name="context"></param>
        private SifXPathContext( SifXPathContext parent, SifElement context )
        {
            if ( parent != null )
            {
                fContext = parent.fContext;
            }
            else
            {
                fContext = new SifXsltContext();
                fContext.AddFunctions( "adk", new ClassFunctions( typeof ( AdkFunctions ), null ) );
            }

            SifVersion version = context.SifVersion;
            if( version == null )
            {
                version = SifVersion.LATEST;
            }

            fContextElement = context;
            fContextPointer = new SifElementPointer( null, fContextElement, version );
            fDefaultNavigator = new SifXPathNavigator( fContext, fContextPointer );
        }
Exemplo n.º 36
0
 /// <summary>
 /// Write a SIF element in the version of SIF currently in effect for this
 /// SIFWriter.
 /// </summary>
 /// <param name="o"></param>
 private void WriteElement( SifElement o )
 {
     WriteElement( o, fVersion.CompareTo( SifVersion.SIF20 ) < 0 );
 }
Exemplo n.º 37
0
 /// <summary>
 /// Adds a SimpleField parsed from a specific version of SIF to the parent.
 /// </summary>
 /// <param name="contentParent">The element to add content to</param>
 /// <param name="fieldDef">The metadata definition of the field to set</param>
 /// <param name="data">The value to set to the field</param>
 /// <param name="version">The version of SIF that the SIFElement is being constructed
 /// from</param>
 /// <returns></returns>
 public virtual SimpleField SetField(SifElement contentParent,
     IElementDef fieldDef,
     SifSimpleType data,
     SifVersion version)
 {
     return contentParent.SetField(fieldDef, data);
 }
Exemplo n.º 38
0
        private void SetFieldValueFromAttribute(
            SifElement element,
            XmlReader reader,
            IDtd dtd,
            SifVersion version,
            SifFormatter formatter,
            IZone zone )
        {
            IElementDef elementDef = element.ElementDef;
            IElementDef field = dtd.LookupElementDef( element.ElementDef, reader.LocalName );
            if ( field == null && reader.Prefix != null )
            {
                if(reader.LocalName == SifWriter.NIL && reader.NamespaceURI == XmlSchema.InstanceNamespace )
                {
                    TypeConverter converter = elementDef.TypeConverter;
                    if ( converter != null )
                    {
                        SifSimpleType sst = converter.GetSifSimpleType( null );
                        element.SetField(elementDef, sst);
                    }
                    return;
                }
                else if( reader.Name.StartsWith( "xmlns" ) )
                {
                    return;
                }
                else
                {
                    field = dtd.LookupElementDef(elementDef, reader.Prefix + ":" + reader.LocalName);
                }
            }

            if( field != null )
            {
                string strVal = reader.Value.Trim();
                SifSimpleType val = ParseValue( field, strVal, version, formatter, zone );
                element.SetField( field, val );
            }
            else if (element.ElementDef.EarliestVersion >= SifVersion.SIF20 && version < SifVersion.SIF20)
            {
                Adk.Log.Warn("Field " + element.ElementDef.ClassName + "." + (reader.Prefix == null ? reader.LocalName : reader.Prefix + ":" + reader.LocalName ) + " does not exist in the sif 2.0 specification onwards.  It may or may not be valid in sif 1.5r1.  It will be ignored."  );
            }
            else
            {
                // TODO: Log and gracefully ignore, depending on whether the ADK is set to strict or loose parsing
                throw new SifException
                    (SifErrorCategoryCode.Xml, SifErrorCodes.XML_GENERIC_VALIDATION_3,
                      "Unknown element or attribute",
                      reader.LocalName + " is not a recognized attribute of the " +
                      elementDef.Name + " element (SIF " +
                      element.EffectiveSIFVersion.ToString() + ")", zone);
            }
        }
Exemplo n.º 39
0
        private void SetFieldValueFromElement( IElementDef def,
                                               SifElement element,
                                               XmlReader reader,
                                               SifVersion version,
                                               SifFormatter formatter,
                                               IZone zone )
        {
            // Check for xsi:nill
            if ( reader.IsEmptyElement )
            {
                // no data to set
                return;
            }

            // Look for the xsi:nill attribute that signals a null value
            while ( reader.MoveToNextAttribute() )
            {
                if (reader.LocalName == SifWriter.NIL && reader.NamespaceURI == XmlSchema.InstanceNamespace)
                {
                    SifSimpleType val = def.TypeConverter.GetSifSimpleType( null );
                    element.SetField( def, val );
                    while (reader.NodeType != XmlNodeType.EndElement)
                    {
                        reader.Read();
                    }
                    return;
                }
                else
                {
                    // TODO: This is an unknown attribute. Log and continue
                }
            }

            while ( reader.NodeType == XmlNodeType.Element )
            {
                reader.Read();
            }

            if ( reader.NodeType == XmlNodeType.Text )
            {
                SifSimpleType val = ParseValue( def, reader.Value.Trim(), version, formatter, zone );
                element.SetField( def, val );
            }
            // TODO: Not sure if this will always advance as expected.
            while ( reader.NodeType != XmlNodeType.EndElement )
            {
                reader.Read();
            }
        }
Exemplo n.º 40
0
 /// <summary>
 /// Create a SimpleField from the value that this type represents
 /// </summary>
 /// <param name="parent">The SIFElement that will be the parent of the field</param>
 /// <param name="id">The metatdata definition of the field being set</param>
 /// <returns>A SimpleField instance initialized with the proper value</returns>
 public virtual SimpleField CreateField( SifElement parent,
                                         IElementDef id )
 {
     return new SimpleField( parent, id, this );
 }
Exemplo n.º 41
0
        /// <summary>  Write the attributes of a SifElement to the output stream</summary>
        /// <param name="o">The SifElement whose attributes are to be written
        /// </param>
        private void WriteAttributes( SifElement o )
        {
            // TODO: We need to make sure the GetFields() API returns a usable collection
            ICollection<SimpleField> fields = fFormatter.GetFields( o, fVersion );
            foreach (SimpleField f in fields )
            {
                IElementVersionInfo evi = f.ElementDef.GetVersionInfo( fVersion );
                if ( evi != null && evi.IsAttribute )
                {
                    // Null attribute values are not supported in SIF, unlike
                    // element values, which can be represented with xs:nil
                    SifSimpleType sst = f.SifValue;
                    if (sst.RawValue != null)
                    {
                        String tag = evi.Tag;
                        Boolean handled = false;
                        if ( tag.StartsWith( "x" ) )
                        {
                            if ( evi.Tag.Equals( "xml:lang" ) )
                            {
                                fWriter.WriteAttributeString("xml", "lang", null, sst.ToString(fFormatter));
                            }
                            else if ( evi.Tag.Equals( "xsi:type" ) )
                            {
                                fWriter.WriteAttributeString("type", XmlSchema.InstanceNamespace, sst.ToString(fFormatter));
                            }
                            handled = true;
                        }

                        if ( !handled )
                        {
                            fWriter.WriteStartAttribute( evi.Tag, string.Empty );
                            fWriter.WriteString( sst.ToString( fFormatter ) );
                            fWriter.WriteEndAttribute();
                        }
                    }
                }
            }

            if ( fSerializeIds && o.XmlId != null )
            {
                fWriter.WriteAttributeString( "id", XML_NAMESPACE, o.XmlId );
            }
        }
Exemplo n.º 42
0
        //private const int CLOSE = 2;
        private Boolean HasContent( SifElement o,
                                    SifVersion version )
        {
            if ( o.ChildCount > 0 )
            {
                return true;
            }
            ICollection<SimpleField> fields = o.GetFields();
            foreach ( SimpleField f in fields )
            {
                // TODO: This is a perfect place to optimize. Version-specific lookups
                // should be optimized

                if ( f.ElementDef.IsSupported( version ) && !f.ElementDef.IsAttribute( version ) )
                {
                    return true;
                }
            }
            return false;
        }
Exemplo n.º 43
0
        private void Write( SifElement o, int mode, Boolean isLegacy )
        {
            if ( !Include( o ) )
            {
                return;
            }

            //  "<tag [attr...]>[text]" or "<tag [attr...]/>"
            string tag = o.ElementDef.Tag( fVersion );
            fWriter.WriteStartElement( tag );
            if (!fRootAttributesWritten)
            {
                writeRootAttributes(false);
            }
            WriteAttributes( o );
            if ( mode == EMPTY )
            {
                fWriter.WriteEndElement();
            }
            else
            {
                // Check for a text value (or an xs:nil value)
                SimpleField elementValue = o.GetField( o.ElementDef );
                if ( elementValue != null )
                {
                    SifSimpleType sst = elementValue.SifValue;
                    if ( sst == null || sst.RawValue == null )
                    {
                        // The value of this element has been set and it is
                        // null. This should be rendered as 'xs:nil' in SIF 2.x and greater
                        if ( !isLegacy )
                        {
                            fWriter.WriteAttributeString(NIL, XmlSchema.InstanceNamespace, "true");
                        }
                    }
                    else
                    {
                        if ( o.DoNotEncode )
                        {
                            fWriter.WriteRaw( o.TextValue );
                        }
                        else
                        {
                            String xmlValue = sst.ToString( fFormatter );
                            fWriter.WriteString( xmlValue );
                        }
                    }
                }
            }
        }
Exemplo n.º 44
0
 /// <summary>
 /// Creates a new SifXPathContext instance to use for traversing the
 /// specified SIF Data Object
 /// </summary>
 /// <remarks>
 /// NOTE: The SIFDataObject.setSIFVersion(version) is automatically
 /// called and set to the target version.
 /// </remarks>
 /// <param name="parent">The SifXPathContext to share custom functions and 
 /// variables with</param>
 /// <param name="sdo">The SIF Data Object or SIFElement to traverse</param>
 /// <returns>an instance of SifXPathContext</returns>
 /// <param name="version">The SIFVersion to use when traversing this object using XPath.</param>
 public static SifXPathContext NewSIFContext( SifXPathContext parent,
                                              SifElement sdo, SifVersion version )
 {
     sdo.SifVersion = version;
     return NewSIFContext( parent, sdo );
 }
Exemplo n.º 45
0
        /// <summary>
        /// Creates a new SifXPathContext instance to use for traversing the
        /// specified SIF Data Object
        /// </summary>
        /// <remarks>
        /// Contexts that are created from other contexts automatically inherit all
        /// custom variables and functions that are defined in the other context
        /// </remarks>
        /// <param name="parent">The SifXPathContext to share custom functions and 
        /// variables with</param>
        /// <param name="sdo">The SIF Data Object or SIFElement to traverse</param>
        /// <returns>an instance of SifXPathContext</returns>
        public static SifXPathContext NewSIFContext( SifXPathContext parent,
                                                     SifElement sdo )
        {
            SifXPathContext context = new SifXPathContext( parent, sdo );

            return context;
        }
Exemplo n.º 46
0
 /// <summary>
 /// Gets the fields from the SIFElement for the specified version of SIF. Only
 /// the fields that apply to the requested version of SIF will be returned.
 /// </summary>
 /// <param name="element"></param>
 /// <param name="version"></param>
 /// <returns></returns>
 public virtual ICollection<SimpleField> GetFields(SifElement element, SifVersion version)
 {
     ICollection<SimpleField> fields = element.GetFields();
     List<SimpleField> returnValue = new List<SimpleField>();
     // remove any fields that do not belong in this version of SIF
     foreach(SimpleField field in fields )
     {
         IElementDef def = field.ElementDef;
         if (version.CompareTo(def.EarliestVersion) > -1 &&
                 version.CompareTo(def.LatestVersion) < 1)
         {
             returnValue.Add( field );
         }
     }
     returnValue.Sort( ElementSorter<SimpleField>.GetInstance( version ) );
     return returnValue;
 }
Exemplo n.º 47
0
        public bool ReadRaw( XmlReader reader,
                             SifVersion version,
                             SifElement parent,
                             SifFormatter formatter )
        {
            String elementName = fElementDef.Name;
            if ( !reader.LocalName.Equals( elementName ) )
            {
                return false;
            }

            String value = ConsumeElementTextValue( reader, version );

            if ( value != null && value.Length > 0 )
            {
                DateTime? time = formatter.ToTime( value );
                SifTime sifTime = new SifTime( time );
                parent.SetField( sifTime.CreateField( parent, fElementDef ) );
            }
            return true;
        }
Exemplo n.º 48
0
        private SifXPathContext GetXPathContext(
            SifElement mappedElement, IFieldAdaptor adaptor)
        {
            lock (this)
            {
                if (!mappedElement.ElementDef.Name.Equals(fElementDef.Name))
                {
                    throw new AdkMappingException(
                        "Unable to use object for mapping. MappingsContext expected an object of type '" +
                        fElementDef.Name + "' but was '" + mappedElement.ElementDef.Name + "'.", null);
                }

                if (fRootContext == null)
                {
                    fRootContext = SifXPathContext.NewSIFContext(mappedElement, fSIFVersion);
                    if (adaptor is IXPathVariableLibrary)
                    {
                        fRootContext.AddVariables( "", (IXPathVariableLibrary)adaptor);
                    }
                }
                return SifXPathContext.NewSIFContext(fRootContext, mappedElement);
            }
        }
Exemplo n.º 49
0
 internal static INodePointer Create( INodePointer parent, SifElement element, SifVersion version )
 {
     if ( version.Major < 2 )
     {
         IElementDef fieldDef = element.ElementDef;
         IRenderSurrogate rs = fieldDef.GetVersionInfo( version ).GetSurrogate();
         if ( rs != null )
         {
             return rs.CreateNodePointer( parent, element, version );
         }
     }
     return new SifElementPointer( parent, element, version );
 }
Exemplo n.º 50
0
        public bool ReadRaw( XmlReader reader,
                             SifVersion version,
                             SifElement parent,
                             SifFormatter formatter )
        {
            string name = reader.LocalName;

            if ( name.Equals( fDateElement ) )
            {
                String dateValue = ConsumeElementTextValue( reader, version );
                DateTime? date = formatter.ToDate( dateValue );
                if ( date.HasValue )
                {
                    DateTime tsValue = date.Value;
                    SifDateTime dateTime = new SifDateTime( tsValue );
                    parent.SetField( dateTime.CreateField( parent, fElementDef ) );
                }
            }
            else if ( name.Equals( fTimeElement ) )
            {
                String timeValue = ConsumeElementTextValue( reader, version );
                DateTime? time = formatter.ToTime( timeValue );
                if ( time.HasValue )
                {
                    DateTime val = time.Value;
                    // See if the Timestamp field already exists on the parent
                    SimpleField timeStampField = parent.GetField( fElementDef );
                    if ( timeStampField == null )
                    {
                        // Doesn't exist, create it
                        SifDateTime dateTime = new SifDateTime( val );
                        parent.SetField( dateTime.CreateField( parent, fElementDef ) );
                    }
                    else
                    {
                        // Exists, update the time portion of the date
                        SifDateTime sdt = (SifDateTime) timeStampField.SifValue;
                        if ( sdt != null && sdt.Value.HasValue )
                        {
                            DateTime tsValue = sdt.Value.Value;
                            tsValue = tsValue.Add( val.TimeOfDay );
                            sdt = new SifDateTime( tsValue );
                            // Overwrite the current value
                            parent.SetField( sdt.CreateField( parent, fElementDef ) );
                        }
                    }
                }
            }
            else
            {
                return false;
            }

            return true;
        }
Exemplo n.º 51
0
 /// <summary>
 /// Write a SIF element in the version of SIF currently in effect for this
 /// SIFWriter
 /// </summary>
 /// <param name="o">The SIF Element instance to write to the output stream</param>
 public virtual void Write( SifElement o )
 {
     WriteElement( o );
 }
Exemplo n.º 52
0
 public virtual SifElement AddChild(SifElement contentParent, SifElement content, SifVersion version)
 {
     return contentParent.AddChild(content);
 }
Exemplo n.º 53
0
 /// <summary>
 /// Creates a new SifXPathContext instance to use for traversing the
 /// specified SIF Data Object
 /// </summary>
 /// <remarks>
 /// NOTE: The SIFDataObject.setSIFVersion(version) is automatically
 /// called and set to the target version.
 /// </remarks>
 /// <param name="sdo">The SIF Data Object or SIFElement to traverse</param>
 /// <returns>an instance of SifXPathContext</returns>
 /// <param name="version">The SIFVersion to use when traversing this object using XPath.</param>
 public static SifXPathContext NewSIFContext( SifElement sdo, SifVersion version )
 {
     sdo.SifVersion = version;
     SifXPathContext context = NewSIFContext( sdo );
     return context;
 }
Exemplo n.º 54
0
        /// <summary>
        /// Gets the content from the SIFElement for the specified version of SIF. Only
        /// elements that apply to the requested version of SIF will be returned.
        /// </summary>
        /// <param name="element">The element to retrieve content from</param>
        /// <param name="version"></param>
        /// <returns></returns>
        public virtual IList<Element> GetContent( SifElement element, SifVersion version )
        {
            List<Element> returnValue = new List<Element>();
            ICollection<SimpleField> fields = element.GetFields();
            foreach (SimpleField val in fields) {
                IElementDef def = val.ElementDef;
                if (def.IsSupported(version) &&
                    !def.IsAttribute(version) &&
                    def.Field)
                {
                    returnValue.Add(val);
                }
            }

               IList<SifElement> children = element.GetChildList();
            foreach(SifElement val in children ) {
                IElementDef def = val.ElementDef;
                if (def.IsSupported(version))
                {
                    returnValue.Add(val);
                }
            }

            MergeSort.Sort<Element>(returnValue, ElementSorter<Element>.GetInstance(version));
            //returnValue.Sort( ElementSorter<Element>.GetInstance( version ) );
            return returnValue;
        }
Exemplo n.º 55
0
 /// <summary>
 /// Creates a new SifXPathContext instance to use for traversing the
 /// specified SIF Data Object
 /// </summary>
 /// <param name="sdo">The SIF Data Object or SIFElement to traverse</param>
 /// <returns>an instance of SifXPathContext</returns>
 public static SifXPathContext NewSIFContext( SifElement sdo )
 {
     return NewSIFContext( null, sdo );
 }
Exemplo n.º 56
0
        private IElementDef LookupElementDef( SifElement parent,
                                              XmlReader reader,
                                              IDtd dtd,
                                              SifVersion version,
                                              IZone zone )
        {
            //  Lookup the ElementDef metadata in the SifDtd object for the
            //  version of SIF we are parsing. First try looking up a ElementDef
            //  for a field or complex object that is a child of another element,
            //  such as StudentPersonal_Name, SIF_Ack_SIF_Header, etc. If none
            //  found then look for a root-level element such as StudentPersonal,
            //  SIF_Ack, etc. If still nothing is found we don't know how to
            //  parse this element -- it is neither a top-level object element
            //  nor a child field element for this version of SIF.
            String elementName = reader.LocalName;
            IElementDef def = null;
            if ( parent != null )
            {
                def = dtd.LookupElementDef( parent.ElementDef, elementName );
            }

            if ( def == null )
            {
                def = dtd.LookupElementDef( elementName );
            }

            //	Beginning with SIF 1.5 *any* object can have a SIF_ExtendedElements
            //	child, so we need to check for that case since the Adk metadata
            //	does not add SIF_ExtendedElements to all object types
            if ( def == null && elementName.Equals( "SIF_ExtendedElements" ) )
            {
                def = GlobalDTD.SIF_EXTENDEDELEMENTS;
            }

            //	Beginning with SIF 2.0 *any* object can have a SIF_ExtendedElements
            //	child, so we need to check for that case since the Adk metadata
            //	does not add SIF_ExtendedElements to all object types
            if ( def == null && elementName.Equals( "SIF_Metadata" ) )
            {
                // TODO: Add support for SIF_Metadata back in to the .NET ADK
                def = null; // DatamodelDTD.SIF_METADATA;
            }

            // Note: def returned can be null.
            return def;
        }
Exemplo n.º 57
0
        private void ParseLegacyXML(
                XmlReader reader, 
                SifVersion version,
			    IZone zone, 
                SifElement currentElement, 
                SifFormatter formatter,
			    String xmlName )
        {
            bool handled = false;

            // Determine if any surrogate formatters that are defined as children
            // of the current element can resolve it
            // NOTE: Until we fix this in the ADK, elements from the common package loose their
            // metadata information that was originally defined.
            IElementDef currentDef = currentElement.ElementDef;
            IList<IElementDef> children = currentDef.Children;
            if ( children == null || children.Count == 0 )
            {
                // try to get the actual element def
                // WARNING! this is somewhat of a hack until
                // we get support for what we need in the ADK metadata

                try
                {
                    SifElement copy =
                        (SifElement) ClassFactory.CreateInstance( currentDef.FQClassName );
                    children = copy.ElementDef.Children;
                }
                catch ( Exception cnfe )
                {
                    throw new SifException(
                        SifErrorCategoryCode.Xml,
                        SifErrorCodes.XML_GENERIC_VALIDATION_3,
                        "Unable to parse" + xmlName + "  " + version.ToString() + cnfe.Message, zone );
                }
            }
            using (XmlReader subtreeReader = reader.ReadSubtree())
            {
                subtreeReader.Read();
                foreach ( IElementDef candidate in children )
                {
                    if ( candidate.EarliestVersion.CompareTo( version ) > 0 )
                    {
                        continue;
                    }
                    IElementVersionInfo evi = candidate.GetVersionInfo( version );
                    if ( evi != null )
                    {
                        IRenderSurrogate rs = evi.GetSurrogate();
                        if ( rs != null )
                        {
                            try
                            {
                                bool surrogateHandled = rs.ReadRaw( subtreeReader, version, currentElement, formatter );
                                if ( surrogateHandled )
                                {
                                    handled = true;
                                    break;
                                }
                            }
                            catch ( AdkTypeParseException e )
                            {
                                HandleTypeParseException( "Unable to parse element or attribute value: " + e.Message, e,
                                                          zone );
                                handled = true;
                                break;
                            }
                            catch ( AdkParsingException e )
                            {
                                throw new SifException( SifErrorCategoryCode.Xml,
                                                        SifErrorCodes.XML_GENERIC_VALIDATION_3,
                                                        "unable to parse xml: " + e.Message
                                                        + version.ToString(), zone );
                            }
                        }
                    }
                }

                subtreeReader.Close();
            }
            // advance to the next tag
            reader.Read();

            if ( !handled )
            {
                String _tag = currentElement != null
                                  ? currentElement.ElementDef.Name + "/" + xmlName
                                  : xmlName;
                throw new SifException(
                    SifErrorCategoryCode.Xml,
                    SifErrorCodes.XML_GENERIC_VALIDATION_3, "Unknown element or attribute",
                    _tag + " is not a recognized element of SIF " + version.ToString(), zone );
            }
        }
Exemplo n.º 58
0
        private SifElement ReadSifElementFromElementNode(
            IElementDef def,
            XmlReader reader,
            IDtd dtd,
            SifElement parent,
            SifFormatter formatter,
            SifVersion version,
            IZone zone )
        {
            SifElement element;
            try
            {
                element = SifElement.Create( parent, def );
            }
            catch ( TypeLoadException tle )
            {
                throw new AdkParsingException
                    ( "Could not create an instance of " + def.FQClassName + " to wrap a " +
                      reader.LocalName + " element because that class doesn't exist", zone, tle );
            }
            catch ( Exception ex )
            {
                throw new AdkParsingException
                    ( "Could not create an instance of " + def.FQClassName, zone, ex );
            }

            element.ElementDef = def;
            element.SifVersion = version;

            if ( parent != null )
            {
                element = formatter.AddChild( parent, element, version );
            }

            // Set the attributes to fields of the SifElement
            while ( reader.MoveToNextAttribute() )
            {
                SetFieldValueFromAttribute( element, reader, dtd, version, formatter, zone );
            }

            return element;
        }
Exemplo n.º 59
0
 /**
  * Perform a mapping operation on the specified SIFElement. The mapping operation
  * will be either inbound or outbound, depending on whether this class was returned
  * from {@link Mappings#selectInbound(ElementDef, SIFVersion, String, String)} or
  * {@link Mappings#selectOutbound(ElementDef, SIFVersion, String, String)}
  * @param mappedElement The SIFElement to perform the mappings operation on
  * @param adaptor The FieldAdaptor to use for getting or setting data
  * @throws ADKMappingException
  */
 public void Map(SifElement mappedElement, IFieldAdaptor adaptor)
 {
     SifXPathContext context = GetXPathContext(mappedElement, adaptor);
     if (fDirection == MappingDirection.Inbound)
     {
         fMappings.MapInbound(context, adaptor, mappedElement, fFieldMappings, fSIFVersion);
     }
     else if (fDirection == MappingDirection.Outbound)
     {
         fMappings.MapOutbound(context, adaptor, mappedElement, fFieldMappings, fValueBuilder, fSIFVersion);
     }
 }
Exemplo n.º 60
0
        /// <summary>  Write a SIF element in the version of SIF currently in effect for this
        /// SifWriter.
        /// </summary>
        /// <param name="element">The SIF Element instance to Write to the output stream
        /// <param name="isLegacy">if true, this method assumes that it needs to do more work,
        /// such as looking for rendering surrogates for the specific version of SIF</param>
        /// </param>
        private void WriteElement( SifElement element, bool isLegacy )
        {
            IElementDef def = element.ElementDef;
            if ( !(Include( element ) && def.IsSupported( fVersion ) )  )
            {
                return;
            }

            if (isLegacy)
            {
                IRenderSurrogate surrogate = def.GetVersionInfo(fVersion).GetSurrogate();
                if (surrogate != null)
                {
                    surrogate.RenderRaw(fWriter, fVersion, element, fFormatter);
                    return;
                }
            }

            if ( element.IsEmpty() || !HasContent( element, fVersion ) )
            {
                if (element is XMLData)
                {
                    XmlDocument doc = ((XMLData) element).Xml;
                    doc.Save( fWriter );
                }
                else
                {
                    Write( element, EMPTY, isLegacy );
                }
            }
            else
            {
                Write( element, OPEN, isLegacy );

                ICollection<Element> elements = fFormatter.GetContent( element, fVersion );
                foreach ( Element childElement in elements )
                {
                    if ( childElement is SifElement )
                    {
                        WriteElement( (SifElement) childElement, isLegacy );
                    }
                    else
                    {
                        Write( (SimpleField) childElement, isLegacy );
                    }
                }
                fWriter.WriteEndElement();
            }
        }