/// <summary>  Create an error SIF_Ack for this message.</summary>
        /// <param name="category">The value of the SIF_Error/SIF_Category element
        /// </param>
        /// <param name="code">The value of the SIF_Error/SIF_Code element
        /// </param>
        /// <param name="desc">The value of the SIF_Error/SIF_Desc element
        /// </param>
        /// <param name="extDesc">The value of the SIF_Error/SIF_ExtendedDesc element
        /// </param>
        /// <returns> A new SIF_Ack instance with a SIF_Error element and SIF_Ack
        /// header values derived from this message's header values
        /// </returns>
        public virtual SIF_Ack AckError(SifErrorCategoryCode category,
                                        int code,
                                        string desc,
                                        string extDesc)
        {
            SIF_Ack ack = new SIF_Ack();

            ack.SIF_OriginalMsgId    = this.MsgId;
            ack.SIF_OriginalSourceId = this.SourceId;
            SIF_Error error = new SIF_Error
                              (
                (int)category,
                code,
                desc ?? "");

            if (extDesc != null)
            {
                error.SIF_ExtendedDesc = extDesc;
            }
            ack.SIF_Error = error;


            //  Ack using the same version of SIF as this message
            ack.SifVersion = SifVersion;

            return(ack);
        }
Example #2
0
 /// <summary>  Constructs an exception to wrap one or more SIF_Errors received from an
 /// inbound SIF_Ack message. This form of constructor is only called by
 /// the Adk.
 /// </summary>
 public SifException(SIF_Ack ack,
                     IZone zone)
     : base(null, zone)
 {
     fAck   = ack;
     fError = ack != null ? ack.SIF_Error : null;
 }
Example #3
0
 private void _checkErrorExists()
 {
     if (fError == null)
     {
         fError = new SIF_Error();
     }
 }
Example #4
0
        public void OnQueryResults(IDataObjectInputStream data,
                                   SIF_Error error,
                                   IZone zone,
                                   IMessageInfo info)
        {
            SifMessageInfo smi = (SifMessageInfo)info;

            if (error != null)
            {
                Adk.Log.Warn("Received Error Response: " + error.SIF_Desc);
            }
            else
            {
                string debug =
                    string.Format
                        ("Received Response for {0} from zone: {1}. Packet {2} of {3}",
                        data.ObjectType, zone.ZoneId, smi.PacketNumber,
                        smi.MorePackets ? smi.PacketNumber + "+" : smi.PacketNumber + " (FINAL)");
                zone.Log.Info(debug);
                zone.ServerLog.Log
                    (LogLevel.INFO, debug, null, "1003", LogEntryCodes.CATEGORY_SUCCESS,
                    LogEntryCodes.CODE_SUCCESS, smi, null);
                bool logToconsole = fAgent.getChameleonProperty(zone, "logConsole", false);
                if (fAgent.getChameleonProperty(zone, "logResponses", true))
                {
                    Log
                        (fDir + Path.DirectorySeparatorChar + zone.ZoneId +
                        Path.DirectorySeparatorChar + "Responses\\" + data.ObjectType.Name + "\\" +
                        data.ObjectType.Name + DateTime.Now.ToFileTime().ToString() + ".xml", data,
                        smi, logToconsole);
                }
            }
        }
Example #5
0
 /// <summary>  Constructs an exception to wrap one or more SIF_Errors received from an
 /// inbound SIF_Ack message. This form of constructor is only called by
 /// the Adk.
 /// </summary>
 public SifException(string msg,
                     SIF_Ack ack,
                     IZone zone)
     : base(msg, zone)
 {
     fAck   = ack;
     fError = ack != null ? ack.SIF_Error : null;
 }
        /// <summary>
        /// This method is called when a response is received to a request made by the Subscriber.
        /// </summary>
        /// <param name="data">The data stream containing the SIF Response.</param>
        /// <param name="error">Error details (if encountered).</param>
        /// <param name="zone">Zone that SIF Response was received.</param>
        /// <param name="info">Information on the received message.</param>
        void IQueryResults.OnQueryResults(IDataObjectInputStream data, SIF_Error error, IZone zone, IMessageInfo info)
        {
            int count = 0;

            // Before reading data from a SIF Response, first check to see if an error was returned.
            if (error != null)
            {
                // The provider returned an error message for this SIF Request.
                if (log.IsErrorEnabled)
                {
                    log.Error("An error was received from the provider of " + SifObjectType.Name + ".");
                }
                if (log.IsErrorEnabled)
                {
                    log.Error(error.SIF_Desc + "\r\n" + error.SIF_ExtendedDesc);
                }
                return;
            }

            // Now, read each object from the DataObjectInputStream until Available returns false.
            while (data.Available)
            {
                count++;
                T sifDataObject = (T)data.ReadDataObject();

                if (PreProcessResponse(sifDataObject, zone))
                {
                    ProcessResponse(sifDataObject, zone);
                }
            }

            // Print out the total number of objects recieved.
            if (log.IsInfoEnabled)
            {
                log.Info(count + " total objects received.");
            }

            // To determine if you have completed receiving all responses, check the
            // MorePackets property of the SIFMessageInfo object
            if (((SifMessageInfo)info).MorePackets)
            {
                if (log.IsInfoEnabled)
                {
                    log.Info("Waiting for more packets...");
                }
            }
            else
            {
                if (log.IsInfoEnabled)
                {
                    log.Info("All requested packets have been received.");
                }
            }
        }
Example #7
0
        public void OnQueryResults(IDataObjectInputStream data, SIF_Error error, IZone zone, IMessageInfo info)
        {
            SifMessageInfo smi = (SifMessageInfo)info;

            fResultsRequestInfo = smi.SIFRequestInfo;
            doBehavior(zone);

            Assert.IsNotNull(fResultsRequestInfo, "RequestInfo should not be null in onQueryResults()");
            if (RequestStateObject != null)
            {
                Assert.AreEqual(RequestStateObject, fResultsRequestInfo.UserData, "Custom State in onQueryResults()");
            }
        }
Example #8
0
 /// <summary>
 /// Constructs a SifException for delivery to the ZIS
 /// </summary>
 /// <param name="category">A <c>SifErrorCategoryCode.</c> error category</param>
 /// <param name="code">A <c>SifErrorCodes</c> error code</param>
 /// <param name="desc">The error description</param>
 /// <param name="extDesc">An option extended error description</param>
 /// <param name="zone">The zone on which the error occurred</param>
 /// <param name="innerException">The internal error that was thrown by the agent</param>
 /// <remarks>
 ///  The Adk will include
 /// the error information provided by the exception when it sends a SIF_Ack
 /// in response to the message being processed. This form of constructor is
 /// typically called by the Adk, but may also be called by agent code if an
 /// exception occurs in a <c>IPublisher</c>, <c>ISubscriber</c>, or <c>IQueryResults</c>
 /// message handler implementation.
 /// </remarks>
 public SifException(SifErrorCategoryCode category,
                     int code,
                     string desc,
                     string extDesc,
                     IZone zone,
                     Exception innerException)
     : base(desc, zone, innerException)
 {
     fAck   = null;
     fError = new SIF_Error((int)category, code, desc == null ? "" : desc);
     if (extDesc != null)
     {
         fError.SIF_ExtendedDesc = extDesc;
     }
 }
Example #9
0
        public void OnQueryResults(IDataObjectInputStream data,
                                   SIF_Error error,
                                   IZone zone,
                                   IMessageInfo info)
        {
            SifMessageInfo smi = (SifMessageInfo)info;

            if (!(fRequestState.Equals(smi.SIFRequestInfo.UserData)))
            {
                // This is a SIF_ZoneStatus response from a previous invocation of the agent
                return;
            }
            if (data.Available)
            {
                SIF_ZoneStatus zoneStatus = data.ReadDataObject() as SIF_ZoneStatus;
                AsyncUtils.QueueTaskToThreadPool(new zsDelegate(_processSIF_ZoneStatus), zoneStatus, zone);
            }
        }
Example #10
0
        public void TestSerializeable()
        {
            MemoryStream    ms        = new MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();

            //************************************************************************
            //Serialize / Deserialize Name object                           **********
            Name name = new Name(NameType.LEGAL, "Nahorniak", "Mike");
            Name result;

            formatter.Serialize(ms, name);
            ms.Seek(0, SeekOrigin.Begin);
            result = (Name)formatter.Deserialize(ms);
            Assert.AreEqual(name.FirstName, result.FirstName, "Name.FirstName field did not properly deserialize");
            Assert.AreEqual(name.FirstName, result.FirstName, "Name.LastName field did not properly deserialize");

            //************************************************************************
            //Serialize / Deserialize StudentPersonal object                **********
            ms.SetLength(0);
            ms.Position = 0;
            StudentPersonal sp = new StudentPersonal();
            StudentPersonal spResult;

            formatter.Serialize(ms, sp);
            ms.Seek(0, SeekOrigin.Begin);
            spResult = (StudentPersonal)formatter.Deserialize(ms);
            Assert.AreEqual(sp.Name, spResult.Name, "Deserialized StudentPersonal Name elements do not match");

            //************************************************************************
            //Serialize / Deserialize SIF_ERROR object                      **********
            ms.SetLength(0);
            ms.Position = 0;
            SIF_Error error = new SIF_Error
                                  ((int)SifErrorCategoryCode.Generic,
                                  SifErrorCodes.GENERIC_GENERIC_ERROR_1,
                                  "Could not serialize the SIF_Err object");
            SIF_Error result_error;

            formatter.Serialize(ms, error);
            ms.Seek(0, SeekOrigin.Begin);
            result_error = (SIF_Error)formatter.Deserialize(ms);
            Assert.AreEqual(error.ToString(), result_error.ToString(), "Deserialized SIF_Error  match");
            ms.Close();
        }
Example #11
0
        public void OnQueryResults(IDataObjectInputStream data,
                                   SIF_Error error,
                                   IZone zone,
                                   IMessageInfo info)
        {
            // Demonstrates basic handling of a SIF_Query response

            // 1)   To read data from a SIF_Response, first check to see if an error was returned
            if (error != null)
            {
                // The provider returned an error message for this SIF_Request
                Console.WriteLine("An error was received from the provider of LearnerPersonal.");
                Console.WriteLine(error.SIF_Desc + "\r\n" + error.SIF_ExtendedDesc);
                return;
            }

            // 2)   Now, read each object from the DataObjectInputStream until available() returns false
            while (data.Available)
            {
                StudentPersonal sp = (StudentPersonal)data.ReadDataObject();
                fObjectCount++;
                Name stuName = sp.Name;
                Console.WriteLine
                    (fObjectCount + ") Refid:{" + sp.RefId +
                    "} Name: " + stuName.FirstName + " " + stuName.LastName);
            }

            // Demonstration purposes only: print out the total number of objects recieved
            Console.WriteLine(fObjectCount + " total objects received.");


            // 3)	To determine if you have completed receiving all responses, check the
            //      MorePackets property of the SIFMessageInfo object
            if (((SifMessageInfo)info).MorePackets)
            {
                Console.WriteLine("Waiting for more packets...");
            }
            else
            {
                Console.WriteLine("All requested packets have been received");
            }
        }
Example #12
0
        /// <summary>
        ///  Attempts to parse attributes out of the source message enough to make a valid
        ///  SIF_Ack with a SIF_Error. This is useful in conditions where the source message cannot
        /// be parsed by the ADK
        /// </summary>
        /// <param name="sourceMessage"> The original message as a string</param>
        /// <param name="error">The error to place in the SIF_Ack/SIF_Error</param>
        /// <param name="zone">The zone associated with this message</param>
        /// <returns></returns>
        /// <exception cref="AdkMessagingException"></exception>
        public static SIF_Ack ackError(String sourceMessage, SifException error, ZoneImpl zone)
        {
            SifMessageInfo parsed = null;

            try
            {
                StringReader reader = new StringReader(sourceMessage);
                parsed = SifMessageInfo.Parse(reader, false, zone);
                reader.Close();
            }
            catch (Exception e)
            {
                zone.Log.Error(e, e);
            }

            SIF_Ack errorAck = new SIF_Ack(zone.HighestEffectiveZISVersion);

            if (parsed != null)
            {
                // Set SIFVersion, OriginalSourceId, and OriginalMsgId;
                if (parsed.SifVersion != null)
                {
                    errorAck.SifVersion = parsed.SifVersion;
                }
                errorAck.SIF_OriginalMsgId    = parsed.GetAttribute("SIF_MsgId");
                errorAck.SIF_OriginalSourceId = parsed.GetAttribute("SIF_SourceId");
            }
            SetRequiredAckValues(errorAck);

            SIF_Error newErr = new SIF_Error();

            newErr.SIF_Category     = (int)error.ErrorCategory;
            newErr.SIF_Code         = error.ErrorCode;
            newErr.SIF_Desc         = error.ErrorDesc;
            newErr.SIF_ExtendedDesc = error.ErrorExtDesc;
            errorAck.SIF_Error      = newErr;

            return(errorAck);
        }
        /// <summary>
        /// Create an error SIF_Ack for this message.
        /// </summary>
        /// <param name="sifEx">The SIFException that is the cause of the error</param>
        /// <returns></returns>
        public SIF_Ack AckError(SifException sifEx)
        {
            SIF_Ack ack = new SIF_Ack();

            ack.message = this;

            ack.SIF_OriginalMsgId    = this.MsgId;
            ack.SIF_OriginalSourceId = this.SourceId;

            SIF_Error error = new SIF_Error(
                sifEx.ErrorCategory,
                sifEx.ErrorCode,
                sifEx.ErrorDesc,
                sifEx.ErrorExtDesc);

            ack.SIF_Error = error;

            //  Ack using the same version of SIF as this message
            ack.SifVersion = this.SifVersion;

            return(ack);
        }
Example #14
0
        /// <summary>  Called when the Publisher.OnQuery method has thrown a SifException,
        /// indicating an error should be returned in the SIF_Response body
        /// </summary>
        public override void SetError(SIF_Error error)
        {
            fError = error;

            //
            //  Write a SIF_Response packet that contains only this SIF_Error
            //
            try
            {
                NewPacket();
                SifWriter writer = new SifWriter(fCurrentOutputStream);
                writer.SuppressNamespace(true);
                writer.Write(error, fRenderAsVersion);
                writer.Close();
            }
            catch (IOException ioe)
            {
                throw new AdkException
                      (
                          "Failed to write Publisher SIF_Error data (packet " + fCurPacket + ") to " +
                          fFile.FullName + ": " +
                          ioe, fZone);
            }
        }
        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);
        }
Example #16
0
 /// <summary>  Called when the Publisher.onQuery method has thrown a SifException,
 /// indicating an error should be returned in the SIF_Response body
 /// </summary>
 public abstract void SetError(SIF_Error error);
Example #17
0
        public void OnQueryResults(IDataObjectInputStream data, SIF_Error error, IZone zone, IMessageInfo info)
        {
            SifMessageInfo smi   = (SifMessageInfo)info;
            DateTime       start = DateTime.Now;

            if (smi.Timestamp.HasValue)
            {
                start = smi.Timestamp.Value;
            }

            Console.WriteLine();
            Console.WriteLine("********************************************* ");
            Console.WriteLine("Received SIF_Response packet from zone" + zone.ZoneId);
            Console.WriteLine("Details... ");
            Console.WriteLine("Request MsgId: " + smi.SIFRequestMsgId);
            Console.WriteLine("Packet Number: " + smi.PacketNumber);
            Console.WriteLine();

            if (error != null)
            {
                Console.WriteLine("The publisher returned an error: ");
                Console.WriteLine("Category: " + error.SIF_Category + " Code: " + error.SIF_Code);
                Console.WriteLine("Description " + error.SIF_Desc);
                if (error.SIF_ExtendedDesc != null)
                {
                    Console.WriteLine("Details: " + error.SIF_ExtendedDesc);
                }
                return;
            }

            try
            {
                int objectCount = 0;
                while (data.Available)
                {
                    SifDataObject next = data.ReadDataObject();
                    objectCount++;
                    Console.WriteLine();
                    Console.WriteLine("Text Values for " + next.ElementDef.Name + " " + objectCount + " {" + next.Key + "}");

                    SifXPathContext context = SifXPathContext.NewSIFContext(next);

                    //	Print out all attributes
                    Console.WriteLine("Attributes:");
                    XPathNodeIterator textNodes = context.Select("//@*");
                    while (textNodes.MoveNext())
                    {
                        XPathNavigator navigator = textNodes.Current;
                        Element        value     = (Element)navigator.UnderlyingObject;
                        IElementDef    valueDef  = value.ElementDef;
                        Console.WriteLine(valueDef.Parent.Tag(SifVersion.LATEST) + "/@" + valueDef.Tag(SifVersion.LATEST) + "=" + value.TextValue + ", ");
                    }
                    Console.WriteLine();
                    // Print out all  elements that have a text value
                    Console.WriteLine("Element:");
                    textNodes = context.Select("//*");
                    while (textNodes.MoveNext())
                    {
                        XPathNavigator navigator = textNodes.Current;
                        Element        value     = (Element)navigator.UnderlyingObject;
                        String         textValue = value.TextValue;
                        if (textValue != null)
                        {
                            IElementDef valueDef = value.ElementDef;
                            Console.WriteLine(valueDef.Tag(SifVersion.LATEST) + "=" + textValue + ", ");
                        }
                    }
                }
                Console.WriteLine();
                Console.WriteLine("Total Objects in Packet: " + objectCount);
            } catch (Exception ex) {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }

            if (!smi.MorePackets)
            {
                // This is the final packet. Print stats
                Console.WriteLine("Final Packet has been received.");
                IRequestInfo ri = smi.SIFRequestInfo;
                if (ri != null)
                {
                    Console.WriteLine("Source Query: ");
                    Console.WriteLine(ri.UserData);
                    TimeSpan difference = start.Subtract(ri.RequestTime);
                    Console.WriteLine("Query execution time: " + difference.Milliseconds + " ms");
                }
            }
            else
            {
                Console.WriteLine("This is not the final packet for this SIF_Response");
            }

            Console.WriteLine("********************************************* ");
            Console.WriteLine( );
            PrintPrompt();
        }
        /// <summary>
        /// Write a SIF_Error to the output stream
        /// </summary>
        /// <param name="error">A SIF_Error instance</param>
        public void Write(SIF_Error error)
        {
            _checkOpen();

            fOut.SetError(error);
        }
Example #19
0
        private void RunLengthTest(Stream[] payloads, bool error, bool replace, SifVersion version)
        {
            // This test loosely emulates what ResponseDelivery does when it builds up the MessageStreamer class
            //  Prepare SIF_Response
            SIF_Response rsp = new SIF_Response();

            rsp.SIF_MorePackets  = "No";
            rsp.SIF_RequestMsgId = "12345123451234512345";
            rsp.SIF_PacketNumber = 1;

            rsp.SifVersion = version;

            //  Write an empty "<SIF_ObjectData> </SIFObjectData>" for the
            //  MessageStreamer to fill in. If this is an errorPacket, the empty
            //  element is required per SIF Specifications.
            SIF_ObjectData placeholder = new SIF_ObjectData();

            placeholder.TextValue = " ";
            rsp.SIF_ObjectData    = placeholder;

            if (error)
            {
                SIF_Error err = new SIF_Error();
                err.TextValue = " ";
                rsp.SIF_Error = err;
            }


            //  Assign values to message header - this is usually done by
            //  MessageDispatcher.send() but because we're preparing a SIF_Response
            //  output stream we need to do it manually
            SIF_Header hdr = rsp.Header;

            hdr.SIF_Timestamp     = DateTime.Now;
            hdr.SIF_MsgId         = SifFormatter.GuidToSifRefID(Guid.NewGuid());
            hdr.SIF_SourceId      = "UnitTest";
            hdr.SIF_DestinationId = "123451234512345";

            //  Write SIF_Response -- without its SIF_ObjectData payload -- to a buffer
            using (MemoryStream envelope = new MemoryStream())
            {
                SifWriter writer = new SifWriter(envelope);
                writer.Write(rsp);
                writer.Flush();

                envelope.Seek(0, SeekOrigin.Begin);
                StreamReader reader      = new StreamReader(envelope, Encoding.UTF8);
                String       envelopeStr = reader.ReadToEnd();
                Console.Out.WriteLine(envelopeStr);

                envelope.Seek(0, SeekOrigin.Begin);

                using (
                    MessageStreamer ms =
                        new MessageStreamer(envelope, payloads, error ? "<SIF_Error>" : "<SIF_ObjectData>", replace))
                {
                    AssertMessageStreamer(ms, version);
                }
                envelope.Close();
            }
        }
Example #20
0
        /// <summary>
        /// Sends a specific packet to the zone
        /// </summary>
        /// <param name="file"></param>
        /// <param name="morePackets"></param>
        protected internal virtual void SendPacket(FileInfo file,
                                                   bool morePackets)
        {
            long extraBytes = 0;

            ResponsePacketInfo responsePacket = DeserializeResponseFileName(file.Name);

            /*	If we're processing SIF_ReportObject responses, read the ReportInfo
             *	data from the "requestMsgId.rpt" file
             *
             *  TT 894 - If a SIFException is thrown after the ReportInfo is set on
             *  the ReportObjectStream, then we don't want to include that ReportInfo
             *  in the packet with the error.  In that case, rptInfoReader will be
             *  null and will not be included in the list of payloads below.
             */

            FileStream rptInfoStream = null;

            if (fSrc == ResponseDeliveryType.SIFReportObject && !responsePacket.errorPacket)
            {
                try {
                    FileInfo f =
                        new FileInfo
                            (fWorkDir + Path.DirectorySeparatorChar.ToString() + responsePacket.destinationId + "." +
                            responsePacket.requestMsgId + ".rpt");
                    rptInfoStream = f.OpenRead();
                    extraBytes    = f.Length;
                }
                catch (FileNotFoundException fnfe) {
                    fZone.Log.Debug
                        ("Error sending SIF_ReportObject packet #" + responsePacket.packetNumber + (morePackets ? "" : " (last packet)") + ", file not found: " + fnfe.Message);
                }
            }

            if ((Adk.Debug & AdkDebugFlags.Messaging) != 0)
            {
                fZone.Log.Debug
                    ("Sending " + (responsePacket.errorPacket ? "SIF_Error response" : "SIF_Response") +
                    " packet #" + responsePacket.packetNumber +
                    (morePackets ? "" : " (last packet)"));
            }

            //  Prepare SIF_Response
            SIF_Response rsp = new SIF_Response();

            rsp.SetSIF_MorePackets(morePackets ? YesNo.YES : YesNo.NO);
            rsp.SIF_RequestMsgId = responsePacket.requestMsgId;
            rsp.SIF_PacketNumber = responsePacket.packetNumber;

            //  The SIF_Response is rendered in the same version of SIF as the original SIF_Request
            rsp.SifVersion = responsePacket.version;

            if (responsePacket.errorPacket)
            {
                //  Write an empty "<SIF_Error> </SIF_Error>" for the MessageStreamer
                //  to replace
                SIF_Error err = new SIF_Error();
                err.TextValue = " ";
                rsp.SIF_Error = err;
            }

            if (!responsePacket.errorPacket || responsePacket.version.Major == 1)
            {
                //  Write an empty "<SIF_ObjectData> </SIFObjectData>" for the
                //  MessageStreamer to fill in. If this is an errorPacket, the empty
                //  element is required per the SIF 1.x Specifications, but disallowed
                // in SIF 2.x.
                SIF_ObjectData placeholder = new SIF_ObjectData();
                placeholder.TextValue = " ";
                rsp.SIF_ObjectData    = placeholder;
            }


            //  Assign values to message header - this is usually done by
            //  MessageDispatcher.send() but because we're preparing a SIF_Response
            //  output stream we need to do it manually
            SIF_Header hdr = rsp.Header;

            hdr.SIF_Timestamp     = DateTime.Now;
            hdr.SIF_MsgId         = SifFormatter.GuidToSifRefID(Guid.NewGuid());
            hdr.SIF_SourceId      = fZone.Agent.Id;
            hdr.SIF_Security      = fZone.Dispatcher.secureChannel();
            hdr.SIF_DestinationId = responsePacket.destinationId;

            //  Write SIF_Response -- without its SIF_ObjectData payload -- to a buffer
            using (MemoryStream envelope = new MemoryStream()) {
                SifWriter writer = new SifWriter(envelope);
                writer.Write(rsp);
                writer.Flush();
                envelope.Seek(0, SeekOrigin.Begin);

                FileStream fs = file.OpenRead();
                try {
                    //  Send the SIF_Response as a stream
                    Stream [] payloads;
                    if (fSrc == ResponseDeliveryType.Generic)
                    {
                        payloads = new Stream [] { fs };
                    }
                    else
                    {
                        if (rptInfoStream != null)
                        {
                            payloads = new Stream [] { rptInfoStream, fs };
                        }
                        else
                        {
                            payloads = new Stream [] { fs };
                        }
                    }

                    using (MessageStreamer ms = new MessageStreamer
                                                (
                               envelope,
                               payloads,
                               responsePacket.errorPacket ? "<SIF_Error>" : "<SIF_ObjectData>", responsePacket.errorPacket))
                    {
                        if ((Adk.Debug & AdkDebugFlags.Messaging) != 0)
                        {
                            fZone.Log.Debug("Send SIF_Response");
                        }
                        if ((Adk.Debug & AdkDebugFlags.Messaging_Detailed) != 0)
                        {
                            fZone.Log.Debug("  MsgId: " + rsp.MsgId);
                        }

                        SIF_Ack ack;
                        using (IMessageInputStream ackStream = fZone.ProtocolHandler.Send(ms)) {
                            ack =
                                (SIF_Ack)
                                fParser.Parse
                                    (ackStream.GetInputStream(), fZone, SifParserFlags.None);
                        }
                        if (ack != null)
                        {
                            ack.LogRecv(fZone.Log);
                        }
                    }

                    //  If we get here, the message was sent successfully
                    envelope.Close();

                    for (int i = 0; i < payloads.Length; i++)
                    {
                        payloads[i].Close();
                    }
                    fs.Close();

                    if (DELETE_ON_SUCCESS && file.Exists)
                    {
                        file.Delete();
                    }
                }
                catch (AdkException adke) {
                    AdkUtils._throw(adke, fZone.Log);
                }
                catch (Exception e) {
                    AdkUtils._throw
                        (new AdkException("Failed to send SIF_Response: " + e, fZone), fZone.Log);
                }
                finally {
                    if (fs != null)
                    {
                        fs.Close();
                    }
                    if (rptInfoStream != null)
                    {
                        rptInfoStream.Close();
                    }
                }
            }
        }
Example #21
0
        /// <summary>  Handles SIF_Responses
        /// </summary>
        public virtual void OnQueryResults(IDataObjectInputStream in_Renamed,
                                            SIF_Error error,
                                            IZone zone,
                                            IMessageInfo inf)
        {
            SifMessageInfo info = (SifMessageInfo)inf;

            Console.WriteLine
                ("\nReceived a query response from agent \"" + info.SourceId + "\" in zone " +
                  zone.ZoneId);
            IRequestInfo reqInfo = info.SIFRequestInfo;
            if (reqInfo != null) {
                Console.WriteLine
                    ("\nResponse was received in {0}. Object State is '{1}'",
                      DateTime.Now.Subtract(reqInfo.RequestTime), reqInfo.UserData);
            }

            //
            //  Use the Mappings class to translate the StudentPersonal objects received
            //  from the zone into a HashMap of field/value pairs, then dump the table
            //  to System.out
            //

            //  Always check for an error response
            if (error != null) {
                Console.WriteLine
                    ("The request for StudentPersonal failed with an error from the provider:");
                Console.WriteLine
                    ("  [Category=" + error.SIF_Category + "; Code=" + error.SIF_Code + "]: " +
                      error.SIF_Desc + ". " + error.SIF_ExtendedDesc);
                return;
            }

            //  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.
            //

            SifFormatter textFormatter = Adk.Dtd.GetFormatter(info.SifVersion);
            MappingsContext context =
                m.SelectInbound(StudentDTD.STUDENTPERSONAL, info);

            while (in_Renamed.Available) {
                StudentPersonal sp = (StudentPersonal)in_Renamed.ReadDataObject();

                //  Ask the Mappings object to populate a HashMap with field/value pairs
                //  by using the mapping rules in the configuration file to decompose
                //  the StudentPersonal object into field values.
                //
                Hashtable data = new Hashtable();
                StringMapAdaptor sma = new StringMapAdaptor(data, textFormatter);
                context.Map(sp, sma);

                //  Now dump the field/value pairs to System.out
                DumpDictionaryToConsole(data);
            }
        }
Example #22
0
    /// <summary>  Handles SIF_Responses
    /// </summary>
    public virtual void OnQueryResults(IDataObjectInputStream inStream,
                                       SIF_Error error,
                                       IZone zone,
                                       IMessageInfo inf)
    {
        SifMessageInfo info = (SifMessageInfo)inf;

        Console.WriteLine
            ("\nReceived a query response from agent \"" + info.SourceId + "\" in zone " +
            zone.ZoneId);
        IRequestInfo reqInfo = info.SIFRequestInfo;

        if (reqInfo != null)
        {
            Console.WriteLine
                ("\nResponse was received in {0}. Object State is '{1}'",
                DateTime.Now.Subtract(reqInfo.RequestTime), reqInfo.UserData);
        }

        //
        //  Use the Mappings class to translate the LearnerPersonal objects received
        //  from the zone into a HashMap of field/value pairs, then dump the table
        //  to System.out
        //

        //  Always check for an error response
        if (error != null)
        {
            Console.WriteLine
                ("The request for LearnerPersonal failed with an error from the provider:");
            Console.WriteLine
                ("  [Category=" + error.SIF_Category + "; Code=" + error.SIF_Code + "]: " +
                error.SIF_Desc +
                ". " + error.SIF_ExtendedDesc);
            return;
        }

        //  Get the root Mappings object from the configuration file
        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.
        MappingsContext  mappings = m.SelectInbound(StudentDTD.STUDENTPERSONAL, info);
        Hashtable        data     = new Hashtable();
        StringMapAdaptor sma      = new StringMapAdaptor(data, Adk.Dtd.GetFormatter(SifVersion.LATEST));

        int count = 0;

        while (inStream.Available)
        {
            Console.WriteLine("Object Number {0}", count++);
            StudentPersonal sp = (StudentPersonal)inStream.ReadDataObject();
            //  Ask the Mappings object to populate the dictionary with field/value pairs
            //  by using the mapping rules in the configuration file to decompose
            //  the LearnerPersonal object into field values.
            mappings.Map(sp, sma);
            //  Now dump the field/value pairs to System.out
            DumpDictionaryToConsole(data);
            Console.WriteLine();
            data.Clear();
        }
    }