public void testSubjectAreaSIF15r1() { Adk.SifVersion = SifVersion.SIF15r1; SchoolCourseInfo sci = new SchoolCourseInfo(); SubjectAreaList lst = new SubjectAreaList(); sci.SubjectAreaList = lst; SubjectArea sa = new SubjectArea( "13" ); sa.TextValue = "Graphic Arts"; // for SIF 1.x ??? OtherCodeList ocl = new OtherCodeList(); ocl.Add( new OtherCode( Codeset.TEXT, "Graphic Arts" ) ); sa.OtherCodeList = ocl; lst.Add( sa ); StringWriter sw = new StringWriter(); SifWriter sifw = new SifWriter( sw ); sifw.Write( sci ); sifw.Flush(); sifw.Close(); String xml = sw.ToString(); Console.WriteLine( xml ); int found = xml.IndexOf( ">Graphic Arts</SubjectArea>" ); Assertion.Assert( found > -1 ); }
/// <summary> Returns the XML representation of this SIF Data Object</summary> public virtual string ToXml() { using (StringWriter buffer = new StringWriter()) { SifWriter w = new SifWriter(buffer); w.Write(this); w.Flush(); return(buffer.ToString()); } }
/** * 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 ); } }
/// <summary> Called by the Adk to construct a SifMessageInfo</summary> /// <param name="msg">The SIF_Message /// </param> /// <param name="zone">The associated zone /// </param> public SifMessageInfo(SifMessagePayload msg, IZone zone) { fZone = zone; fPayload = Adk.Dtd.GetElementType(msg.ElementDef.Name); if (zone.Properties.KeepMessageContent) { try { StringWriter sw = new StringWriter(); SifWriter writer = new SifWriter(sw); writer.Write(msg); writer.Flush(); writer.Close(); sw.Close(); fMessage = sw.ToString(); } catch { // Do nothing } } // Set SIF_Header values fHeader = msg.Header; IList <SifContext> contexts = msg.SifContexts; fContexts = new SifContext[contexts.Count]; contexts.CopyTo(fContexts, 0); // Set information about the message payload fPayloadVersion = msg.SifVersion; switch (fPayload) { case SifMessageType.SIF_Request: { SIF_Request req = (SIF_Request)msg; fObjects["SIF_MaxBufferSize"] = req.SIF_MaxBufferSize; fObjects["SIF_RequestVersions"] = req.parseRequestVersions(fZone.Log); } break; case SifMessageType.SIF_Response: { SIF_Response rsp = (SIF_Response)msg; this.SIFRequestMsgId = rsp.SIF_RequestMsgId; fObjects["SIF_PacketNumber"] = rsp.SIF_PacketNumber; SetAttribute("SIF_MorePackets", rsp.SIF_MorePackets); } break; } }
public void CreateElementOrAttribute() { String firstName = "Rosemary"; String middleName = null; String lastName = "Evans"; StudentPersonal retval = new StudentPersonal(); retval.SetElementOrAttribute("Name[@Type='04']/FirstName", firstName); retval.SetElementOrAttribute("Name[@Type='04']/MiddleName", middleName); retval.SetElementOrAttribute("Name[@Type='04']/LastName", lastName); Name name = retval.Name; Assert.AreEqual(firstName, name.FirstName, "First Name"); Assert.AreEqual(lastName, name.LastName, "Last Name"); Assert.IsNull(name.MiddleName, "Middle Name"); // echo to the console so we can see what's going on SifWriter writer = new SifWriter(Console.Out); writer.Write(retval); writer.Flush(); }
/// <summary> /// Returns the XML representation of this Query in the format required by SIF /// for the specified version /// </summary> /// <param name="version">The SIF Version to render the Query in. The ADK will attempt to render /// the query path using the proper element or attribute names for the version of SIF /// </param> /// <returns>a string containing the XML representation as a SIF_Query element. If an error /// occurs during the conversion, an empty string ("") is returned. /// </returns> public String ToXml(SifVersion version) { // Create a SIF_Query object SIF_Query sifQ = SIFPrimitives.CreateSIF_Query(this, version, true); try { using (StringWriter outStream = new StringWriter()) { SifWriter w = new SifWriter(outStream); w.Write(sifQ); w.Flush(); return(outStream.ToString()); } } catch (Exception e) { Adk.Log.Warn("Error creating XML equivalent of Query: " + e, e); return(""); } }
public void CustomSIFElementEncoding() { SIF_Query q = new SIF_Query(); q.SIF_QueryObject = new SIF_QueryObject( StudentDTD.STUDENTPERSONAL.Name ); SIF_Conditions conditions = new SIF_Conditions( ConditionType.NONE ); conditions.AddSIF_Condition( "Name[@Type=\"05\"]/LastName", Operators.EQ, "Cookie" ); q.SetSIF_ConditionGroup( ConditionType.NONE, conditions ); string xml; using ( StringWriter w = new StringWriter() ) { SifWriter writer = new SifWriter( w ); writer.Write( q ); writer.Flush(); writer.Close(); xml = w.ToString(); } Console.WriteLine( xml ); // Mainly, just check to make sure that the single quotes didn't get encoded int index = xml.IndexOf( """ ); Assert.AreEqual( -1, index, "Single quotes should not be encoded" ); }
//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); } } }
/// <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 ) { } } } }
/// <summary> /// Returns the XML representation of this Query in the format required by SIF /// for the specified version /// </summary> /// <param name="version">The SIF Version to render the Query in. The ADK will attempt to render /// the query path using the proper element or attribute names for the version of SIF /// </param> /// <returns>a string containing the XML representation as a SIF_Query element. If an error /// occurs during the conversion, an empty string ("") is returned. /// </returns> public String ToXml(SifVersion version) { // Create a SIF_Query object SIF_Query sifQ = SIFPrimitives.CreateSIF_Query(this, version, true); try { using (StringWriter outStream = new StringWriter()) { SifWriter w = new SifWriter(outStream); w.Write(sifQ); w.Flush(); return outStream.ToString(); } } catch (Exception e) { Adk.Log.Warn("Error creating XML equivalent of Query: " + e, e); return ""; } }
private void Log(string fileName, IDataObjectInputStream input, SifMessageInfo info, bool logToConsole) { try { // Ensure that the directory is there FileInfo file = new FileInfo(fileName); file.Directory.Create(); int numObjects = 0; using (Stream outStream = File.OpenWrite(fileName)) { using (TextWriter twriter = new StreamWriter(outStream, Encoding.UTF8)) { twriter.WriteLine("<SIF_ObjectData>"); twriter.Flush(); SifWriter writer = new SifWriter(twriter); SifWriter consoleWriter = null; if (logToConsole) { consoleWriter = new SifWriter(Console.Out); } SifDataObject o; while ((o = input.ReadDataObject()) != null) { numObjects++; Track(o); writer.Write(o); if (logToConsole) { consoleWriter.Write(o); Console.WriteLine(); } } writer.Flush(); if (logToConsole) { consoleWriter.Flush(); } twriter.WriteLine("</SIF_ObjectData>"); } outStream.Close(); Console.WriteLine ("Received {0} objects for {1}, Packet# {2}", numObjects, input.ObjectType.Name, info.PacketNumber); } } catch (Exception ex) { Adk.Log.Error(ex.Message, ex); } }
/// <summary> Returns the XML representation of this SIF Data Object</summary> public virtual string ToXml() { using ( StringWriter buffer = new StringWriter() ) { SifWriter w = new SifWriter( buffer ); w.Write( this ); w.Flush(); return buffer.ToString(); } }
private bool RunSingleTest( SifVersion parseVersion, SifVersion writeVersion, string fileName, TextWriter output, SchemaValidator sv) { sv.Clear(); if (VERBOSE) { output.Write("Running test on " + fileName + "\r\n"); } // 1) Read the object into memory SifElement se = null; try { se = AdkObjectParseHelper.ParseFile(fileName, parseVersion); } catch (AdkException adke) { // Parsing failed. However, since this unit test is a complete // test of all available objects, just emit the problem and allow // the test to continue (with a notification of false) output .WriteLine("Error parsing file " + fileName + "\r\n - " + adke); output.WriteLine(); return false; } catch (Exception re) { output.WriteLine("Error parsing file " + fileName + "\r\n - " + re); output.WriteLine(); return false; } // if (VERBOSE) // { // SifWriter writer = new SifWriter(output); // writer.Write(se,parseVersion); // output.Flush(); // } // Before we can validate with the schema, we need to ensure that the // data object is wrapped in a SIF_Message elements, because the SIF // Schema makes that assumption SifMessagePayload smp = SchemaValidator.MakeSIFMessagePayload(se); String tmpFileName = fileName + "." + writeVersion.ToString() + ".adk"; // 2) Write the message out to a file try { SchemaValidator.WriteObject( writeVersion, tmpFileName, smp ); } catch( Exception ex ) { Console.WriteLine( "Error running test on {0}. {1}", tmpFileName, ex ); return false; } // 3) Validate the file bool validated = sv.Validate(tmpFileName); // 4) If validation failed, write the object out for tracing purposes if (!validated) { if (VERBOSE) { SifWriter outWriter = new SifWriter(output); outWriter.Write(se, writeVersion ); outWriter.Flush(); } output.WriteLine("Validation failed on " + tmpFileName ); sv.PrintProblems(output); return false; } // 5) Read the object again into memory try { se = AdkObjectParseHelper.ParseFile(fileName, parseVersion); } catch (AdkException adke) { // Parsing failed. However, since this unit test is a complete // test of all available objects, just emit the problem and allow // the test to continue (with a notification of false) output.WriteLine("Error parsing file " + fileName + ": " + adke.Message ); return false; } catch (Exception re) { output.Write("Error parsing file " + fileName + ": " + re.Message + "\r\n"); return false; } return validated; }
private void AckPush( SIF_Ack ack, AdkHttpResponse response ) { try { // Set SIF_Ack / SIF_Header fields SIF_Header hdr = ack.Header; hdr.SIF_Timestamp = DateTime.Now; hdr.SIF_MsgId = SifFormatter.GuidToSifRefID( Guid.NewGuid() ); hdr.SIF_SourceId = this.Zone.Agent.Id; ack.LogSend( this.Zone.Log ); response.ContentType = SifIOFormatter.CONTENTTYPE; // TODO: This code may need to change. The ADKHttpResponse should not automatically set the content length // and other implementations will not do so. SifWriter w = new SifWriter( response.GetResponseStream() ); w.Write( ack ); w.Flush(); } catch ( Exception thr ) { Console.Out.WriteLine ( "HttpProtocolHandler failed to send SIF_Ack for pushed message (zone=" + this.Zone.ZoneId + "): " + thr ); throw new AdkHttpException ( AdkHttpStatusCode.ServerError_500_Internal_Server_Error, thr.Message, thr ); } }
private static IMessageInputStream makeAck() { SIF_Ack retval = new SIF_Ack(); retval.SIF_Status = new SIF_Status( 0 ); MemoryStream ms = new MemoryStream(); try { SifWriter sifWriter = new SifWriter( ms ); sifWriter.Write( retval ); sifWriter.Flush(); //sifWriter.Close(); MessageStreamImpl imp = new MessageStreamImpl( ms ); return (IMessageInputStream) imp; } catch ( Exception ) { return null; } }
/// <summary> Called by the Adk to construct a SifMessageInfo</summary> /// <param name="msg">The SIF_Message /// </param> /// <param name="zone">The associated zone /// </param> public SifMessageInfo( SifMessagePayload msg, IZone zone ) { fZone = zone; fPayload = Adk.Dtd.GetElementType( msg.ElementDef.Name ); if ( zone.Properties.KeepMessageContent ) { try { StringWriter sw = new StringWriter(); SifWriter writer = new SifWriter( sw ); writer.Write( msg ); writer.Flush(); writer.Close(); sw.Close(); fMessage = sw.ToString(); } catch { // Do nothing } } // Set SIF_Header values fHeader = msg.Header; IList<SifContext> contexts = msg.SifContexts; fContexts = new SifContext[ contexts.Count ]; contexts.CopyTo( fContexts, 0 ); // Set information about the message payload fPayloadVersion = msg.SifVersion; switch ( fPayload ) { case SifMessageType.SIF_Request: { SIF_Request req = (SIF_Request) msg; fObjects["SIF_MaxBufferSize"] = req.SIF_MaxBufferSize; fObjects["SIF_RequestVersions"] = req.parseRequestVersions( fZone.Log ); } break; case SifMessageType.SIF_Response: { SIF_Response rsp = (SIF_Response) msg; this.SIFRequestMsgId = rsp.SIF_RequestMsgId; fObjects["SIF_PacketNumber"] = rsp.SIF_PacketNumber; SetAttribute( "SIF_MorePackets", rsp.SIF_MorePackets ); } break; } }
public void WriteSpeedTest() { Adk.Debug = AdkDebugFlags.None; StudentPersonal sp = ObjectCreator.CreateStudentPersonal(); Address addr = sp.AddressLists[0][0]; // Add in a few cases where escaping needs to be done addr.Street.Line1 = "ATTN: \"Miss Thompson\""; addr.Street.Line2 = "321 Dunn & Bradstreeet Lane"; addr.Street.Line3 = "Weyer's Way, MO 32254"; // Dump the object once to the console SifWriter writer = new SifWriter(Console.Out); writer.Write(sp); writer.Flush(); MemoryStream stream = new MemoryStream(); writer = new SifWriter(stream); for (int a = 0; a < 50000; a++) { writer.Write(sp); writer.Flush(); stream.Seek(0, SeekOrigin.Begin); } Console.WriteLine("Test Complete. Please See timings for details"); }