/** * Stores the items in the cache that will later be asserted * @param cache */ private void storeAssertedRequests(RequestCache cache) { SIF_QueryObject obj = new SIF_QueryObject(""); SIF_Query query = new SIF_Query(obj); SIF_Request request = new SIF_Request(); request.SIF_Query = query; Query q; TestState ts; fMsgIds = new String[10]; fStateObjects = new String[10]; // Add 10 entries to the cache, interspersed with other entries that are removed for (int i = 0; i < 10; i++) { ts = new TestState(); ts.State = Adk.MakeGuid(); fStateObjects[i] = ts.State; q = new Query(StudentDTD.STUDENTPERSONAL); q.UserData = ts; String phantom1 = Adk.MakeGuid(); String phantom2 = Adk.MakeGuid(); storeRequest(cache, request, q, phantom1, "foo"); fMsgIds[i] = Adk.MakeGuid(); storeRequest(cache, request, q, fMsgIds[i], "Object_" + i.ToString()); storeRequest(cache, request, q, phantom2, "bar"); cache.GetRequestInfo(phantom1, null); cache.GetRequestInfo(phantom2, null); } }
public void SharedChildren() { Adk.SifVersion = SifVersion.LATEST; StudentPersonal sp = new StudentPersonal(Adk.MakeGuid(), new Name(NameType.LEGAL, "hello", "world")); // Replace the existing demographics so there is no confusion Demographics d = new Demographics(); sp.Demographics = d; d.SetCountryOfBirth(CountryCode.US); CountriesOfCitizenship countries = new CountriesOfCitizenship(); d.CountriesOfCitizenship = countries; CountriesOfResidency residencies = new CountriesOfResidency(); d.CountriesOfResidency = residencies; countries.AddCountryOfCitizenship(CountryCode.Wrap("UK")); residencies.AddCountryOfResidency(CountryCode.Wrap("AU")); // overwrite the country codes again, just to try to repro the issue d.SetCountryOfBirth(CountryCode.Wrap("AA")); // Should overwrite the existing one //Remove the existing CountryOfCitizenship, add three more, and remove the middle one Assert.IsTrue(countries.Remove(CountryCode.Wrap("UK"))); countries.AddCountryOfCitizenship(CountryCode.Wrap("BB1")); countries.AddCountryOfCitizenship(CountryCode.Wrap("BB2")); countries.AddCountryOfCitizenship(CountryCode.Wrap("BB3")); Assert.IsTrue(countries.Remove(CountryCode.Wrap("BB2"))); // Remove the existing CountryOfResidency, add three more, and remove the first one Assert.IsTrue(residencies.Remove(CountryCode.Wrap("AU"))); residencies.AddCountryOfResidency(CountryCode.Wrap("CC1")); residencies.AddCountryOfResidency(CountryCode.Wrap("CC2")); residencies.AddCountryOfResidency(CountryCode.Wrap("CC3")); Assert.IsTrue(residencies.Remove(CountryCode.Wrap("CC1"))); StudentPersonal sp2 = AdkObjectParseHelper.runParsingTest(sp, SifVersion.LATEST); // The runParsingTest() method will compare the objects after writing them and reading them // back in, but to be completely sure, let's assert the country codes again // NOTE: Due to the .Net Array.Sort algorithm, repeatable elements come out in reverse order. // This doesn't appear to be a problem yet, but may be fixed in a future release. // For now, these tests look for the elements in reverse order Demographics d2 = sp2.Demographics; Assert.AreEqual("AA", d2.CountryOfBirth.ToString(), "Country of Birth"); Country[] citizenships = d2.CountriesOfCitizenship.ToArray(); Assert.AreEqual(2, citizenships.Length, "Should be two CountryOfCitizenships"); Assert.AreEqual("BB1", citizenships[0].TextValue, "First CountryOfCitizenship"); Assert.AreEqual("BB3", citizenships[1].TextValue, "Second CountryOfCitizenship"); // assert Country[] resid = d2.CountriesOfResidency.ToArray(); Assert.AreEqual(2, resid.Length, "Should be two CountryOfResidencys"); Assert.AreEqual("CC2", resid[0].TextValue, "First CountryOfResidencys"); Assert.AreEqual("CC3", resid[1].TextValue, "Second CountryOfResidencys"); }
public void SDOParse() { DateTime today = DateTime.Now; Demographics demo = new Demographics(); demo.CountriesOfCitizenship = new CountriesOfCitizenship(); demo.CountriesOfCitizenship.AddCountryOfCitizenship(CountryCode.US); demo.CountriesOfCitizenship.AddCountryOfCitizenship(CountryCode.Wrap("CA")); demo.CountriesOfResidency = new CountriesOfResidency(new Country(CountryCode.Wrap("CA"))); demo.CountryOfBirth = CountryCode.US.ToString(); // Create a StudentPlacement StudentPlacement sp = new StudentPlacement(); sp.RefId = Adk.MakeGuid(); sp.StudentParticipationRefId = Adk.MakeGuid(); sp.StudentPersonalRefId = Adk.MakeGuid(); sp.SetService(ServiceCode.STAFF_PROFESSIONAL_DEVELOPMENT, "foo", "test"); sp.ServiceProviderAgency = "ABSD"; sp.ServiceProviderName = "John Smithfield"; sp.SetServiceSetting("asdfasdf", ServiceSettingCode.REGULAR_SCHOOL_CAMPUS); sp.StartDate = today; sp.FrequencyTime = new FrequencyTime(); sp.SetIndirectTime(DurationUnit.MINUTES, 10); sp.TotalServiceDuration = new TimeUnit(DurationUnit.MINUTES, 5); sp.SpecialNeedsTransportation = false; sp.AssistiveTechnology = true; sp.SetDirectTime(DurationUnit.HOURS, 5); AdkObjectParseHelper.runParsingTest(sp, SifVersion.LATEST); }
private static StudentPersonal CreateStudent( String id, String lastName, String firstName, String street, String city, String state, CountryCode country, String post, String phone, Sex gender, YearLevelCode grade, String birthDateyyyyMMdd) { StudentPersonal student = new StudentPersonal(); ; student.RefId = Adk.MakeGuid(); student.LocalId = id; PersonInfo stupersonal = new PersonInfo(); student.PersonInfo = stupersonal; // Set the Name Name name = new Name(NameType.LEGAL); name.FamilyName = lastName; name.GivenName = firstName; stupersonal.Name = name; Address addr = new Address(); addr.SetType(AddressType.C0765_PHYSICAL_LOCATION); addr.SetStreet(street); addr.City = city; addr.StateProvince = state; addr.PostalCode = post; addr.Country = country.ToString(); stupersonal.AddressList = new AddressList(addr); stupersonal.PhoneNumberList = new PhoneNumberList(new PhoneNumber(PhoneNumberType.PRIMARY, phone)); Demographics dem = new Demographics(); dem.SetSex(gender); dem.BirthDate = DateTime.ParseExact (birthDateyyyyMMdd, "yyyyMMdd", CultureInfo.InvariantCulture.DateTimeFormat); stupersonal.Demographics = dem; return(student); }
public void testConditionWithNullValue() { StudentPersonal sp = new StudentPersonal(Adk.MakeGuid(), new Name(NameType.BIRTH, "E", "Sally")); Query q = new Query(StudentDTD.STUDENTPERSONAL); q.AddCondition(CommonDTD.NAME_LASTNAME, ComparisonOperators.GT, null); Assert.IsFalse(q.Evaluate(sp)); }
public void TestWriteXSINillMultiple() { SIF_Data data = new SIF_Data(); for (int a = 0; a < 3; a++) { StudentPersonal sp = new StudentPersonal(); sp.RefId = Adk.MakeGuid(); sp.StateProvinceId = "\u06DE55889"; sp.LocalId = "987987987987987"; Name name = new Name(NameType.LEGAL, "Johnson", "Steve"); sp.Name = name; name.SetField(CommonDTD.NAME_TYPE, new SifString(null)); name.SetField(CommonDTD.NAME_MIDDLENAME, new SifString(null)); SIF_ExtendedElement see = new SIF_ExtendedElement("FOO", null); see.SetField(GlobalDTD.SIF_EXTENDEDELEMENT, new SifString(null)); see.XsiType = "Integer"; sp.SIFExtendedElementsContainer.Add(see); sp.SetField(StudentDTD.STUDENTPERSONAL_LOCALID, new SifString(null)); data.AddChild(sp); } SIF_Data data2 = (SIF_Data)AdkObjectParseHelper.WriteParseAndReturn(data, SifVersion.LATEST, null, true); foreach (SifElement child in data2.GetChildList()) { StudentPersonal copy = (StudentPersonal)child; Name name = copy.Name; Assert.IsNull(name.Type); Assert.IsNull(name.MiddleName); Assert.IsNotNull(name.FirstName); Assert.IsNotNull(name.LastName); // Attributes cannot be represented using xs nil SimpleField field = name.GetField(CommonDTD.NAME_TYPE); Assert.IsNull(field); field = name.GetField(CommonDTD.NAME_MIDDLENAME); Assert.IsNotNull(field); Assert.IsNull(field.Value); SIF_ExtendedElement see = copy.GetSIFExtendedElement("FOO"); field = see.GetField(GlobalDTD.SIF_EXTENDEDELEMENT); Assert.IsNotNull(field); Assert.IsNull(field.Value); field = copy.GetField(StudentDTD.STUDENTPERSONAL_LOCALID); Assert.IsNotNull(field); Assert.IsNull(field.Value); } }
private SifDataObject createPerson(string id, string lastName, string firstName, string number, string street, string locality, string town, string post, string phone, string gender, string grade, EthnicityCodes ethnicity, string birthDateyyyyMMdd) { SifDataObject person = createPersonObject(id); person.SetElementOrAttribute("@RefId", Adk.MakeGuid()); Name name = new Name(NameType.CURRENT_LEGAL, firstName, lastName); PersonalInformation personal = new PersonalInformation(name); person.AddChild(CommonDTD.PERSONALINFORMATION, personal); AddressableObjectName aon = new AddressableObjectName(); aon.StartNumber = number; Address address = new Address(AddressType.CURRENT, aon); address.Street = street; address.Locality = locality; address.Town = town; address.PostCode = post; address.SetCountry(CountryCode.GBR); personal.Address = address; personal.PhoneNumber = new PhoneNumber(PhoneType.HOME, phone); Demographics dem = new Demographics(); dem.SetEthnicityList(new Ethnicity(ethnicity)); dem.SetGender(Gender.Wrap(gender)); try { dem.BirthDate = SifDate.ParseSifDateString(birthDateyyyyMMdd, SifVersion.SIF15r1); } catch (Exception pex) { Console.WriteLine(pex); } personal.Demographics = dem; return(person); }
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); } }
public static StudentPersonal makeStudentPersonal(String localId, NameType nameType, String firstName, String lastName) { StudentPersonal s = new StudentPersonal(); s.RefId = Adk.MakeGuid(); s.LocalId = localId; Name name = new Name(nameType, lastName, firstName); s.Name = name; return(s); }
public void TestEncodingHighAsciiChars() { StudentPersonal sp = new StudentPersonal(); sp.RefId = Adk.MakeGuid(); sp.StateProvinceId = "\u06DE55889"; sp.LocalId = "987987987987987"; StudentPersonal copy = (StudentPersonal)AdkObjectParseHelper.WriteParseAndReturn(sp, SifVersion.LATEST); Assert.AreEqual("\u06DE55889", copy.StateProvinceId, "LocalID, Encoded"); }
private Authentication CreateAuthentication() { AuthenticationInfo inf = new AuthenticationInfo(new AuthSystem(AuthSystemType.APPLICATION, "Sample SIF Application")); inf.DistinguishedName = "cn=Example User, cn=Users, dc=sifinfo, dc=org"; inf.Username = "******"; Authentication auth = new Authentication(Adk.MakeGuid(), Adk.MakeGuid(), AuthSifRefIdType.STAFFPERSONAL); auth.AuthenticationInfo = inf; return(auth); }
private static StudentPersonal CreateStudent( String id, String lastName, String firstName, String street, String city, StatePrCode state, CountryCode country, String post, String phone, Gender gender, GradeLevelCode grade, RaceType race, String birthDateyyyyMMdd) { StudentPersonal student = new StudentPersonal(); ; student.RefId = Adk.MakeGuid(); student.LocalId = id; // Set the Name Name name = new Name(NameType.LEGAL, firstName, lastName); student.Name = name; Address addr = new Address(); addr.SetType(AddressType.C0369_PERMANENT); addr.SetStreet(street); addr.City = city; addr.SetStateProvince(state); addr.PostalCode = post; addr.SetCountry(country); student.AddressList = new StudentAddressList(PickupOrDropoff.NA, "NA", addr); student.PhoneNumberList = new PhoneNumberList(new PhoneNumber(PhoneNumberType.PRIMARY, phone)); Demographics dem = new Demographics(); dem.RaceList = new RaceList(new Race("", race)); dem.SetGender(gender); dem.BirthDate = DateTime.ParseExact (birthDateyyyyMMdd, "yyyyMMdd", CultureInfo.InvariantCulture.DateTimeFormat); student.Demographics = dem; return(student); }
public void testSimpleLTFilter() { StudentPersonal sp = new StudentPersonal(Adk.MakeGuid(), new Name(NameType.BIRTH, "E", "Sally")); Query q = new Query(StudentDTD.STUDENTPERSONAL); q.AddCondition(CommonDTD.NAME_LASTNAME, ComparisonOperators.LT, "G"); Assert.IsTrue(q.Evaluate(sp)); q = new Query(StudentDTD.STUDENTPERSONAL); q.AddCondition(CommonDTD.NAME_LASTNAME, ComparisonOperators.LT, "E"); Assert.IsFalse(q.Evaluate(sp)); }
public void testStudentSchoolEnrollment020() { StudentSchoolEnrollment sse = new StudentSchoolEnrollment(Adk.MakeGuid(), Adk.MakeGuid(), Adk.MakeGuid(), MembershipType.HOME, TimeFrame.CURRENT); sse.SchoolYear = 2008; sse.SifVersion = SifVersion.SIF20r1; DateTime entryDate = DateTime.Now; sse.EntryDate = entryDate; sse.computeTimeFrame(DateTime.Now); sse.Homeroom = new Homeroom("RoomInfo", Adk.MakeGuid()); sse.SetGradeLevel(GradeLevelCode.KG); testSchemaElement(sse); }
public void testPersistenceWithRemoval() { fRC = RequestCache.GetInstance(fAgent); SIF_QueryObject obj = new SIF_QueryObject(""); SIF_Query query = new SIF_Query(obj); SIF_Request request = new SIF_Request(); request.SIF_Query = query; Query q = new Query(StudentDTD.STUDENTPERSONAL); String testStateItem = Adk.MakeGuid(); TestState ts = new TestState(); ts.State = testStateItem; q.UserData = ts; fMsgIds = new String[10]; // Add 10 entries to the cache, interspersed with other entries that are removed for (int i = 0; i < 10; i++) { String phantom1 = Adk.MakeGuid(); String phantom2 = Adk.MakeGuid(); storeRequest(fRC, request, q, phantom1, "foo"); fMsgIds[i] = Adk.MakeGuid(); storeRequest(fRC, request, q, fMsgIds[i], "Object_" + i); storeRequest(fRC, request, q, phantom2, "bar"); fRC.GetRequestInfo(phantom1, null); fRC.GetRequestInfo(phantom2, null); } // remove every other entry, close, re-open and assert that the correct entries are there for (int i = 0; i < 10; i += 2) { fRC.GetRequestInfo(fMsgIds[i], null); } Assertion.AssertEquals("Before closing Should have five objects", 5, fRC.ActiveRequestCount); fRC.Close(); // Create a new instance. This one should retrieve its settings from the persistence mechanism fRC = RequestCache.GetInstance(fAgent); Assertion.AssertEquals("After Re-Openeing Should have five objects", 5, fRC.ActiveRequestCount); for (int i = 1; i < 10; i += 2) { IRequestInfo cachedInfo = fRC.GetRequestInfo(fMsgIds[i], null); Assertion.AssertNotNull("No cachedID returned for " + i, cachedInfo); } Assertion.AssertEquals("Should have zero objects", 0, fRC.ActiveRequestCount); }
public void testPersistenceWithBadState() { //create new cache for agent RequestCache cache = RequestCache.GetInstance(fAgent); //create new queryobject SIF_QueryObject obj = new SIF_QueryObject(""); //create query, telling it what type of query it is(passing it queryobj) SIF_Query query = new SIF_Query(obj); //create new sif request SIF_Request request = new SIF_Request(); //set query property request.SIF_Query = query; Query q = new Query(StudentDTD.STUDENTPERSONAL); String testStateItem = Adk.MakeGuid(); String requestMsgId = Adk.MakeGuid(); String testObjectType = Adk.MakeGuid(); TestState ts = new TestState(); ts.State = testStateItem; ts.setCreateErrorOnRead(true); q.UserData = ts; storeRequest(cache, request, q, requestMsgId, testObjectType); cache.Close(); // Create a new instance. This one should retrieve its settings from the persistence mechanism cache = RequestCache.GetInstance(fAgent); IRequestInfo ri = cache.GetRequestInfo(requestMsgId, null); //if state is null, should still return ri object Assertion.AssertNotNull("RequestInfo was null", ri); Assertion.AssertEquals("MessageId", requestMsgId, ri.MessageId); Assertion.AssertEquals("ObjectType", testObjectType, ri.ObjectType); ts = (TestState) ri.UserData; // In order for this to be a valid test, the TestState class should have thrown // an exception during deserialization and should be null here. Assertion.AssertNull("UserData should be null", ts); }
public void testSIFRetryQueryResults() { TestState requestState = new TestState(Adk.MakeGuid()); IElementDef objType = StudentDTD.STUDENTCONTACT; ErrorMessageHandler handler = new ErrorMessageHandler(ErrorMessageHandler.HandlerBehavior.ThrowSIFRetryException); handler.RequestStateObject = requestState; fZone.SetQueryResults(handler, objType, null); fZone.Connect(ProvisioningFlags.Register); SIF_Response r = createSIF_Response(objType, true, requestState); AssertRetryHandling(handler, r, fZone); // Now, dispatch a second time. This time the dispatching should work correctly, including // custom state handler.Behavior = ErrorMessageHandler.HandlerBehavior.Normal; assertNormalHandling(handler, r, fZone); assertRequestCacheCleared(r); }
public void testStudentSchoolEnrollmentGradeLevelMapping() { Adk.SifVersion = SifVersion.SIF15r1; IDictionary values = new Hashtable(); values.Add("GRADE", "00"); StringMapAdaptor sma = new StringMapAdaptor(values); StudentSchoolEnrollment sse = new StudentSchoolEnrollment(); Mappings m = fCfg.Mappings.GetMappings("Default").Select(null, null, null); m.MapOutbound(sma, sse, SifVersion.SIF15r1); sse.SetHomeroom("RoomInfo", Adk.MakeGuid()); Console.WriteLine(sse.ToXml()); // This specific case tests what should happen when the grade level is // using an undefined value. // The valueset entries don't have a value for "00", so "00" should be // returned as-is }
public static SifMessagePayload MakeSIFMessagePayload(SifElement payload) { if (payload is SIF_Response) { return((SIF_Response)payload); } SIF_Response rsp = new SIF_Response(); rsp.SetSIF_MorePackets(YesNo.NO); rsp.SIF_RequestMsgId = Adk.MakeGuid(); rsp.SIF_PacketNumber = 1; SIF_Header hdr = rsp.Header; hdr.SIF_Timestamp = DateTime.Now; hdr.SIF_MsgId = Adk.MakeGuid(); hdr.SIF_SourceId = "ADK Unit Tests"; hdr.SetSIF_Security(new SIF_SecureChannel(AuthenticationLevel.ZERO, EncryptionLevel.ZERO)); hdr.SIF_DestinationId = "Schema Validator"; if (payload is SifDataObject) { SIF_ObjectData data = new SIF_ObjectData(); data.AddChild(payload); rsp.SIF_ObjectData = data; } else if (payload is SIF_ObjectData) { rsp.SIF_ObjectData = (SIF_ObjectData)payload; } else { throw new ArgumentException("Unable to use payload: " + payload.ElementDef.Name); } return(rsp); }
//public string Send(string msg) //{ // lock (this) // { // fMessages.AddLast(msg); // } // return makeAck(); //} public IMessageInputStream Send( IMessageOutputStream msg ) { lock ( this ) { try { MemoryStream stream = new MemoryStream(); msg.CopyTo( stream ); stream.Seek( 0, SeekOrigin.Begin ); SifParser parser = SifParser.NewInstance(); SifMessagePayload smp = (SifMessagePayload) parser.Parse( stream, fZone ); fMessages.Add( smp ); parser = null; SIF_Ack ack = smp.ackStatus( 0 ); SIF_Header hdr = ack.Header; hdr.SIF_Timestamp = DateTime.Now; hdr.SIF_MsgId = Adk.MakeGuid(); hdr.SIF_SourceId = fZone.Agent.Id; StringWriter str = new StringWriter(); SifWriter writer = new SifWriter( str ); writer.Write( ack ); writer.Flush(); writer.Close(); writer = null; return new MessageStreamImpl( str.ToString() ); } catch( Exception ex ) { // Possible error parsing. Write the message to console out Console.Out.WriteLine(msg.Decode()); throw new AdkMessagingException(ex.Message, fZone, ex); } } }
public void TestWriteXSIType() { StudentPersonal sp = new StudentPersonal(); sp.RefId = Adk.MakeGuid(); sp.StateProvinceId = "\u06DE55889"; sp.LocalId = "987987987987987"; SIF_ExtendedElement see = new SIF_ExtendedElement("FOO", "BAR"); see.XsiType = "Integer"; sp.SIFExtendedElementsContainer.Add(see); Console.WriteLine(sp.ToXml()); StudentPersonal copy = (StudentPersonal)AdkObjectParseHelper.WriteParseAndReturn(sp, SifVersion.LATEST, null, true); see = copy.SIFExtendedElements[0]; Assert.IsNotNull(see); Assert.AreEqual("Integer", see.XsiType); }
/// <summary> Respond to SIF RequestsGetTopicMap /// </summary> public virtual void OnRequest(IDataObjectOutputStream outStream, Query query, IZone zone, IMessageInfo inf) { SifMessageInfo info = (SifMessageInfo)inf; SifWriter debug = new SifWriter(Console.Out); Console.WriteLine ("Received a request for " + query.ObjectTag + " from agent \"" + info.SourceId + "\" in zone " + zone.ZoneId); // Read all students from the database to populate a HashMap of // field/value pairs. The field names can be whatever we choose as long // as they match the field names used in the <mappings> section of the // agent.cfg configuration file. Each time a record is read, convert it // to a StudentPersonal object using the Mappings class and stream it to // the supplied output stream. // IDbCommand command = null; // Set a basic filter on the outgoing data stream // What will happen is that any object written to the output stream will // be evaluated based on the query conditions. If the object doesn't meet the // query conditions, it will be excluded outStream.Filter = query; // Get the root Mappings object from the configuration file Edustructures.SifWorks.Tools.Mapping.Mappings m = fCfg.Mappings.GetMappings("Default"); // Ask the root Mappings instance to select a Mappings from its // hierarchy. For example, you might have customized the agent.cfg // file with mappings specific to zones, versions of SIF, or // requesting agents. The Mappings.select() method will select // the most appropriate instance from the hierarchy given the // three parameters passed to it. // //IDictionary<string, string> dataMap = new System.Collections.Generic.Dictionary<string, string>(); // IFieldAdaptor adaptor = new StringMapAdaptor(dataMap); //m.MapOutbound(); MappingsContext mc = m.SelectOutbound(StudentDTD.STUDENTPERSONAL, info); try { int count = 0; // Query the database for all students command = fConn.CreateCommand(); fConn.Open(); command.CommandText = "SELECT * FROM Students"; using (IDataReader rs = command.ExecuteReader(CommandBehavior.CloseConnection)) { DataReaderAdaptor dra = new DataReaderAdaptor(rs); while (rs.Read()) { // Finally, create a new StudentPersonal object and ask the // Mappings to populate it with SIF elements from the HashMap // of field/value pairs. As long as there is an <object>/<field> // definition for each entry in the HashMap, the ADK will take // care of producing the appropriate SIF element/attribute in // the StudentPersonal object. // StudentPersonal sp = new StudentPersonal(); sp.RefId = Adk.MakeGuid(); // TODO: When using custom macros for outboud mapping operations, set the ValueBuilder. // You will need to call SetValueBuilder() giving the MappingsContext a derived version // of DefaultValueBuilder that has the macro methods available in it. mc.SetValueBuilder(new DataUtilMacro(dra)); mc.Map(sp, dra); // Now write out the StudentPersonal to the output stream and // we're done publishing this student. // Console.WriteLine("\nThe agent has read these values from the database:"); DumpFieldsToConsole(rs); Console.WriteLine("To produce this StudentPersonal object:"); debug.Write(sp); debug.Flush(); outStream.Write(sp); } rs.Close(); } Console.WriteLine ("- Returned " + count + " records from the Student database in response"); } catch (Exception ex) { Console.WriteLine("- Returning a SIF_Error response: " + ex); throw new SifException (SifErrorCategoryCode.RequestResponse, SifErrorCodes.REQRSP_GENERIC_ERROR_1, "An error occurred while querying the database for students", ex.ToString(), zone); } finally { if (command != null) { try { fConn.Close(); } catch (Exception ignored) { Log.Warn(ignored.Message, ignored); } } } }
public void testSifResponseSender010() { string queryStr = @"<SIF_Query> <SIF_QueryObject ObjectName='SectionInfo'> <SIF_Element>@RefId</SIF_Element> <SIF_Element>@SchoolCourseInfoRefId</SIF_Element> <SIF_Element>@SchoolYear</SIF_Element> <SIF_Element>LocalId</SIF_Element> <SIF_Element>ScheduleInfoList/ScheduleInfo/@TermInfoRefId</SIF_Element> <SIF_Element>Description</SIF_Element> <SIF_Element>LanguageOfInstruction</SIF_Element> <SIF_Element>LanguageOfInstruction/Code</SIF_Element> </SIF_QueryObject> </SIF_Query>"; string sectionInfoStr = @"<SectionInfo RefId='D9C9889878144863B190C7D3428D7953' SchoolCourseInfoRefId='587F89D23EDD4761A59C04BA0D39E8D9' SchoolYear='2008'> <LocalId>1</LocalId> <Description>section 19</Description> <ScheduleInfoList> <ScheduleInfo TermInfoRefId='0D8165B1ADB34780BD1DFF9E38A7B935'> <TeacherList> <StaffPersonalRefId>F9D3916707634682B84C530BCF96B5CA</StaffPersonalRefId> </TeacherList> <SectionRoomList> <RoomInfoRefId>EED167D761CD493EA94A875F56ABB0CB</RoomInfoRefId> </SectionRoomList> <MeetingTimeList> <MeetingTime> <TimetableDay>R</TimetableDay> <TimetablePeriod>6</TimetablePeriod> </MeetingTime> <MeetingTime> <TimetableDay>F</TimetableDay> <TimetablePeriod>6</TimetablePeriod> </MeetingTime> <MeetingTime> <TimetableDay>W</TimetableDay> <TimetablePeriod>6</TimetablePeriod> </MeetingTime> <MeetingTime> <TimetableDay>M</TimetableDay> <TimetablePeriod>6</TimetablePeriod> </MeetingTime> <MeetingTime> <TimetableDay>T</TimetableDay> <TimetablePeriod>6</TimetablePeriod> </MeetingTime> </MeetingTimeList> </ScheduleInfo> </ScheduleInfoList> <MediumOfInstruction><Code>0605</Code></MediumOfInstruction> <LanguageOfInstruction><Code>eng</Code></LanguageOfInstruction> <SummerSchool>No</SummerSchool> </SectionInfo>"; SifParser parser = SifParser.NewInstance(); SIF_Query sifquery = (SIF_Query)parser.Parse(queryStr); SectionInfo section = (SectionInfo)parser.Parse(sectionInfoStr); Query query = new Query(sifquery); String SifRequestMsgId = Adk.MakeGuid(); String sourceId = "TEST_SOURCEID"; SifVersion testVersion = SifVersion.LATEST; int maxBufferSize = int.MaxValue; MessageDispatcher testDispatcher = new MessageDispatcher(Zone); Zone.SetDispatcher(testDispatcher); Zone.Connect(ProvisioningFlags.None); InMemoryProtocolHandler testProto = (InMemoryProtocolHandler)Zone.ProtocolHandler; testProto.clear(); SifResponseSender srs = new SifResponseSender(); srs.Open(Zone, SifRequestMsgId, sourceId, testVersion, maxBufferSize, query); srs.Write(section); srs.Close(); // 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(1, response.SIF_PacketNumber.Value); Assert.AreEqual("No", response.SIF_MorePackets); SIF_Header header = response.SIF_Header; Assert.AreEqual(sourceId, header.SIF_DestinationId); SifDataObject responseObject = (SifDataObject)response.SIF_ObjectData.GetChildList()[0]; Assert.IsNotNull(responseObject); Console.Out.WriteLine(responseObject.ToXml()); SifXPathContext context = SifXPathContext.NewSIFContext(responseObject); foreach (ElementRef reference in query.FieldRestrictionRefs) { Element found = context.GetElementOrAttribute(reference.XPath); Assert.IsNotNull(found, reference.XPath); } Element sectionInfoList = responseObject.GetElementOrAttribute("ScheduleInfoList/ScheduleInfo/SectionInfoList"); Assert.IsNull(sectionInfoList); }
public void testWithLegacyFile() { //assertStoredRequests(fRC, true); // Copy the legacy requests.adk file to the agent work directory //FileInfo legacyFile = new FileInfo("requests.adk"); //Assertion.Assert("Saved legacy file does [not?] exist", legacyFile.Exists); //FileInfo copiedFile = new FileInfo(fAgent.HomeDir + Path.DirectorySeparatorChar + "work" + Path.DirectorySeparatorChar + "requests.adk"); //if (copiedFile.Exists) //{ // copiedFile.Delete(); //} //// Copy the file //legacyFile.CopyTo(copiedFile.FullName, true); // Now open up an instance of the request cache and verify that the contents are there fRC = RequestCache.GetInstance(fAgent); SIF_QueryObject obj = new SIF_QueryObject(""); SIF_Query query = new SIF_Query(obj); SIF_Request request = new SIF_Request(); request.SIF_Query = query; Query q; TestState ts; fMsgIds = new String[10]; fStateObjects = new String[10]; // Add 10 entries to the cache for (int i = 0; i < 10; i++) { ts = new TestState(); ts.State = Adk.MakeGuid(); fStateObjects[i] = (String) ts.State; q = new Query(StudentDTD.STUDENTPERSONAL); q.UserData = ts; fMsgIds[i] = Adk.MakeGuid(); storeRequest(fRC, request, q, fMsgIds[i], "Object_" + i.ToString()); } Assertion.AssertEquals("Active request count", 10, fRC.ActiveRequestCount); // Lookup each setting, for (int i = 0; i < 10; i++) { IRequestInfo reqInfo = fRC.LookupRequestInfo(fMsgIds[i], null); Assertion.AssertEquals("Initial lookup", "Object_" + i.ToString(), reqInfo.ObjectType); } // Lookup each setting, for (int i = 0; i < 10; i++) { IRequestInfo reqInfo = fRC.GetRequestInfo(fMsgIds[i], null); Assertion.AssertEquals("Initial lookup", "Object_" + i.ToString(), reqInfo.ObjectType); } // all messages should now be removed from the queue Assertion.AssertEquals("Cache should be empty", 0, fRC.ActiveRequestCount); // Now run one of our other tests testPersistence(); }
public void testSifResponseSenderError() { MessageDispatcher testDispatcher = new MessageDispatcher(Zone); 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; SIF_Error error = new SIF_Error(SifErrorCategoryCode.Generic, SifErrorCodes.GENERIC_GENERIC_ERROR_1, "ERROR", "EXT_ERROR"); 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(error); srs.Close(); // 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(1, response.SIF_PacketNumber.Value); 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); // now test the error packet response = (SIF_Response)testProto.readMsg(); Assert.AreEqual(SifRequestMsgId, response.SIF_RequestMsgId); Assert.AreEqual(2, response.SIF_PacketNumber.Value); Assert.AreEqual("No", response.SIF_MorePackets); header = response.SIF_Header; Assert.AreEqual(sourceId, header.SIF_DestinationId); Assert.IsNull(response.SIF_ObjectData); SIF_Error respError = response.SIF_Error; Assert.IsNotNull(respError); Assert.AreEqual(12, respError.SIF_Category.Value); Assert.AreEqual(1, respError.SIF_Code.Value); Assert.AreEqual("ERROR", respError.SIF_Desc); Assert.AreEqual("EXT_ERROR", respError.SIF_ExtendedDesc); }
/// <summary> Respond to SIF Requests /// </summary> public virtual void OnRequest(IDataObjectOutputStream outStream, Query query, IZone zone, IMessageInfo inf) { SifMessageInfo info = (SifMessageInfo)inf; SifWriter debug = new SifWriter(Console.Out); Console.WriteLine ("Received a request for " + query.ObjectTag + " from agent \"" + info.SourceId + "\" in zone " + zone.ZoneId); // Tell the ADK to automatically filter out any objects that don't meet the requirements // of the query conditions outStream.Filter = query; // Read all learners from the database to populate a HashMap of // field/value pairs. The field names can be whatever we choose as long // as they match the field names used in the <mappings> section of the // agent.cfg configuration file. Each time a record is read, convert it // to a LearnerPersonal object using the Mappings class and stream it to // the supplied output stream. // IDictionary data = new Hashtable(); IDbCommand command = null; Console.WriteLine("The SIF Request was requested in the following SIF Versions"); foreach (SifVersion version in info.SIFRequestVersions) { Console.WriteLine(" - " + version); } Console.WriteLine("This agent will respond in its latest supported version, which is: "); Console.WriteLine(" - " + info.LatestSIFRequestVersion); // Get the root Mappings object from the configuration file Mappings m = fCfg.Mappings.GetMappings("Default").Select (info.SourceId, zone.ZoneId, info.LatestSIFRequestVersion); // Ask the root Mappings instance to select a Mappings from its // hierarchy. For example, you might have customized the agent.cfg // file with mappings specific to zones, versions of SIF, or // requesting agents. The Mappings.selectOutbound() method will select // the most appropriate instance from the hierarchy given the // three parameters passed to it. MappingsContext mappings = m.SelectOutbound(StudentDTD.STUDENTPERSONAL, info); try { int count = 0; // Query the database for all students command = fConn.CreateCommand(); fConn.Open(); command.CommandText = "SELECT * FROM Students"; using (IDataReader rs = command.ExecuteReader(CommandBehavior.CloseConnection)) { DataReaderAdaptor dra = new DataReaderAdaptor(rs); while (rs.Read()) { count++; // Finally, create a new LearnerPersonal object and ask the // Mappings to populate it with SIF elements from the HashMap // of field/value pairs. As long as there is an <object>/<field> // definition for each entry in the HashMap, the ADK will take // care of producing the appropriate SIF element/attribute in // the LearnerPersonal object. // StudentPersonal sp = new StudentPersonal(); sp.RefId = Adk.MakeGuid(); mappings.Map(sp, dra); // Now write out the LearnerPersonal to the output stream and // we're done publishing this student. // Console.WriteLine("\nThe agent has read these values from the database:"); DumpDictionaryToConsole(data); Console.WriteLine("To produce this LearnerPersonal object:"); debug.Write(sp); debug.Flush(); outStream.Write(sp); data.Clear(); } rs.Close(); } Console.WriteLine ("- Returned " + count + " records from the Student database in response"); } catch (Exception ex) { Console.WriteLine("- Returning a SIF_Error response: " + ex.ToString()); throw new SifException (SifErrorCategoryCode.RequestResponse, SifErrorCodes.REQRSP_GENERIC_ERROR_1, "An error occurred while querying the database for students", ex.ToString(), zone); } finally { if (command != null) { try { fConn.Close(); } catch (Exception ignored) { } } } }